diff --git a/geo.js b/geo.js
index a34ac9f9e2..89cfba1667 100644
--- a/geo.js
+++ b/geo.js
@@ -12156,83 +12156,86 @@ vgl.DataBuffers = function (initialSize) {
this.data = elem[current];
this.left = null;
this.right = null;
- if (start != current)
- this.left = new RangeNode (elem, start, current - 1, parseInt ((start + (current - 1)) / 2, 10));
- if (end != current)
- this.right = new RangeNode (elem, current + 1, end, parseInt ((end + (current + 1)) / 2, 10));
- this.subtree = [];
- for (var i = start; i <= end; i ++) {
- this.subtree.push (elem[i]);
- }
- this.subtree.sort (function (a, b) {
- return a.y - b.y;
- });
+ if (start !== current)
+ this.left = new RangeNode(elem, start, current - 1, parseInt((start + (current - 1)) / 2, 10));
+ if (end !== current)
+ this.right = new RangeNode(elem, current + 1, end, parseInt((end + (current + 1)) / 2, 10));
+ this.elem = elem;
+ this.start = start;
+ this.end = end;
+ this.subtree = null; /* This is populated as needed */
+ this.search = rangeNodeSearch;
+ };
+
+ var rangeNodeSearch = function (result, box) {
+ var m_this = this;
var xrange = function (b) {
- return (b.x_in (elem[start]) && b.x_in (elem[end]));
+ return (b.x_in(m_this.elem[m_this.start]) &&
+ b.x_in(m_this.elem[m_this.end]));
};
- this.yrange = function (b, start, end) {
- return (b.y_in (this.subtree[start]) && b.y_in (this.subtree[end]));
+ var yrange = function (b, start, end) {
+ return (b.y_in(m_this.subtree[start]) &&
+ b.y_in(m_this.subtree[end]));
};
- this.subquery = function (result, box, start, end, current) {
- if (this.yrange (box, start, end)) {
+ var subquery = function (result, box, start, end, current) {
+ if (yrange(box, start, end)) {
for (var i = start; i <= end; i ++) {
- result.push (this.subtree[i]);
+ result.push(m_this.subtree[i]);
}
return;
}
- if (box.y_in (this.subtree[current]))
- result.push (this.subtree[current]);
- if (box.y_left (this.subtree[current])){
- if (current != end)
- this.subquery (result, box, current + 1, end, parseInt ((end + (current + 1)) / 2, 10));
- }
- else if (box.x_right (this.subtree[current])) {
- if (current != start)
- this.subquery (result, box, start, current - 1, parseInt ((start + (current - 1)) / 2, 10));
- }
- else {
- if (current != end)
- this.subquery (result, box, current + 1, end, parseInt ((end + (current + 1)) / 2, 10));
- if (current != start)
- this.subquery (result, box, start, current - 1, parseInt ((start + (current - 1)) / 2, 10));
+ if (box.y_in(m_this.subtree[current]))
+ result.push(m_this.subtree[current]);
+ if (box.y_left(m_this.subtree[current])){
+ if (current !== end)
+ subquery(result, box, current + 1, end, parseInt((end + (current + 1)) / 2, 10));
+ } else if (box.x_right(m_this.subtree[current])) {
+ if (current !== start)
+ subquery(result, box, start, current - 1, parseInt((start + (current - 1)) / 2, 10));
+ } else {
+ if (current !== end)
+ subquery(result, box, current + 1, end, parseInt((end + (current + 1)) / 2, 10));
+ if (current !== start)
+ subquery(result, box, start, current - 1, parseInt((start + (current - 1)) / 2, 10));
}
};
-
- this.search = function (result, box) {
- if (xrange (box)) {
- this.subquery (result, box, 0, this.subtree.length - 1, parseInt ((this.subtree.length - 1) / 2, 10));
- return;
+
+ if (xrange(box)) {
+ if (!this.subtree) {
+ this.subtree = this.elem.slice(this.start, this.end + 1);
+ this.subtree.sort(function (a, b) {
+ return a.y - b.y;
+ });
}
- else {
- if (box.contains (this.data))
- result.push (this.data);
- if (box.x_left (this.data)) {
- if (this.right)
- this.right.search (result, box);
- }
- else if (box.x_right (this.data)) {
- if (this.left)
- this.left.search (result, box);
- }
- else {
- if (this.left)
- this.left.search (result, box);
- if (this.right)
- this.right.search (result, box);
- }
+ subquery(result, box, 0, this.subtree.length - 1, parseInt((this.subtree.length - 1) / 2, 10));
+ return;
+ } else {
+ if (box.contains(this.data))
+ result.push(this.data);
+ if (box.x_left(this.data)) {
+ if (this.right)
+ this.right.search(result, box);
+ } else if (box.x_right(this.data)) {
+ if (this.left)
+ this.left.search(result, box);
+ } else {
+ if (this.left)
+ this.left.search(result, box);
+ if (this.right)
+ this.right.search(result, box);
}
- };
+ }
};
var RangeTree = function (elem) {
- elem.sort (function (a, b) {
+ elem.sort(function (a, b) {
return a.x - b.x;
});
if (elem.length > 0)
- this.root = new RangeNode (elem, 0, elem.length - 1, parseInt ((elem.length - 1) / 2, 10));
+ this.root = new RangeNode(elem, 0, elem.length - 1, parseInt((elem.length - 1) / 2, 10));
else
this.root = null;
@@ -12289,7 +12292,7 @@ vgl.DataBuffers = function (initialSize) {
this.width = function () {
return this.max.x - this.min.x;
};
-
+
this.vertex = function (index) {
switch (index) {
case 0:
@@ -12404,7 +12407,7 @@ vgl.DataBuffers = function (initialSize) {
return this;
};
this.clone = function () {
- return new Vector2D (this.x, this.y);
+ return new Vector2D (this.x, this.y);
};
this.array = function () {
@@ -12470,7 +12473,7 @@ vgl.DataBuffers = function (initialSize) {
if (denom === 0)
return Infinity;
-
+
var num_s = a.x * (d.y - c.y) +
c.x * (a.y - d.y) +
d.x * (c.y - a.y);
@@ -12480,7 +12483,7 @@ vgl.DataBuffers = function (initialSize) {
b.x * (a.y - c.y) +
c.x * (b.y - a.y));
var t = num_t / denom;
-
+
return t;
};
@@ -12492,7 +12495,7 @@ vgl.DataBuffers = function (initialSize) {
if (denom === 0)
return Infinity;
-
+
var num_s = a.x * (d.y - c.y) +
c.x * (a.y - d.y) +
d.x * (c.y - a.y);
@@ -12502,7 +12505,7 @@ vgl.DataBuffers = function (initialSize) {
b.x * (a.y - c.y) +
c.x * (b.y - a.y));
var t = num_t / denom;*/
-
+
var dir = vect.sub (b, a);
dir.scale (s);
return vect.add (a, dir);
@@ -14772,7 +14775,7 @@ geo.mapInteractor = function (args) {
$node.on('mousemove.geojs', m_this._handleMouseMove);
$node.on('mousedown.geojs', m_this._handleMouseDown);
$node.on('mouseup.geojs', m_this._handleMouseUp);
- $node.on('mousewheel.geojs', m_this._handleMouseWheel);
+ $node.on('wheel.geojs', m_this._handleMouseWheel);
if (m_options.panMoveButton === 'right' ||
m_options.zoomMoveButton === 'right') {
$node.on('contextmenu.geojs', function () { return false; });
@@ -15238,8 +15241,21 @@ geo.mapInteractor = function (args) {
this._handleMouseWheel = function (evt) {
var zoomFactor, direction;
- // In case jquery-mousewheel isn't loaded for some reason
- evt.deltaFactor = evt.deltaFactor || 1;
+ // try to normalize deltas using the wheel event standard:
+ // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
+ evt.deltaFactor = 1;
+ if (evt.originalEvent.deltaMode === 1) {
+ // DOM_DELTA_LINE -- estimate line height
+ evt.deltaFactor = 12;
+ } else if (evt.originalEvent.deltaMode === 2) {
+ // DOM_DELTA_PAGE -- get window height
+ evt.deltaFactor = $(window).height();
+ }
+
+ // If the browser doesn't support the standard then
+ // just set the delta's to zero.
+ evt.deltaX = evt.originalEvent.deltaX || 0;
+ evt.deltaY = evt.originalEvent.deltaY || 0;
m_this._getMouseModifiers(evt);
evt.deltaX = evt.deltaX * m_options.wheelScaleX * evt.deltaFactor / 120;
@@ -15265,13 +15281,13 @@ geo.mapInteractor = function (args) {
m_this.map().pan({
x: evt.deltaX,
- y: evt.deltaY
+ y: -evt.deltaY
});
} else if (m_options.zoomWheelEnabled &&
eventMatch('wheel', m_options.zoomWheelModifiers)) {
- zoomFactor = evt.deltaY;
+ zoomFactor = -evt.deltaY;
direction = m_mouse.map;
m_this.map().zoom(
@@ -15458,9 +15474,11 @@ geo.mapInteractor = function (args) {
ctrlKey: options.modifiers.indexOf('ctrl') >= 0,
metaKey: options.modifiers.indexOf('meta') >= 0,
shiftKey: options.modifiers.indexOf('shift') >= 0,
- deltaX: options.wheelDelta.x,
- deltaY: options.wheelDelta.y,
- deltaFactor: 1
+ originalEvent: {
+ deltaX: options.wheelDelta.x,
+ deltaY: options.wheelDelta.y,
+ deltaMode: options.wheelMode
+ }
}
);
$node.trigger(evt);
@@ -16973,23 +16991,71 @@ geo.map = function (arg) {
////////////////////////////////////////////////////////////////////////////
/**
- * Get the locations of the current map corners as latitudes/longitudes.
- * The return value of this function is an object as follows: ::
+ * Get/set the locations of the current map corners as latitudes/longitudes.
+ * When provided the argument should be an object containing the keys
+ * lowerLeft and upperRight declaring the desired new map bounds. The
+ * new bounds will contain at least the min/max lat/lngs provided. In any
+ * case, the actual new bounds will be returned by this function.
*
- * {
- * lowerLeft: {x: ..., y: ...},
- * upperLeft: {x: ..., y: ...},
- * lowerRight: {x: ..., y: ...},
- * upperRight: {x: ..., y: ...}
- * }
- *
- * @todo Provide a setter
+ * @param {geo.geoBounds} [bds] The requested map bounds
+ * @return {geo.geoBounds} The actual new map bounds
*/
////////////////////////////////////////////////////////////////////////////
- this.bounds = function () {
+ this.bounds = function (bds) {
+ var nav;
+
+ if (bds === undefined) {
+ return m_bounds;
+ }
+
+ nav = m_this.zoomAndCenterFromBounds(bds);
+ m_this.zoom(nav.zoom);
+ m_this.center(nav.center);
return m_bounds;
};
+ ////////////////////////////////////////////////////////////////////////////
+ /**
+ * Get the center zoom level necessary to display the given lat/lon bounds.
+ *
+ * @param {geo.geoBounds} [bds] The requested map bounds
+ * @return {object} Object containing keys "center" and "zoom"
+ */
+ ////////////////////////////////////////////////////////////////////////////
+ this.zoomAndCenterFromBounds = function (bds) {
+ var ll, ur, dx, dy, zx, zy, center;
+
+ // Caveat:
+ // Much of the following is invalid for alternative map projections. These
+ // computations should really be defered to the base layer, but there is
+ // no clear path for doing that with the current base layer api.
+
+ // extract bounds info and check for validity
+ ll = geo.util.normalizeCoordinates(bds.lowerLeft || {});
+ ur = geo.util.normalizeCoordinates(bds.upperRight || {});
+
+ if (ll.x >= ur.x || ll.y >= ur.y) {
+ throw new Error("Invalid bounds provided");
+ }
+
+ center = {
+ x: (ll.x + ur.x) / 2,
+ y: (ll.y + ur.y) / 2
+ };
+
+ // calculate the current extend
+ dx = m_bounds.upperRight.x - m_bounds.lowerLeft.x;
+ dy = m_bounds.upperRight.y - m_bounds.lowerLeft.y;
+
+ // calculate the zoom levels necessary to fit x and y bounds
+ zx = m_zoom - Math.log2((ur.x - ll.x) / dx);
+ zy = m_zoom - Math.log2((ur.y - ll.y) / dy);
+
+ return {
+ zoom: Math.min(zx, zy),
+ center: center
+ };
+ };
this.interactor(arg.interactor || geo.mapInteractor());
this.clock(arg.clock || geo.clock());
@@ -17424,6 +17490,14 @@ geo.feature = function (arg) {
} else {
m_visible = val;
m_this.modified();
+
+ // bind or unbind mouse handlers on visibility change
+ if (m_visible) {
+ m_this._bindMouseHandlers();
+ } else {
+ m_this._unbindMouseHandlers();
+ }
+
return m_this;
}
};
@@ -17664,8 +17738,8 @@ geo.pointFeature = function (arg) {
var m_this = this,
s_init = this._init,
m_rangeTree = null,
+ m_rangeTreeTime = geo.timestamp(),
s_data = this.data,
- s_style = this.style,
m_maxRadius = 0;
////////////////////////////////////////////////////////////////////////////
@@ -17693,6 +17767,9 @@ geo.pointFeature = function (arg) {
*/
////////////////////////////////////////////////////////////////////////////
this._updateRangeTree = function () {
+ if (m_rangeTreeTime.getMTime() >= m_this.dataTime().getMTime()) {
+ return;
+ }
var pts, position,
radius = m_this.style.get("radius"),
stroke = m_this.style.get("stroke"),
@@ -17717,6 +17794,7 @@ geo.pointFeature = function (arg) {
});
m_rangeTree = new geo.util.RangeTree(pts);
+ m_rangeTreeTime.modified();
};
////////////////////////////////////////////////////////////////////////////
@@ -17762,6 +17840,7 @@ geo.pointFeature = function (arg) {
// Find points inside the bounding box
box = new geo.util.Box(geo.util.vect(min.x, min.y), geo.util.vect(max.x, max.y));
+ m_this._updateRangeTree();
m_rangeTree.search(box).forEach(function (q) {
idx.push(q.idx);
});
@@ -17824,20 +17903,6 @@ geo.pointFeature = function (arg) {
return m_this;
};
- ////////////////////////////////////////////////////////////////////////////
- /**
- * Overloaded style method that updates the internal range tree on write.
- */
- ////////////////////////////////////////////////////////////////////////////
- this.style = function (arg1, arg2) {
- var val = s_style(arg1, arg2);
- if (val === m_this && m_this.selectionAPI()) {
- m_this._updateRangeTree();
- }
- return val;
- };
- this.style.get = s_style.get;
-
////////////////////////////////////////////////////////////////////////////
/**
* Returns the bounding box for a given datum in screen coordinates as an
@@ -24779,9 +24844,6 @@ geo.registerWidget('d3', 'legend', geo.gui.legendWidget);
return;
}
- // for multiple initialization detection
- var initialized = false;
-
/**
* Takes an option key and returns true if it should
* return a color accessor.
@@ -24909,7 +24971,7 @@ geo.registerWidget('d3', 'legend', geo.gui.legendWidget);
* renderer: 'vgl',
* features: [{
* type: 'point',
- * size: 5,
+ * radius: 5,
* position: function (d) { return {x: d.geometry.x, y: d.geometry.y} },
* fillColor: function (d, i) { return i < 5 ? 'red' : 'blue' },
* stroke: false
@@ -24925,7 +24987,7 @@ geo.registerWidget('d3', 'legend', geo.gui.legendWidget);
* features: [{
* data: [...],
* type: 'point',
- * size: 5,
+ * radius: 5,
* position: function (d) { return {x: d.geometry.x, y: d.geometry.y} },
* fillColor: function (d, i) { return i < 5 ? 'red' : 'blue' },
* stroke: false
@@ -24991,8 +25053,8 @@ geo.registerWidget('d3', 'legend', geo.gui.legendWidget);
* @property {number} radius
* Radius of the circle in pixels (ignored when size
* is present)
- * @property {number} size
- * A numerical value mapped affinely to a radius in the range [5,20]
+ * @property {function} size
+ * A function returning a numerical value
* @property {boolean} fill Presence or absence of the fill
* @property {color} fillColor Interior color
* @property {float} fillOpacity Opacity of the interior [0,1]
@@ -25050,16 +25112,6 @@ geo.registerWidget('d3', 'legend', geo.gui.legendWidget);
// when called multiple times on a single element, do nothing
return;
}
- if (initialized) {
- // warn when called multiple times on different elements
- console.warn(
- 'Geojs already initialized in this window.'
- );
- // Try to clean up the old gl context, but this doesn't usually work
- delete window.gl;
- }
- // set global initialization state
- initialized = true;
// create the map
this._map = geo.map({
@@ -25121,7 +25173,7 @@ geo.registerWidget('d3', 'legend', geo.gui.legendWidget);
var scl;
if (feature.type === 'point') {
if (feature.size) {
- feature._size = feature.size;
+ feature._size = geo.util.ensureFunction(feature.size);
} else if (feature.size === null) {
delete feature._size;
}
diff --git a/geo.min.js b/geo.min.js
index 7854b4319f..90856a5479 100644
--- a/geo.min.js
+++ b/geo.min.js
@@ -1,13 +1,7 @@
-function inherit(C,P){"use strict";var F=function(){};F.prototype=P.prototype,C.prototype=new F,C.uber=P.prototype,C.prototype.constructor=C}var geo={};if(window.geo=geo,geo.renderers={},geo.features={},geo.fileReaders={},geo.inherit=function(C,P){"use strict";var F=inherit.func();F.prototype=P.prototype,C.prototype=new F,C.prototype.constructor=C},geo.inherit.func=function(){"use strict";return function(){}},window.inherit=geo.inherit,geo.registerFileReader=function(name,func){"use strict";void 0===geo.fileReaders&&(geo.fileReaders={}),geo.fileReaders[name]=func},geo.createFileReader=function(name,opts){"use strict";return geo.fileReaders.hasOwnProperty(name)?geo.fileReaders[name](opts):null},geo.registerRenderer=function(name,func){"use strict";void 0===geo.renderers&&(geo.renderers={}),geo.renderers[name]=func},geo.createRenderer=function(name,layer,canvas){"use strict";if(geo.renderers.hasOwnProperty(name)){var ren=geo.renderers[name]({layer:layer,canvas:canvas});return ren._init(),ren}return null},geo.registerFeature=function(category,name,func){"use strict";void 0===geo.features&&(geo.features={}),category in geo.features||(geo.features[category]={}),geo.features[category][name]=func},geo.createFeature=function(name,layer,renderer,arg){"use strict";var category=renderer.api(),options={layer:layer,renderer:renderer};return category in geo.features&&name in geo.features[category]?(void 0!==arg&&$.extend(!0,options,arg),geo.features[category][name](options)):null},geo.registerLayer=function(name,func){"use strict";void 0===geo.layers&&(geo.layers={}),geo.layers[name]=func},geo.createLayer=function(name,map,arg){"use strict";var options={map:map,renderer:"vgl"},layer=null;return name in geo.layers?(void 0!==arg&&$.extend(!0,options,arg),layer=geo.layers[name](options),layer._init(),layer):null},geo.registerWidget=function(category,name,func){"use strict";void 0===geo.widgets&&(geo.widgets={}),category in geo.widgets||(geo.widgets[category]={}),geo.widgets[category][name]=func},geo.createWidget=function(name,layer,renderer,arg){"use strict";var category=renderer.api(),options={layer:layer,renderer:renderer};return category in geo.widgets&&name in geo.widgets[category]?(void 0!==arg&&$.extend(!0,options,arg),geo.widgets[category][name](options)):null},window.requestAnimationFrame||(window.requestAnimationFrame=function(func){"use strict";window.setTimeout(func,15)}),Math.log2||(Math.log2=function(){"use strict";return Math.log.apply(Math,arguments)/Math.LN2}),geo.version="0.4.2","undefined"==typeof ogs)var ogs={};ogs.namespace=function(ns_string){"use strict";var i,parts=ns_string.split("."),parent=ogs;for("ogs"===parts[0]&&(parts=parts.slice(1)),i=0;ithis.computeBoundsTimestamp().getMTime()&&this.m_parent.boundsDirtyTimestamp.modified(),this.computeBounds(),visitor.mode()===visitor.TraverseAllChildren)for(i=0;ithis.boundsDirtyTimestamp().getMTime()))for(i=0;ii;++i)istep=2*i,jstep=2*i+1,childBounds[istep]bounds[jstep]&&(bounds[jstep]=childBounds[jstep]);this.setBounds(bounds[0],bounds[1],bounds[2],bounds[3],bounds[4],bounds[5])}},this},inherit(vgl.groupNode,vgl.node),vgl.actor=function(){"use strict";if(!(this instanceof vgl.actor))return new vgl.actor;vgl.node.call(this);var m_transformMatrix=mat4.create(),m_referenceFrame=vgl.boundingObject.ReferenceFrame.Relative,m_mapper=null;return this.matrix=function(){return m_transformMatrix},this.setMatrix=function(tmatrix){tmatrix!==m_transformMatrix&&(m_transformMatrix=tmatrix,this.modified())},this.referenceFrame=function(){return m_referenceFrame},this.setReferenceFrame=function(referenceFrame){return referenceFrame!==m_referenceFrame?(m_referenceFrame=referenceFrame,this.modified(),!0):!1},this.mapper=function(){return m_mapper},this.setMapper=function(mapper){mapper!==m_mapper&&(m_mapper=mapper,this.boundsModified())},this.accept=function(){},this.ascend=function(){},this.computeLocalToWorldMatrix=function(){},this.computeWorldToLocalMatrix=function(){},this.computeBounds=function(){if(null===m_mapper||void 0===m_mapper)return void this.resetBounds();var mapperBounds,minPt,maxPt,newBounds,computeBoundsTimestamp=this.computeBoundsTimestamp();(this.boundsDirtyTimestamp().getMTime()>computeBoundsTimestamp.getMTime()||m_mapper.boundsDirtyTimestamp().getMTime()>computeBoundsTimestamp.getMTime())&&(m_mapper.computeBounds(),mapperBounds=m_mapper.bounds(),minPt=[mapperBounds[0],mapperBounds[2],mapperBounds[4]],maxPt=[mapperBounds[1],mapperBounds[3],mapperBounds[5]],vec3.transformMat4(minPt,minPt,m_transformMatrix),vec3.transformMat4(maxPt,maxPt,m_transformMatrix),newBounds=[minPt[0]>maxPt[0]?maxPt[0]:minPt[0],minPt[0]>maxPt[0]?minPt[0]:maxPt[0],minPt[1]>maxPt[1]?maxPt[1]:minPt[1],minPt[1]>maxPt[1]?minPt[1]:maxPt[1],minPt[2]>maxPt[2]?maxPt[2]:minPt[2],minPt[2]>maxPt[2]?minPt[2]:maxPt[2]],this.setBounds(newBounds[0],newBounds[1],newBounds[2],newBounds[3],newBounds[4],newBounds[5]),computeBoundsTimestamp.modified())},this},inherit(vgl.actor,vgl.node),vgl.freezeObject=function(obj){"use strict";var freezedObject=Object.freeze(obj);return"undefined"==typeof freezedObject&&(freezedObject=function(o){return o}),freezedObject},vgl.defaultValue=function(a,b){"use strict";return"undefined"!=typeof a?a:b},vgl.defaultValue.EMPTY_OBJECT=vgl.freezeObject({}),vgl.geojsonReader=function(){"use strict";if(!(this instanceof vgl.geojsonReader))return new vgl.geojsonReader;return this.readScalars=function(coordinates,geom,size_estimate,idx){var array=null,s=null,r=null,g=null,b=null;"values"===this.m_scalarFormat&&4===coordinates.length?(s=coordinates[3],array=geom.sourceData(vgl.vertexAttributeKeys.Scalar),array||(array=new vgl.sourceDataSf,this.m_scalarRange&&array.setScalarRange(this.m_scalarRange[0],this.m_scalarRange[1]),void 0!==size_estimate&&(array.data().length=size_estimate),geom.addSource(array)),void 0===size_estimate?array.pushBack(s):array.insertAt(idx,s)):"rgb"===this.m_scalarFormat&&6===coordinates.length&&(array=geom.sourceData(vgl.vertexAttributeKeys.Color),array||(array=new vgl.sourceDataC3fv,void 0!==size_estimate&&(array.length=3*size_estimate),geom.addSource(array)),r=coordinates[3],g=coordinates[4],b=coordinates[5],void 0===size_estimate?array.pushBack([r,g,b]):array.insertAt(idx,[r,g,b]))},this.readPoint=function(coordinates){var geom=new vgl.geometryData,vglpoints=new vgl.points,vglcoords=new vgl.sourceDataP3fv,indices=new Uint16Array(1),x=null,y=null,z=null,i=null;for(geom.addSource(vglcoords),i=0;1>i;i++)indices[i]=i,x=coordinates[0],y=coordinates[1],z=0,coordinates.length>2&&(z=coordinates[2]),vglcoords.pushBack([x,y,z]),this.readScalars(coordinates,geom);return vglpoints.setIndices(indices),geom.addPrimitive(vglpoints),geom.setName("aPoint"),geom},this.readMultiPoint=function(coordinates){var i,geom=new vgl.geometryData,vglpoints=new vgl.points,vglcoords=new vgl.sourceDataP3fv,indices=new Uint16Array(coordinates.length),pntcnt=0,estpntcnt=coordinates.length,x=null,y=null,z=null;for(vglcoords.data().length=3*estpntcnt,i=0;i2&&(z=coordinates[i][2]),vglcoords.insertAt(pntcnt,[x,y,z]),this.readScalars(coordinates[i],geom,estpntcnt,pntcnt),pntcnt++;return vglpoints.setIndices(indices),geom.addPrimitive(vglpoints),geom.addSource(vglcoords),geom.setName("manyPoints"),geom},this.readLineString=function(coordinates){var geom=new vgl.geometryData,vglline=new vgl.lineStrip,vglcoords=new vgl.sourceDataP3fv,indices=[],i=null,x=null,y=null,z=null;for(vglline.setIndicesPerPrimitive(coordinates.length),i=0;i2&&(z=coordinates[i][2]),vglcoords.pushBack([x,y,z]),this.readScalars(coordinates[i],geom);return vglline.setIndices(indices),geom.addPrimitive(vglline),geom.addSource(vglcoords),geom.setName("aLineString"),geom},this.readMultiLineString=function(coordinates){var geom=new vgl.geometryData,vglcoords=new vgl.sourceDataP3fv,pntcnt=0,estpntcnt=2*coordinates.length,i=null,j=null,x=null,y=null,z=null,indices=null,vglline=null,thisLineLength=null;for(vglcoords.data().length=3*estpntcnt,j=0;ji;i++)indices.push(pntcnt),x=coordinates[j][i][0],y=coordinates[j][i][1],z=0,coordinates[j][i].length>2&&(z=coordinates[j][i][2]),vglcoords.insertAt(pntcnt,[x,y,z]),this.readScalars(coordinates[j][i],geom,2*estpntcnt,pntcnt),pntcnt++;vglline.setIndices(indices),geom.addPrimitive(vglline)}return geom.setName("aMultiLineString"),geom.addSource(vglcoords),geom},this.readPolygon=function(coordinates){var geom=new vgl.geometryData,vglcoords=new vgl.sourceDataP3fv,x=null,y=null,z=null,thisPolyLength=coordinates[0].length,vl=1,i=null,indices=null,vgltriangle=null;for(i=0;thisPolyLength>i;i++)x=coordinates[0][i][0],y=coordinates[0][i][1],z=0,coordinates[0][i].length>2&&(z=coordinates[0][i][2]),vglcoords.pushBack([x,y,z]),this.readScalars(coordinates[0][i],geom),i>1&&(indices=new Uint16Array([0,vl,i]),vgltriangle=new vgl.triangles,vgltriangle.setIndices(indices),geom.addPrimitive(vgltriangle),vl=i);return geom.setName("POLY"),geom.addSource(vglcoords),geom},this.readMultiPolygon=function(coordinates){var geom=new vgl.geometryData,vglcoords=new vgl.sourceDataP3fv,ccount=0,numPolys=coordinates.length,pntcnt=0,estpntcnt=3*numPolys,vgltriangle=new vgl.triangles,indexes=[],i=null,j=null,x=null,y=null,z=null,thisPolyLength=null,vf=null,vl=null,flip=null,flipped=!1,tcount=0;for(vglcoords.data().length=3*numPolys,j=0;numPolys>j;j++)for(thisPolyLength=coordinates[j][0].length,vf=ccount,vl=ccount+1,flip=[!1,!1,!1],i=0;thisPolyLength>i;i++)x=coordinates[j][0][i][0],y=coordinates[j][0][i][1],z=0,coordinates[j][0][i].length>2&&(z=coordinates[j][0][i][2]),flipped=!1,x>180&&(flipped=!0,x-=360),0===i?flip[0]=flipped:flip[1+(i-1)%2]=flipped,vglcoords.insertAt(pntcnt,[x,y,z]),this.readScalars(coordinates[j][0][i],geom,estpntcnt,pntcnt),pntcnt++,i>1&&(flip[0]===flip[1]&&flip[1]===flip[2]&&(indexes[3*tcount+0]=vf,indexes[3*tcount+1]=vl,indexes[3*tcount+2]=ccount,tcount++),vl=ccount),ccount++;return vgltriangle.setIndices(indexes),geom.addPrimitive(vgltriangle),geom.setName("aMultiPoly"),geom.addSource(vglcoords),geom},this.readGJObjectInt=function(object){if(!object.hasOwnProperty("type"))return null;object.properties&&object.properties.ScalarFormat&&"values"===object.properties.ScalarFormat&&(this.m_scalarFormat="values",object.properties.ScalarRange&&(this.m_scalarRange=object.properties.ScalarRange)),object.properties&&object.properties.ScalarFormat&&"rgb"===object.properties.ScalarFormat&&(this.m_scalarFormat="rgb");var ret,type=object.type,next=null,nextset=null,i=null;switch(type){case"Point":ret=this.readPoint(object.coordinates);break;case"MultiPoint":ret=this.readMultiPoint(object.coordinates);break;case"LineString":ret=this.readLineString(object.coordinates);break;case"MultiLineString":ret=this.readMultiLineString(object.coordinates);break;case"Polygon":ret=this.readPolygon(object.coordinates);break;case"MultiPolygon":ret=this.readMultiPolygon(object.coordinates);break;case"GeometryCollection":for(nextset=[],i=0;im_max)&&(m_max=value),(null===m_min||m_min>value)&&(m_min=value),this.data()[this.data().length]=value},this.insertAt=function(index,value){(null===m_max||value>m_max)&&(m_max=value),(null===m_min||m_min>value)&&(m_min=value),this.data()[index]=value},this.scalarRange=function(){return null===m_fixedmin||null===m_fixedmax?[m_min,m_max]:[m_fixedmin,m_fixedmax]},this.setScalarRange=function(min,max){m_fixedmin=min,m_fixedmax=max},this},inherit(vgl.sourceDataSf,vgl.sourceData),vgl.sourceDataDf=function(arg){"use strict";if(!(this instanceof vgl.sourceDataDf))return new vgl.sourceDataDf(arg);return vgl.sourceData.call(this,arg),this.addAttribute(vgl.vertexAttributeKeys.Scalar,gl.FLOAT,4,0,4,1,!1),this.pushBack=function(value){this.data()[this.data().length]=value},this.insertAt=function(index,value){this.data()[index]=value},this},inherit(vgl.sourceDataDf,vgl.sourceData),vgl.geometryData=function(){"use strict";if(!(this instanceof vgl.geometryData))return new vgl.geometryData;vgl.data.call(this);var m_name="",m_primitives=[],m_sources=[],m_bounds=[0,0,0,0,0,0],m_computeBoundsTimestamp=vgl.timestamp(),m_boundsDirtyTimestamp=vgl.timestamp();return this.type=function(){return vgl.data.geometry},this.name=function(){return m_name},this.setName=function(name){m_name=name},this.addSource=function(source,sourceName){return void 0!==sourceName&&source.setName(sourceName),-1===m_sources.indexOf(source)?(m_sources.push(source),source.hasKey(vgl.vertexAttributeKeys.Position)&&m_boundsDirtyTimestamp.modified(),!0):!1},this.source=function(index){return indexm_computeBoundsTimestamp.getMTime()&&this.computeBounds(),m_bounds},this.boundsDirty=function(dirty){return dirty&&m_boundsDirtyTimestamp.modified(),m_boundsDirtyTimestamp.getMTime()>m_computeBoundsTimestamp.getMTime()},this.resetBounds=function(){m_bounds[0]=0,m_bounds[1]=0,m_bounds[2]=0,m_bounds[3]=0,m_bounds[4]=0,m_bounds[5]=0},this.setBounds=function(minX,maxX,minY,maxY,minZ,maxZ){return m_bounds[0]=minX,m_bounds[1]=maxX,m_bounds[2]=minY,m_bounds[3]=maxY,m_bounds[4]=minZ,m_bounds[5]=maxZ,m_computeBoundsTimestamp.modified(),!0},this.computeBounds=function(){if(m_boundsDirtyTimestamp.getMTime()>m_computeBoundsTimestamp.getMTime()){var j,ib,jb,maxv,minv,vertexIndex,attr=vgl.vertexAttributeKeys.Position,sourceData=this.sourceData(attr),data=sourceData.data(),numberOfComponents=sourceData.attributeNumberOfComponents(attr),stride=sourceData.attributeStride(attr),offset=sourceData.attributeOffset(attr),sizeOfDataType=sourceData.sizeOfAttributeDataType(attr),count=data.length,value=null;for(stride/=sizeOfDataType,offset/=sizeOfDataType,this.resetBounds(),j=0;numberOfComponents>j;++j){for(ib=2*j,jb=2*j+1,maxv=minv=count?m_bounds[jb]=data[offset+j]:0,vertexIndex=offset+stride+j;count>vertexIndex;vertexIndex+=stride)value=data[vertexIndex],value>maxv&&(maxv=value),minv>value&&(minv=value);m_bounds[ib]=minv,m_bounds[jb]=maxv}m_computeBoundsTimestamp.modified()}},this.findClosestVertex=function(point){var vi,vPos,dx,dy,dz,dist,i,attr=vgl.vertexAttributeKeys.Position,sourceData=this.sourceData(attr),sizeOfDataType=sourceData.sizeOfAttributeDataType(attr),numberOfComponents=sourceData.attributeNumberOfComponents(attr),data=sourceData.data(),stride=sourceData.attributeStride(attr)/sizeOfDataType,offset=sourceData.attributeOffset(attr)/sizeOfDataType,minDist=Number.MAX_VALUE,minIndex=null;for(3!==numberOfComponents&&console.log("[warning] Find closest vertex assumes threecomponent vertex "),point.z||(point={x:point.x,y:point.y,z:0}),vi=offset,i=0;vidist&&(minDist=dist,minIndex=i);return minIndex},this.getPosition=function(index){var attr=vgl.vertexAttributeKeys.Position,sourceData=this.sourceData(attr),sizeOfDataType=sourceData.sizeOfAttributeDataType(attr),numberOfComponents=sourceData.attributeNumberOfComponents(attr),data=sourceData.data(),stride=sourceData.attributeStride(attr)/sizeOfDataType,offset=sourceData.attributeOffset(attr)/sizeOfDataType;
+var geo={};window.geo=geo,geo.renderers={},geo.features={},geo.fileReaders={},geo.inherit=function(C,P){"use strict";var F=inherit.func();F.prototype=P.prototype,C.prototype=new F,C.prototype.constructor=C},geo.inherit.func=function(){"use strict";return function(){}},window.inherit=geo.inherit,geo.registerFileReader=function(name,func){"use strict";void 0===geo.fileReaders&&(geo.fileReaders={}),geo.fileReaders[name]=func},geo.createFileReader=function(name,opts){"use strict";return geo.fileReaders.hasOwnProperty(name)?geo.fileReaders[name](opts):null},geo.registerRenderer=function(name,func){"use strict";void 0===geo.renderers&&(geo.renderers={}),geo.renderers[name]=func},geo.createRenderer=function(name,layer,canvas){"use strict";if(geo.renderers.hasOwnProperty(name)){var ren=geo.renderers[name]({layer:layer,canvas:canvas});return ren._init(),ren}return null},geo.registerFeature=function(category,name,func){"use strict";void 0===geo.features&&(geo.features={}),category in geo.features||(geo.features[category]={}),geo.features[category][name]=func},geo.createFeature=function(name,layer,renderer,arg){"use strict";var category=renderer.api(),options={layer:layer,renderer:renderer};return category in geo.features&&name in geo.features[category]?(void 0!==arg&&$.extend(!0,options,arg),geo.features[category][name](options)):null},geo.registerLayer=function(name,func){"use strict";void 0===geo.layers&&(geo.layers={}),geo.layers[name]=func},geo.createLayer=function(name,map,arg){"use strict";var options={map:map,renderer:"vgl"},layer=null;return name in geo.layers?(void 0!==arg&&$.extend(!0,options,arg),layer=geo.layers[name](options),layer._init(),layer):null},geo.registerWidget=function(category,name,func){"use strict";void 0===geo.widgets&&(geo.widgets={}),category in geo.widgets||(geo.widgets[category]={}),geo.widgets[category][name]=func},geo.createWidget=function(name,layer,renderer,arg){"use strict";var category=renderer.api(),options={layer:layer,renderer:renderer};return category in geo.widgets&&name in geo.widgets[category]?(void 0!==arg&&$.extend(!0,options,arg),geo.widgets[category][name](options)):null},window.requestAnimationFrame||(window.requestAnimationFrame=function(func){"use strict";window.setTimeout(func,15)}),Math.log2||(Math.log2=function(){"use strict";return Math.log.apply(Math,arguments)/Math.LN2}),geo.version="0.4.2",function(){"use strict";function setNumeric(){var i;for(i=0;in?!1:(outer.forEach(function(vert,i){var j=(n+i-1)%n,intersect=outer[i].y>point.y!=outer[j].y>point.y&&point.x<(outer[j].x-outer[i].x)*(point.y-outer[i].y)/(outer[j].y-outer[i].y)+outer[i].x;intersect&&(inside=!inside)}),(inner||[]).forEach(function(hole){inside=inside&&!geo.util.pointInPolygon(point,hole)}),inside)},isFunction:function(f){return"function"==typeof f},ensureFunction:function(f){return geo.util.isFunction(f)?f:function(){return f}},randomString:function(n){var s,i,r;for(n=n||8,s="",i=0;n>i;i+=1)r=Math.floor(Math.random()*chars.length),s+=chars.substring(r,r+1);return s},convertColor:function(color){return void 0!==color.r&&void 0!==color.g&&void 0!==color.b?color:("string"==typeof color&&(geo.util.cssColors.hasOwnProperty(color)?color=geo.util.cssColors[color]:"#"===color.charAt(0)&&(color=parseInt(color.slice(1),16))),isFinite(color)&&(color={r:((16711680&color)>>16)/255,g:((65280&color)>>8)/255,b:(255&color)/255}),color)},normalizeCoordinates:function(p){return p=p||{},Array.isArray(p)?{x:p[0],y:p[1],z:p[2]||0}:p instanceof geo.latlng?{x:p.lng(),y:p.lat(),z:0}:{x:setNumeric(p.x,p.longitude,p.lng,p.lon,0),y:setNumeric(p.y,p.latitude,p.lat,0),z:setNumeric(p.z,p.elevation,p.elev,p.height,0)}}},geo.util.cssColors={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,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}}(),function(){"use strict";function vect(x,y){return new Vector2D(x,y)}var RangeNode=function(elem,start,end,current){this.data=elem[current],this.left=null,this.right=null,start!==current&&(this.left=new RangeNode(elem,start,current-1,parseInt((start+(current-1))/2,10))),end!==current&&(this.right=new RangeNode(elem,current+1,end,parseInt((end+(current+1))/2,10))),this.elem=elem,this.start=start,this.end=end,this.subtree=null,this.search=rangeNodeSearch},rangeNodeSearch=function(result,box){var m_this=this,xrange=function(b){return b.x_in(m_this.elem[m_this.start])&&b.x_in(m_this.elem[m_this.end])},yrange=function(b,start,end){return b.y_in(m_this.subtree[start])&&b.y_in(m_this.subtree[end])},subquery=function(result,box,start,end,current){if(yrange(box,start,end))for(var i=start;end>=i;i++)result.push(m_this.subtree[i]);else box.y_in(m_this.subtree[current])&&result.push(m_this.subtree[current]),box.y_left(m_this.subtree[current])?current!==end&&subquery(result,box,current+1,end,parseInt((end+(current+1))/2,10)):box.x_right(m_this.subtree[current])?current!==start&&subquery(result,box,start,current-1,parseInt((start+(current-1))/2,10)):(current!==end&&subquery(result,box,current+1,end,parseInt((end+(current+1))/2,10)),current!==start&&subquery(result,box,start,current-1,parseInt((start+(current-1))/2,10)))};return xrange(box)?(this.subtree||(this.subtree=this.elem.slice(this.start,this.end+1),this.subtree.sort(function(a,b){return a.y-b.y})),void subquery(result,box,0,this.subtree.length-1,parseInt((this.subtree.length-1)/2,10))):(box.contains(this.data)&&result.push(this.data),void(box.x_left(this.data)?this.right&&this.right.search(result,box):box.x_right(this.data)?this.left&&this.left.search(result,box):(this.left&&this.left.search(result,box),this.right&&this.right.search(result,box))))},RangeTree=function(elem){elem.sort(function(a,b){return a.x-b.x}),elem.length>0?this.root=new RangeNode(elem,0,elem.length-1,parseInt((elem.length-1)/2,10)):this.root=null,this.search=function(_box){if(!this.root)return[];var box=_box.clone(),result=[];return this.root.search(result,box),result}},Box=function(v1,v2){this.min=v1.clone(),this.max=v2.clone(),this.contains=function(p){return v1.x<=p.x&&v2.x>=p.x&&v1.y<=p.y&&v2.y>=p.y},this.x_in=function(p){return v1.x<=p.x&&v2.x>=p.x},this.x_left=function(p){return v1.x>=p.x},this.x_right=function(p){return v2.x<=p.x},this.y_in=function(p){return v1.y<=p.y&&v2.y>=p.y},this.y_left=function(p){return v1.y>=p.y},this.y_right=function(p){return v2.y<=p.y},this.area=function(){return(this.max.x-this.min.x)*(this.max.y-this.min.y)},this.height=function(){return this.max.y-this.min.y},this.width=function(){return this.max.x-this.min.x},this.vertex=function(index){switch(index){case 0:return this.min.clone();case 1:return new vect(this.max.x,this.min.y);case 2:return this.max.clone();case 3:return new vect(this.min.x,this.max.y);default:throw"Index out of bounds: "+index}},this.intersects=function(box){for(var i=0;4>i;i++)for(var j=0;4>j;j++)if(vect.intersects(this.vertex(i),this.vertex((i+1)%4),box.vertex(j),box.vertex((j+1)%4)))return!0;return this.contains(box.min)&&this.contains(box.max)&&this.contains(new vect(box.min.x,box.max.y))&&this.contains(new vect(box.max.x,box.min.y))?!0:box.contains(this.min)&&box.contains(this.max)&&box.contains(new vect(this.min.x,this.max.y))&&box.contains(new vect(this.max.x,this.min.y))?!0:!1},this.union=function(b){this.min.x=Math.min(this.min.x,b.min.x),this.min.y=Math.min(this.min.y,b.min.y),this.max.x=Math.max(this.max.x,b.max.x),this.max.y=Math.max(this.max.y,b.max.y)},this.centroid=function(){return new vect((this.max.x+this.min.x)/2,(this.max.y+this.min.y)/2)},this.clone=function(){return new Box(v1,v2)}},Vector2D=function(x,y){this.x=x,this.y=y,this.add=function(v){return this.x+=v.x,this.y+=v.y,this},this.sub=function(v){return this.x-=v.x,this.y-=v.y,this},this.scale=function(s){return this.x*=s,this.y*=s,this},this.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},this.normalize=function(){var scale=this.length();return 0===scale?this:(this.x/=scale,this.y/=scale,this)},this.div=function(v){return this.x/=v.x,this.y/=v.y,this},this.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},this.zero=function(tol){return tol=tol||0,this.length()<=tol},this.dot=function(v){return this.x*v.x+this.y*v.y},this.cross=function(v){return this.x*v.y-this.y*v.x},this.rotate=function(omega){var cos=Math.cos(omega),sin=Math.sin(omega);return xp=cos*this.x-sin*this.y,yp=sin*this.x+cos*this.y,this.x=xp,this.y=yp,this},this.clone=function(){return new Vector2D(this.x,this.y)},this.array=function(){return[this.x,this.y]}};vect.scale=function(v,s){return v.clone().scale(s)},vect.add=function(v1,v2){return v1.clone().add(v2)},vect.sub=function(v1,v2){return v1.clone().sub(v2)},vect.dist=function(v1,v2){return v1.clone().sub(v2).length()},vect.dir=function(v1,v2){return v1.clone().sub(v2).normalize()},vect.dot=function(v1,v2){return v1.x*v2.x+v1.y*v2.y},vect.cross=function(v1,v2){return v1.x*v2.y-v1.y*v2.x},vect.left=function(a,b,c,tol){tol||(tol=0);var v1=vect.sub(b,a),v2=vect.sub(c,a);return vect.cross(v1,v2)>=-tol},vect.intersects=function(a,b,c,d,tol){return tol||(tol=0),vect.left(a,b,c,tol)!=vect.left(a,b,d,tol)&&vect.left(c,d,b,tol)!=vect.left(c,d,a,tol)},vect.intersect2dt=function(a,b,c,d){var denom=a.x*(d.y-c.y)+b.x*(c.y-d.y)+d.x*(b.y-a.y)+c.x*(a.y-b.y);if(0===denom)return 1/0;var num_t=(a.x*(d.y-c.y)+c.x*(a.y-d.y)+d.x*(c.y-a.y),-(a.x*(c.y-b.y)+b.x*(a.y-c.y)+c.x*(b.y-a.y))),t=num_t/denom;return t},vect.intersect2dpos=function(a,b,c,d){var denom=a.x*(d.y-c.y)+b.x*(c.y-d.y)+d.x*(b.y-a.y)+c.x*(a.y-b.y);if(0===denom)return 1/0;var num_s=a.x*(d.y-c.y)+c.x*(a.y-d.y)+d.x*(c.y-a.y),s=num_s/denom,dir=vect.sub(b,a);return dir.scale(s),vect.add(a,dir)},vect.rotate=function(v,omega){var cos=Math.cos(omega),sin=Math.sin(omega);xp=cos*v.x-sin*v.y,yp=sin*v.x+cos*v.y;var c=new vect(xp,yp);return c},vect.normalize=function(v){return v.clone().normalize()},geo.util.RangeTree=RangeTree,geo.util.Box=Box,geo.util.vect=vect}(),geo.object=function(){"use strict";if(!(this instanceof geo.object))return new geo.object;var m_this=this,m_eventHandlers={},m_idleHandlers=[],m_deferredCount=0;return this.onIdle=function(handler){return m_deferredCount?m_idleHandlers.push(handler):handler(),m_this},this.addDeferred=function(defer){return m_deferredCount+=1,defer.done(function(){m_deferredCount-=1,m_deferredCount||m_idleHandlers.splice(0,m_idleHandlers.length).forEach(function(handler){handler()})}),m_this},this.geoOn=function(event,handler){return Array.isArray(event)?(event.forEach(function(e){m_this.geoOn(e,handler)}),m_this):(m_eventHandlers.hasOwnProperty(event)||(m_eventHandlers[event]=[]),m_eventHandlers[event].push(handler),m_this)},this.geoTrigger=function(event,args){return Array.isArray(event)?(event.forEach(function(e){m_this.geoTrigger(e,args)}),m_this):(m_eventHandlers.hasOwnProperty(event)&&m_eventHandlers[event].forEach(function(handler){handler.call(m_this,args)}),m_this)},this.geoOff=function(event,arg){if(void 0===event&&(m_eventHandlers={},m_idleHandlers=[],m_deferredCount=0),Array.isArray(event))return event.forEach(function(e){m_this.geoOff(e,arg)}),m_this;if(arg){if(Array.isArray(arg))return arg.forEach(function(handler){m_this.geoOff(event,handler)}),m_this}else m_eventHandlers[event]=[];return m_eventHandlers.hasOwnProperty(event)&&(m_eventHandlers[event]=m_eventHandlers[event].filter(function(f){return f!==arg})),m_this},this._exit=function(){m_this.geoOff()},vgl.object.call(this),this},inherit(geo.object,vgl.object),geo.sceneObject=function(arg){"use strict";if(!(this instanceof geo.sceneObject))return new geo.sceneObject;geo.object.call(this,arg);var m_this=this,m_parent=null,m_children=[],s_exit=this._exit,s_trigger=this.geoTrigger,s_addDeferred=this.addDeferred,s_onIdle=this.onIdle;return this.addDeferred=function(defer){m_parent?m_parent.addDeferred(defer):s_addDeferred(defer)},this.onIdle=function(handler){m_parent?m_parent.onIdle(handler):s_onIdle(handler)},this.parent=function(arg){return void 0===arg?m_parent:(m_parent=arg,m_this)},this.addChild=function(child){return Array.isArray(child)?(child.forEach(m_this.addChild),m_this):(child.parent(m_this),m_children.push(child),m_this)},this.removeChild=function(child){return Array.isArray(child)?(child.forEach(m_this.removeChild),m_this):(m_children=m_children.filter(function(c){return c!==child}),m_this)},this.children=function(){return m_children.slice()},this.draw=function(arg){return m_this.children().forEach(function(child){child.draw(arg)}),m_this},this.geoTrigger=function(event,args,childrenOnly){var geoArgs;return args=args||{},geoArgs=args.geo||{},args.geo=geoArgs,geoArgs.stopPropagation?m_this:!childrenOnly&&m_parent&&geoArgs._triggeredBy!==m_parent?(geoArgs._triggeredBy=m_this,m_parent.geoTrigger(event,args),m_this):(s_trigger.call(m_this,event,args),geoArgs.stopPropagation?m_this:(m_children.forEach(function(child){geoArgs._triggeredBy=m_this,child.geoTrigger(event,args)}),m_this))},this._exit=function(){m_this.children=[],delete m_this.parent,s_exit()},this},inherit(geo.sceneObject,geo.object),geo.timestamp=function(){"use strict";return this instanceof geo.timestamp?void vgl.timestamp.call(this):new geo.timestamp},inherit(geo.timestamp,vgl.timestamp),geo.ellipsoid=function(x,y,z){"use strict";if(!(this instanceof geo.ellipsoid))return new geo.ellipsoid(x,y,z);if(x=vgl.defaultValue(x,0),y=vgl.defaultValue(y,0),z=vgl.defaultValue(z,0),0>x||0>y||0>z)return console.log("[error] Al radii components must be greater than zero");var m_this=this,m_radii=new vec3.fromValues(x,y,z),m_radiiSquared=new vec3.fromValues(x*x,y*y,z*z),m_minimumRadius=Math.min(x,y,z),m_maximumRadius=Math.max(x,y,z);return this.radii=function(){return m_radii},this.radiiSquared=function(){return m_radiiSquared},this.maximumRadius=function(){return m_maximumRadius},this.minimumRadius=function(){return m_minimumRadius},this.computeGeodeticSurfaceNormal=function(lat,lon){if("undefined"==typeof lat||"undefined"==typeof lon)throw"[error] Valid latitude and longitude is required";var cosLatitude=Math.cos(lat),result=vec3.create();return result[0]=cosLatitude*Math.cos(lon),result[1]=cosLatitude*Math.sin(lon),result[2]=Math.sin(lat),vec3.normalize(result,result),result},this.transformPoint=function(lat,lon,elev){lat*=Math.PI/180,lon*=Math.PI/180;var n=m_this.computeGeodeticSurfaceNormal(lat,lon),k=vec3.create(),gamma=Math.sqrt(vec3.dot(n,k)),result=vec3.create();return vec3.multiply(k,m_radiiSquared,n),vec3.scale(k,k,1/gamma),vec3.scale(n,n,elev),vec3.add(result,n,k),result},this.transformGeometry=function(geom){if(!geom)throw"[error] Failed to transform to cartesian. Invalid geometry.";var sourceData=geom.sourceData(vgl.vertexAttributeKeys.Position),sourceDataArray=sourceData.data(),noOfComponents=sourceData.attributeNumberOfComponents(vgl.vertexAttributeKeys.Position),stride=sourceData.attributeStride(vgl.vertexAttributeKeys.Position),offset=sourceData.attributeOffset(vgl.vertexAttributeKeys.Position),sizeOfDataType=sourceData.sizeOfAttributeDataType(vgl.vertexAttributeKeys.Position),index=null,count=sourceDataArray.length*(1/noOfComponents),gamma=null,n=null,j=0,k=vec3.create(),result=vec3.create();if(stride/=sizeOfDataType,offset/=sizeOfDataType,3!==noOfComponents)throw"[error] Requires positions with three components";for(j=0;count>j;j+=1)index=j*stride+offset,sourceDataArray[index]=sourceDataArray[index]*(Math.PI/180),sourceDataArray[index+1]=sourceDataArray[index+1]*(Math.PI/180),n=m_this.computeGeodeticSurfaceNormal(sourceDataArray[index+1],sourceDataArray[index]),vec3.multiply(k,m_radiiSquared,n),gamma=Math.sqrt(vec3.dot(n,k)),vec3.scale(k,k,1/gamma),vec3.scale(n,n,sourceDataArray[index+2]),vec3.add(result,n,k),sourceDataArray[index]=result[0],sourceDataArray[index+1]=result[1],sourceDataArray[index+2]=result[2]},m_this},geo.ellipsoid.WGS84=vgl.freezeObject(geo.ellipsoid(6378137,6378137,6356752.314245179)),geo.ellipsoid.UNIT_SPHERE=vgl.freezeObject(geo.ellipsoid(1,1,1)),geo.mercator={r_major:6378137},geo.mercator.r_minor=function(spherical){"use strict";var r_minor;return spherical=void 0!==spherical?spherical:!1,r_minor=spherical?6378137:6356752.314245179},geo.mercator.f=function(spherical){"use strict";return(geo.mercator.r_major-geo.mercator.r_minor(spherical))/geo.mercator.r_major},geo.mercator.long2tilex=function(lon,z){"use strict";var rad=(lon+180)/360,f=Math.floor(rad*Math.pow(2,z));return f},geo.mercator.lat2tiley=function(lat,z){"use strict";var rad=lat*Math.PI/180;return Math.floor((1-rad/Math.PI)/2*Math.pow(2,z))},geo.mercator.long2tilex2=function(lon,z){"use strict";var rad=(lon+180)/360,f=rad*Math.pow(2,z),ret=Math.floor(f),frac=f-ret;return[ret,frac]},geo.mercator.lat2tiley2=function(lat,z){"use strict";var rad=lat*Math.PI/180,f=(1-Math.log(Math.tan(rad)+1/Math.cos(rad))/Math.PI)/2*Math.pow(2,z),ret=Math.floor(f),frac=f-ret;return[ret,frac]},geo.mercator.tilex2long=function(x,z){"use strict";return x/Math.pow(2,z)*360-180},geo.mercator.tiley2lat=function(y,z){"use strict";var n=Math.PI-2*Math.PI*y/Math.pow(2,z);return 180/Math.PI*Math.atan(.5*(Math.exp(n)-Math.exp(-n)))},geo.mercator.y2lat=function(a){"use strict";return 180/Math.PI*(2*Math.atan(Math.exp(a*Math.PI/180))-Math.PI/2)},geo.mercator.lat2y=function(a){"use strict";return 180/Math.PI*Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2))},geo.mercator.deg2rad=function(d){"use strict";var r=d*(Math.PI/180);return r},geo.mercator.rad2deg=function(r){"use strict";var d=r/(Math.PI/180);return d},geo.mercator.ll2m=function(lon,lat,spherical){"use strict";lat>89.5&&(lat=89.5),-89.5>lat&&(lat=-89.5);var x=this.r_major*this.deg2rad(lon),temp=this.r_minor(spherical)/this.r_major,es=1-temp*temp,eccent=Math.sqrt(es),phi=this.deg2rad(lat),sinphi=Math.sin(phi),con=eccent*sinphi,com=.5*eccent,con2=Math.pow((1-con)/(1+con),com),ts=Math.tan(.5*(.5*Math.PI-phi))/con2,y=-this.r_major*Math.log(ts),ret={x:x,y:y};return ret},geo.mercator.m2ll=function(x,y,spherical){"use strict";var lon=this.rad2deg(x/this.r_major),temp=this.r_minor(spherical)/this.r_major,e=Math.sqrt(1-temp*temp),lat=this.rad2deg(this.pjPhi2(Math.exp(-(y/this.r_major)),e)),ret={lon:lon,lat:lat};return ret},geo.mercator.pjPhi2=function(ts,e){"use strict";var con,dphi,N_ITER=15,HALFPI=Math.PI/2,TOL=1e-10,i=N_ITER,eccnth=.5*e,Phi=HALFPI-2*Math.atan(ts);do con=e*Math.sin(Phi),dphi=HALFPI-2*Math.atan(ts*Math.pow((1-con)/(1+con),eccnth))-Phi,Phi+=dphi,i-=1;while(Math.abs(dphi)>TOL&&i);return Phi},geo.latlng=function(arg1,arg2,arg3){"use strict";if(!(this instanceof geo.latlng))return new geo.latlng(arg1,arg2,arg3);var m_this=this,m_lat=void 0===arg2&&void 0===arg3?arg1.lat():arg1,m_lng=void 0===arg2&&void 0===arg3?arg1.lng():arg2,m_elv=void 0===arg2&&void 0===arg3?arg1.elv():arg3;return this.lat=function(val){return void 0===val?m_lat:void(m_lat=val)},this.lng=function(val){return void 0===val?m_lng:void(m_lng=val)},this.elv=function(val){return void 0===val?m_elv:void(m_elv=val)},this.x=function(val){return void 0===val?m_this.lng():void(m_lng=val)},this.y=function(val){return void 0===val?m_this.lat():void(m_lat=val)},this.z=function(val){return void 0===val?m_this.elv():void(m_elv=val)},this},geo.layer=function(arg){"use strict";if(!(this instanceof geo.layer))return new geo.layer(arg);arg=arg||{},geo.sceneObject.call(this,arg);var m_this=this,s_exit=this._exit,m_style=void 0===arg.style?{opacity:.5,color:[.8,.8,.8],visible:!0,bin:100}:arg.style,m_id=void 0===arg.id?geo.layer.newLayerId():arg.id,m_name="",m_gcs="EPSG:4326",m_timeRange=null,m_source=arg.source||null,m_map=void 0===arg.map?null:arg.map,m_isReference=!1,m_x=0,m_y=0,m_width=0,m_height=0,m_node=null,m_canvas=null,m_renderer=null,m_initialized=!1,m_rendererName=void 0===arg.renderer?"vgl":arg.renderer,m_dataTime=geo.timestamp(),m_updateTime=geo.timestamp(),m_drawTime=geo.timestamp(),m_sticky=void 0===arg.sticky?!0:arg.sticky,m_active=void 0===arg.active?!0:arg.active;return this.sticky=function(){return m_sticky},this.active=function(){return m_active},this.node=function(){return m_node},this.id=function(val){return void 0===val?m_id:(m_id=geo.newLayerId(),m_this.modified(),m_this)},this.name=function(val){return void 0===val?m_name:(m_name=val,m_this.modified(),m_this)},this.opacity=function(val){return void 0===val?m_style.opacity:(m_style.opacity=val,m_this.modified(),m_this)},this.visible=function(val){return void 0===val?m_style.visible:(m_style.visible=val,m_this.modified(),m_this)},this.bin=function(val){return void 0===val?m_style.bin:(m_style.bin=val,m_this.modified(),m_this)},this.gcs=function(val){return void 0===val?m_gcs:(m_gcs=val,m_this.modified(),m_this)},this.transform=function(val){return geo.transform.transformLayer(val,m_this,m_map.baseLayer()),m_this},this.timeRange=function(val){return void 0===val?m_timeRange:(m_timeRange=val,m_this.modified(),m_this)},this.source=function(val){return void 0===val?m_source:(m_source=val,m_this.modified(),m_this)},this.map=function(val){return void 0===val?m_map:(m_map=val,m_map.node().append(m_node),m_this.modified(),m_this)},this.renderer=function(){return m_renderer},this.canvas=function(){return m_canvas},this.viewport=function(){return[m_x,m_y,m_width,m_height]},this.dataTime=function(){return m_dataTime},this.updateTime=function(){return m_updateTime},this.drawTime=function(){return m_drawTime},this.query=function(){},this.referenceLayer=function(val){return void 0!==val?(m_isReference=val,m_this.modified(),m_this):m_isReference},this.initialized=function(val){return void 0!==val?(m_initialized=val,m_this):m_initialized},this.toLocal=function(input){return input},this.fromLocal=function(input){return input},this._init=function(){return m_initialized?m_this:(m_node=$(document.createElement("div")),m_node.attr("id",m_name),m_node.css("position","absolute"),m_map&&m_map.node().append(m_node),m_canvas?m_renderer=geo.createRenderer(m_rendererName,m_this,m_canvas):(m_renderer=geo.createRenderer(m_rendererName,m_this),m_canvas=m_renderer.canvas()),m_this.active()||m_node.css("pointerEvents","none"),m_initialized=!0,m_this)},this._exit=function(){m_renderer._exit(),m_node.off(),m_node.remove(),m_node=null,arg={},m_canvas=null,m_renderer=null,s_exit()},this._update=function(){},this._resize=function(x,y,w,h){return m_x=x,m_y=y,m_width=w,m_height=h,m_node.width(w),m_node.height(h),m_this.modified(),m_this.geoTrigger(geo.event.resize,{x:x,y:y,width:m_width,height:m_height}),m_this},this.width=function(){return m_width},this.height=function(){return m_height},this},geo.layer.newLayerId=function(){"use strict";var currentId=1;return function(){var id=currentId;return currentId+=1,id}}(),geo.layer.create=function(map,spec){"use strict";if(spec=spec||{},spec.type="feature","feature"!==spec.type)return console.warn("Unsupported layer type"),null;if(spec.renderer=spec.renderer||"vgl","d3"!==spec.renderer&&"vgl"!==spec.renderer)return console.warn("Invalid renderer"),null;var layer=map.createLayer(spec.type,spec);return layer?(spec.features.forEach(function(f){f.data=f.data||spec.data,f.feature=geo.feature.create(layer,f)}),layer):(console.warn("Unable to create a layer"),null)},inherit(geo.layer,geo.sceneObject),geo.featureLayer=function(arg){"use strict";if(!(this instanceof geo.featureLayer))return new geo.featureLayer(arg);geo.layer.call(this,arg);var m_this=this,m_features=[],s_init=this._init,s_exit=this._exit,s_update=this._update,s_draw=this.draw;return this.createFeature=function(featureName,arg){var newFeature=geo.createFeature(featureName,m_this,m_this.renderer(),arg);return m_this.addChild(newFeature),m_features.push(newFeature),m_this.features(m_features),m_this.modified(),newFeature},this.deleteFeature=function(feature){var i;for(i=0;im_this.updateTime().getMTime())for(i=0;i=deltaT?30:deltaT;var sf=springForce(),speed=calcSpeed(v),vx=v.x/speed,vy=v.y/speed;return speed*=Math.exp(-m_options.momentum.drag*deltaT),calcSpeed(sf)*deltaT+speed0?(vx*=speed,vy*=speed):(vx=0,vy=0),{x:vx-sf.x*deltaT,y:vy-sf.y*deltaT})}function springForce(){var xplus,xminus,yplus,yminus;if(!m_options.spring.enabled)return{x:0,y:0};var ul=m_this.map().gcsToDisplay({x:-180,y:82}),lr=m_this.map().gcsToDisplay({x:180,y:-82}),c=m_options.spring.springConstant,width=m_this.map().node().width(),height=m_this.map().node().height();return xplus=c*Math.max(0,ul.x),xminus=c*Math.max(0,width-lr.x),yplus=c*Math.max(0,ul.y)/2,yminus=c*Math.max(0,height-lr.y)/2,{x:xplus-xminus,y:yplus-yminus}}if(!(this instanceof geo.mapInteractor))return new geo.mapInteractor(args);geo.object.call(this);var m_mouse,m_keyboard,m_state,$node,m_options=args||{},m_this=this,m_wheelQueue={x:0,y:0},m_throttleTime=10,m_wait=!1,m_disableThrottle=!0,m_selectionLayer=null,m_selectionPlane=null;return m_options=$.extend(!0,{panMoveButton:"left",panMoveModifiers:{},zoomMoveButton:"right",zoomMoveModifiers:{},panWheelEnabled:!1,panWheelModifiers:{},zoomWheelEnabled:!0,zoomWheelModifiers:{},wheelScaleX:1,wheelScaleY:1,zoomScale:1,selectionButton:"left",selectionModifiers:{shift:!0},momentum:{enabled:!0,maxSpeed:2.5,minSpeed:.01,drag:.01},spring:{enabled:!1,springConstant:5e-5}},m_options),m_mouse={page:{x:0,y:0},map:{x:0,y:0},buttons:{left:!1,right:!1,middle:!1},modifiers:{alt:!1,ctrl:!1,shift:!1,meta:!1},time:new Date,deltaTime:1,velocity:{x:0,y:0}},m_keyboard={},m_state={},this._connectEvents=function(){return m_options.map?(m_this._disconnectEvents(),$node=$(m_options.map.node()),$node.on("mousemove.geojs",m_this._handleMouseMove),$node.on("mousedown.geojs",m_this._handleMouseDown),$node.on("mouseup.geojs",m_this._handleMouseUp),$node.on("wheel.geojs",m_this._handleMouseWheel),("right"===m_options.panMoveButton||"right"===m_options.zoomMoveButton)&&$node.on("contextmenu.geojs",function(){return!1}),m_this):m_this},this._disconnectEvents=function(){return $node&&($node.off(".geojs"),$node=null),m_this},this.map=function(val){return void 0!==val?(m_options.map=val,m_this._connectEvents(),m_this):m_options.map},this.options=function(opts){return void 0===opts?$.extend({},m_options):($.extend(m_options,opts),m_this)},this._getMousePosition=function(evt){
+var dt,t,offset=$node.offset();t=(new Date).valueOf(),dt=t-m_mouse.time,m_mouse.time=t,m_mouse.deltaTime=dt,m_mouse.velocity={x:(evt.pageX-m_mouse.page.x)/dt,y:(evt.pageY-m_mouse.page.y)/dt},m_mouse.page={x:evt.pageX,y:evt.pageY},m_mouse.map={x:evt.pageX-offset.left,y:evt.pageY-offset.top};try{m_mouse.geo=m_this.map().displayToGcs(m_mouse.map)}catch(e){m_mouse.geo=null}},this._getMouseButton=function(evt){1===evt.which?m_mouse.buttons.left="mouseup"!==evt.type:3===evt.which?m_mouse.buttons.right="mouseup"!==evt.type:2===evt.which&&(m_mouse.buttons.middle="mouseup"!==evt.type)},this._getMouseModifiers=function(evt){m_mouse.modifiers.alt=evt.altKey,m_mouse.modifiers.ctrl=evt.ctrlKey,m_mouse.modifiers.meta=evt.metaKey,m_mouse.modifiers.shift=evt.shiftKey},this._getSelection=function(){var origin=m_state.origin,mouse=m_this.mouse(),map=m_this.map(),display={},gcs={};return display.upperLeft={x:Math.min(origin.map.x,mouse.map.x),y:Math.min(origin.map.y,mouse.map.y)},display.lowerRight={x:Math.max(origin.map.x,mouse.map.x),y:Math.max(origin.map.y,mouse.map.y)},display.upperRight={x:display.lowerRight.x,y:display.upperLeft.y},display.lowerLeft={x:display.upperLeft.x,y:display.lowerRight.y},gcs.upperLeft=map.displayToGcs(display.upperLeft),gcs.lowerRight=map.displayToGcs(display.lowerRight),gcs.upperRight=map.displayToGcs(display.upperRight),gcs.lowerLeft=map.displayToGcs(display.lowerLeft),m_selectionPlane.origin([display.lowerLeft.x,display.lowerLeft.y,0]),m_selectionPlane.upperLeft([display.upperLeft.x,display.upperLeft.y,0]),m_selectionPlane.lowerRight([display.lowerRight.x,display.lowerRight.y,0]),m_selectionPlane.draw(),{display:display,gcs:gcs,mouse:mouse,origin:$.extend({},m_state.origin)}},this.cancel=function(action){var out;return out=action?m_state.action===action:!!m_state.action,out&&(m_state={}),out},this._handleMouseDown=function(evt){var action=null;"momentum"===m_state.action&&(m_state={}),m_this._getMousePosition(evt),m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),eventMatch(m_options.panMoveButton,m_options.panMoveModifiers)?action="pan":eventMatch(m_options.zoomMoveButton,m_options.zoomMoveModifiers)?action="zoom":eventMatch(m_options.selectionButton,m_options.selectionModifiers)&&(action="select"),m_mouse.velocity={x:0,y:0},action&&(m_state={action:action,origin:$.extend(!0,{},m_mouse),delta:{x:0,y:0}},"select"===action&&(m_selectionLayer&&(m_selectionLayer.clear(),m_this.map().deleteLayer(m_selectionLayer),m_selectionLayer=null),m_selectionLayer=m_this.map().createLayer("feature",{renderer:"d3"}),m_selectionPlane=m_selectionLayer.createFeature("plane"),m_selectionPlane.style({screenCoordinates:!0,fillOpacity:function(){return.25}}),m_this.map().geoTrigger(geo.event.brushstart,m_this._getSelection())),$(document).on("mousemove.geojs",m_this._handleMouseMoveDocument),$(document).on("mouseup.geojs",m_this._handleMouseUpDocument))},this._handleMouseMove=function(evt){m_state.action||(m_this._getMousePosition(evt),m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),m_this.map().geoTrigger(geo.event.mousemove,m_this.mouse()))},this._handleMouseMoveDocument=function(evt){var dx,dy,selectionObj;return m_this._getMousePosition(evt),m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),m_state.action?void(doRespond()&&(dx=m_mouse.map.x-m_state.origin.map.x-m_state.delta.x,dy=m_mouse.map.y-m_state.origin.map.y-m_state.delta.y,m_state.delta.x+=dx,m_state.delta.y+=dy,"pan"===m_state.action?m_this.map().pan({x:dx,y:dy}):"zoom"===m_state.action?m_this.map().zoom(m_this.map().zoom()-dy*m_options.zoomScale/120):"select"===m_state.action&&(selectionObj=m_this._getSelection(),m_this.map().geoTrigger(geo.event.brush,selectionObj)),evt.preventDefault())):void console.log("WARNING: Invalid state in mapInteractor.")},this._handleMouseUpDocument=function(evt){var selectionObj,oldAction;m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),$(document).off(".geojs"),m_mouse.buttons.right&&evt.preventDefault(),"select"===m_state.action&&(selectionObj=m_this._getSelection(),m_selectionLayer.clear(),m_this.map().deleteLayer(m_selectionLayer),m_selectionLayer=null,m_selectionPlane=null,m_this.map().geoTrigger(geo.event.brushend,selectionObj)),oldAction=m_state.action,m_state={},m_options.momentum.enabled&&"pan"===oldAction&&m_this.springBack(!0)},this._handleMouseUp=function(evt){m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),m_this.map().geoTrigger(geo.event.mouseclick,m_this.mouse())},this._handleMouseWheel=function(evt){var zoomFactor,direction;return evt.deltaFactor=1,1===evt.originalEvent.deltaMode?evt.deltaFactor=12:2===evt.originalEvent.deltaMode&&(evt.deltaFactor=$(window).height()),evt.deltaX=evt.originalEvent.deltaX||0,evt.deltaY=evt.originalEvent.deltaY||0,m_this._getMouseModifiers(evt),evt.deltaX=evt.deltaX*m_options.wheelScaleX*evt.deltaFactor/120,evt.deltaY=evt.deltaY*m_options.wheelScaleY*evt.deltaFactor/120,evt.preventDefault(),doRespond()?(evt.deltaX+=m_wheelQueue.x,evt.deltaY+=m_wheelQueue.y,m_wheelQueue={x:0,y:0},void(m_options.panWheelEnabled&&eventMatch("wheel",m_options.panWheelModifiers)?m_this.map().pan({x:evt.deltaX,y:-evt.deltaY}):m_options.zoomWheelEnabled&&eventMatch("wheel",m_options.zoomWheelModifiers)&&(zoomFactor=-evt.deltaY,direction=m_mouse.map,m_this.map().zoom(m_this.map().zoom()+zoomFactor,direction)))):(m_wheelQueue.x+=evt.deltaX,void(m_wheelQueue.y+=evt.deltaY))},this.springBack=function(initialVelocity){"momentum"!==m_state.action&&(initialVelocity||(m_mouse.velocity={x:0,y:0}),m_state.action="momentum",m_state.origin=m_this.mouse(),m_state.start=new Date,m_state.handler=function(){var v,s,last,dt;if(dt=Math.min(m_mouse.deltaTime,30),"momentum"===m_state.action&&m_this.map()&&!m_this.map().transition()){if(last=m_state.start.valueOf(),m_state.start=new Date,v=modifyVelocity(m_mouse.velocity,m_state.start-last),!v)return void(m_state={});s=calcSpeed(v),s>m_options.momentum.maxSpeed&&(s=m_options.momentum.maxSpeed/s,v.x=v.x*s,v.y=v.y*s),isFinite(v.x)&&isFinite(v.y)||(v.x=0,v.y=0),m_mouse.velocity.x=v.x,m_mouse.velocity.y=v.y,m_this.map().pan({x:m_mouse.velocity.x*dt,y:m_mouse.velocity.y*dt}),m_state.handler&&window.requestAnimationFrame(m_state.handler)}},m_state.handler&&window.requestAnimationFrame(m_state.handler))},this._handleDoubleClick=function(){},this.destroy=function(){m_this._disconnectEvents(),m_this.map(null)},this.mouse=function(){return $.extend(!0,{},m_mouse)},this.keyboard=function(){return $.extend(!0,{},m_keyboard)},this.state=function(){return $.extend(!0,{},m_state)},this.simulateEvent=function(type,options){var evt,page,offset,which;return m_this.map()?(page=options.page||{},options.map&&(offset=$node.offset(),page.x=options.map.x+offset.left,page.y=options.map.y+offset.top),"left"===options.button?which=1:"right"===options.button?which=3:"middle"===options.button&&(which=2),options.modifiers=options.modifiers||[],options.wheelDelta=options.wheelDelta||{},evt=$.Event(type,{pageX:page.x,pageY:page.y,which:which,altKey:options.modifiers.indexOf("alt")>=0,ctrlKey:options.modifiers.indexOf("ctrl")>=0,metaKey:options.modifiers.indexOf("meta")>=0,shiftKey:options.modifiers.indexOf("shift")>=0,originalEvent:{deltaX:options.wheelDelta.x,deltaY:options.wheelDelta.y,deltaMode:options.wheelMode}}),void $node.trigger(evt)):m_this},this._connectEvents(),this},inherit(geo.mapInteractor,geo.object),geo.clock=function(opts){"use strict";if(!(this instanceof geo.clock))return new geo.clock(opts);opts=opts||{},geo.object.call(this,opts);var m_this=this,m_now=new Date(0),m_start=null,m_end=null,m_step=null,m_rate=null,m_loop=Number.POSITIVE_INFINITY,m_currentLoop=0,m_state="stop",m_currentAnimation=null,m_object=null;this.object=function(arg){return void 0===arg?m_object:(m_object=arg,m_this)},this._attached=function(){return m_object instanceof geo.object},this.now=function(arg){var previous=m_now;return void 0===arg?m_now:(m_now=arg,m_now!==previous&&m_this._attached()&&m_this.object().geoTrigger(geo.event.clock.change,{previous:previous,current:m_now,clock:m_this}),m_this)},this.start=function(arg){return void 0===arg?m_start:(m_start=arg,m_this)},this.end=function(arg){return void 0===arg?m_end:(m_end=arg,m_this)},this.step=function(arg){return void 0===arg?m_step:(m_step=arg,m_this)},this.loop=function(arg){return void 0===arg?m_loop:(m_loop=arg,m_this)},this.state=function(arg,step){return void 0===arg?m_state:["stop","play","pause"].indexOf(arg)<0?(console.log("WARNING: Ignored invalid state: "+arg),m_this):("play"===arg&&"stop"===m_state&&(m_currentLoop=0,m_this.now(m_this.start())),"play"===arg&&"play"!==m_state&&(m_state=arg,m_this._animate(step||1)),m_state=arg,m_this)},this.framerate=function(arg){return void 0===arg?m_rate:(m_rate=arg,m_this)},this.stepForward=function(){return m_this.state("pause"),m_this._setNextFrame(1),m_this},this.stepBackward=function(){return m_this.state("pause"),m_this._setNextFrame(-1),m_this},this._setNextFrame=function(step){var next=new Date(m_this.now().valueOf()+step*m_this.step());return next>=m_this.end()||next<=m_this.start()?m_this.loop()<=m_currentLoop?void m_this.state("stop"):(m_currentLoop+=1,void m_this.now(step>=0?m_this.start():m_this.end())):void m_this.now(next)},this._animate=function(step){function frame(){myAnimation===m_currentAnimation&&(m_this._setNextFrame(step),"play"===m_this.state()?m_this.framerate()?window.setTimeout(frame,1e3/m_this.framerate()):window.requestAnimationFrame(frame):m_this._attached()&&m_this.object().geoTrigger(geo.event.clock[m_this.state()],{current:m_this.now(),clock:m_this}))}var myAnimation={};m_currentAnimation=myAnimation,m_this._attached()&&m_this.object().geoTrigger(geo.event.clock.play,{current:m_this.now(),clock:m_this}),m_this.framerate()?window.setTimeout(frame,1e3/m_this.framerate()):window.requestAnimationFrame(frame)}},inherit(geo.clock,geo.object),geo.fileReader=function(arg){"use strict";function newFileReader(done,progress){var reader=new FileReader;return progress&&(reader.onprogress=progress),reader.onloadend=function(){reader.result||done(reader.error),done(reader.result)},reader}if(!(this instanceof geo.fileReader))return new geo.fileReader(arg);if(geo.object.call(this),arg=arg||{},!(arg.layer instanceof geo.featureLayer))throw"fileReader must be given a feature layer";var m_layer=arg.layer;return this.layer=function(){return m_layer},this.canRead=function(){return!1},this.read=function(file,done){done(!1)},this._getString=function(file,done,progress){var reader=newFileReader(done,progress);reader.readAsText(file)},this._getArrayBuffer=function(file,done,progress){var reader=newFileReader(done,progress);reader.readAsText(file)},this},inherit(geo.fileReader,geo.object),geo.jsonReader=function(arg){"use strict";if(!(this instanceof geo.jsonReader))return new geo.jsonReader(arg);var m_this=this,m_style=arg.style||{};m_style=$.extend({strokeWidth:2,strokeColor:{r:0,g:0,b:0},strokeOpacity:1,fillColor:{r:1,g:0,b:0},fillOpacity:1},m_style),geo.fileReader.call(this,arg),this.canRead=function(file){if(file instanceof File)return"application/json"===file.type||file.name.match(/\.json$/);if("string"==typeof file){try{JSON.parse(file)}catch(e){return!1}return!0}try{if(Array.isArray(m_this._featureArray(file)))return!0}catch(e){}return!1},this._readObject=function(file,done,progress){function onDone(fileString){"string"!=typeof fileString&&done(!1);try{object=JSON.parse(fileString),done(object)}catch(e){object||$.ajax({type:"GET",url:fileString,dataType:"text"}).done(function(data){object=JSON.parse(data),done(object)}).fail(function(){done(!1)})}}var object;file instanceof File?m_this._getString(file,onDone,progress):"string"==typeof file?onDone(file):done(file)},this._featureArray=function(spec){if("FeatureCollection"===spec.type)return spec.features||[];if("GeometryCollection"===spec.type)throw"GeometryCollection not yet implemented.";if(Array.isArray(spec.coordinates))return spec;throw"Unsupported collection type: "+spec.type},this._featureType=function(spec){var geometry=spec.geometry||{};return"Point"===geometry.type||"MultiPoint"===geometry.type?"point":"LineString"===geometry.type?"line":"Polygon"===geometry.type?"polygon":null},this._getCoordinates=function(spec){var elv,geometry=spec.geometry||{},coordinates=geometry.coordinates||[];return(2===coordinates.length||3===coordinates.length)&&isFinite(coordinates[0])&&isFinite(coordinates[1])?(isFinite(coordinates[2])&&(elv=coordinates[2]),[{x:coordinates[0],y:coordinates[1],z:elv}]):(Array.isArray(coordinates[0][0])&&(coordinates=coordinates[0]),coordinates.map(function(c){return{x:c[0],y:c[1],z:c[2]}}))},this._getStyle=function(spec){return spec.properties},this.read=function(file,done,progress){function _done(object){var features,allFeatures=[];features=m_this._featureArray(object),features.forEach(function(feature){var type=m_this._featureType(feature),coordinates=m_this._getCoordinates(feature),style=m_this._getStyle(feature);type?"line"===type?(style.fill=style.fill||!1,allFeatures.push(m_this._addFeature(type,[coordinates],style,feature.properties))):"point"===type?(style.stroke=style.stroke||!1,allFeatures.push(m_this._addFeature(type,coordinates,style,feature.properties))):"polygon"===type&&(style.fill=void 0===style.fill?!0:style.fill,style.fillOpacity=void 0===style.fillOpacity?.25:style.fillOpacity,allFeatures.push(m_this._addFeature("line",[coordinates],style,feature.properties))):console.log("unsupported feature type: "+feature.geometry.type)}),done&&done(allFeatures)}m_this._readObject(file,_done,progress)},this._buildData=function(coordinates,properties,style){return coordinates.map(function(coord){return{coordinates:coord,properties:properties,style:style}})},this._addFeature=function(type,coordinates,style,properties){var _style=$.extend({},m_style,style),feature=m_this.layer().createFeature(type).data(m_this._buildData(coordinates,properties,style)).style(_style);return"line"===type?feature.line(function(d){return d.coordinates}):feature.position(function(d){return d.coordinates}),feature}},inherit(geo.jsonReader,geo.fileReader),geo.registerFileReader("jsonReader",geo.jsonReader),geo.map=function(arg){"use strict";function resizeSelf(){m_this.resize(0,0,m_node.width(),m_node.height())}if(!(this instanceof geo.map))return new geo.map(arg);arg=arg||{},geo.sceneObject.call(this,arg),arg.layers=void 0===arg.layers?[]:arg.layers;var m_this=this,s_exit=this._exit,m_x=0,m_y=0,m_node=$(arg.node),m_width=arg.width||m_node.width(),m_height=arg.height||m_node.height(),m_gcs=void 0===arg.gcs?"EPSG:4326":arg.gcs,m_uigcs=void 0===arg.uigcs?"EPSG:4326":arg.uigcs,m_center={x:0,y:0},m_zoom=void 0===arg.zoom?1:arg.zoom,m_baseLayer=null,m_fileReader=null,m_interactor=null,m_validZoomRange={min:0,max:16},m_transition=null,m_queuedTransition=null,m_clock=null,m_bounds={};return arg.center=geo.util.normalizeCoordinates(arg.center),arg.autoResize=void 0===arg.autoResize?!0:arg.autoResize,arg.clampBounds=void 0===arg.clampBounds?!0:arg.clampBounds,this.gcs=function(arg){return void 0===arg?m_gcs:(m_gcs=arg,m_this)},this.uigcs=function(){return m_uigcs},this.node=function(){return m_node},this.zoom=function(val,direction){var base,evt,recenter=!1;return void 0===val?m_zoom:(val=Math.min(m_validZoomRange.max,Math.max(val,m_validZoomRange.min)),val===m_zoom?m_this:(base=m_this.baseLayer(),evt={geo:{},zoomLevel:val,screenPosition:direction,eventType:geo.event.zoom},base&&base.renderer().geoTrigger(geo.event.zoom,evt,!0),recenter=evt.center,evt.geo.preventDefault||(m_zoom=val,m_this._updateBounds(),m_this.children().forEach(function(child){child.geoTrigger(geo.event.zoom,evt,!0)}),m_this.modified()),evt.center?m_this.center(recenter):m_this.pan({x:0,y:0}),m_this))},this.pan=function(delta,force){var evt,pt,corner1,corner2,base=m_this.baseLayer();return arg.clampBounds&&!force&&m_width&&m_height&&(pt=m_this.displayToGcs({x:delta.x,y:delta.y}),corner1=m_this.gcsToDisplay({x:-180,y:82}),corner2=m_this.gcsToDisplay({x:180,y:-82}),corner1.x>0&&corner2.x0&&corner2.y0||input instanceof Object))throw"Conversion method latLonToDisplay does not handle "+input;return world=m_baseLayer.toLocal(input),output=m_baseLayer.renderer().worldToDisplay(world)},this.displayToGcs=function(input){var output;if(!(input instanceof Array&&input.length>0||input instanceof Object))throw"Conversion method displayToGcs does not handle "+input;return output=m_baseLayer.renderer().displayToWorld(input),output=m_baseLayer.fromLocal(output)},this.query=function(){},this.baseLayer=function(baseLayer){var save;return void 0!==baseLayer?(m_gcs!==baseLayer.gcs()&&m_this.gcs(baseLayer.gcs()),m_baseLayer=baseLayer,m_baseLayer.referenceLayer(!0),arg.center&&m_this.center(arg.center,!0),save=m_zoom,m_zoom=null,m_this.zoom(save),m_this._updateBounds(),m_this.pan({x:0,y:0}),m_this):m_baseLayer},this.draw=function(){var i,layers=m_this.children();for(m_this.geoTrigger(geo.event.draw,{type:geo.event.draw,target:m_this}),m_this._update(),i=0;i=m_transition.end.time||next)return next||(m_this.center(m_transition.end.center),m_this.zoom(m_transition.end.zoom)),m_transition=null,m_this.geoTrigger(geo.event.transitionend,defaultOpts),done&&done(),void(next&&(m_queuedTransition=null,m_this.transition(next)));var z=m_transition.ease((time-m_transition.start.time)/defaultOpts.duration),p=m_transition.interp(z);m_transition.zCoord&&(p[2]=z2zoom(p[2])),m_this.center({x:p[0],y:p[1]}),m_this.zoom(p[2]),window.requestAnimationFrame(anim)}if(void 0===opts)return m_transition;if(m_transition)return m_queuedTransition=opts,m_this;var defaultOpts={center:m_this.center(),zoom:m_this.zoom(),duration:1e3,ease:function(t){return t},interp:defaultInterp,done:null,zCoord:!0};return opts.center&&(opts.center=geo.util.normalizeCoordinates(opts.center)),$.extend(defaultOpts,opts),m_transition={start:{center:m_this.center(),zoom:m_this.zoom()},end:{center:defaultOpts.center,zoom:defaultOpts.zoom},ease:defaultOpts.ease,zCoord:defaultOpts.zCoord,done:defaultOpts.done,duration:defaultOpts.duration},defaultOpts.zCoord?m_transition.interp=defaultOpts.interp([m_transition.start.center.x,m_transition.start.center.y,zoom2z(m_transition.start.zoom)],[m_transition.end.center.x,m_transition.end.center.y,zoom2z(m_transition.end.zoom)]):m_transition.interp=defaultOpts.interp([m_transition.start.center.x,m_transition.start.center.y,m_transition.start.zoom],[m_transition.end.center.x,m_transition.end.center.y,m_transition.end.zoom]),m_this.geoTrigger(geo.event.transitionstart,defaultOpts),defaultOpts.cancelNavigation?(m_this.geoTrigger(geo.event.transitionend,defaultOpts),m_this):(defaultOpts.cancelAnimation?(defaultOpts.duration=0,anim(0)):window.requestAnimationFrame(anim),m_this)},this._updateBounds=function(){m_bounds.lowerLeft=m_this.displayToGcs({x:0,y:m_height}),m_bounds.lowerRight=m_this.displayToGcs({x:m_width,y:m_height}),m_bounds.upperLeft=m_this.displayToGcs({x:0,y:0}),m_bounds.upperRight=m_this.displayToGcs({x:m_width,y:0})},this.bounds=function(bds){var nav;return void 0===bds?m_bounds:(nav=m_this.zoomAndCenterFromBounds(bds),m_this.zoom(nav.zoom),m_this.center(nav.center),m_bounds)},this.zoomAndCenterFromBounds=function(bds){var ll,ur,dx,dy,zx,zy,center;if(ll=geo.util.normalizeCoordinates(bds.lowerLeft||{}),ur=geo.util.normalizeCoordinates(bds.upperRight||{}),ll.x>=ur.x||ll.y>=ur.y)throw new Error("Invalid bounds provided");return center={x:(ll.x+ur.x)/2,y:(ll.y+ur.y)/2},dx=m_bounds.upperRight.x-m_bounds.lowerLeft.x,dy=m_bounds.upperRight.y-m_bounds.lowerLeft.y,zx=m_zoom-Math.log2((ur.x-ll.x)/dx),zy=m_zoom-Math.log2((ur.y-ll.y)/dy),{zoom:Math.min(zx,zy),center:center}},this.interactor(arg.interactor||geo.mapInteractor()),this.clock(arg.clock||geo.clock()),arg.autoResize&&$(window).resize(resizeSelf),this},geo.map.create=function(spec){"use strict";var map=geo.map(spec);return map?(spec.data=spec.data||[],spec.layers=spec.layers||[],spec.layers.forEach(function(l){l.data=l.data||spec.data,l.layer=geo.layer.create(map,l)}),map):(console.warn("Could not create map."),null)},inherit(geo.map,geo.sceneObject),geo.feature=function(arg){"use strict";if(!(this instanceof geo.feature))return new geo.feature(arg);geo.sceneObject.call(this),arg=arg||{};var m_this=this,s_exit=this._exit,m_selectionAPI=void 0===arg.selectionAPI?!1:arg.selectionAPI,m_style={},m_layer=void 0===arg.layer?null:arg.layer,m_gcs=void 0===arg.gcs?"EPSG:4326":arg.gcs,m_visible=void 0===arg.visible?!0:arg.visible,m_bin=void 0===arg.bin?0:arg.bin,m_renderer=void 0===arg.renderer?null:arg.renderer,m_dataTime=geo.timestamp(),m_buildTime=geo.timestamp(),m_updateTime=geo.timestamp(),m_selectedFeatures=[];return this._bindMouseHandlers=function(){m_selectionAPI&&(m_this._unbindMouseHandlers(),m_this.geoOn(geo.event.mousemove,m_this._handleMousemove),m_this.geoOn(geo.event.mouseclick,m_this._handleMouseclick),m_this.geoOn(geo.event.brushend,m_this._handleBrushend),m_this.geoOn(geo.event.brush,m_this._handleBrush))},this._unbindMouseHandlers=function(){m_this.geoOff(geo.event.mousemove,m_this._handleMousemove),m_this.geoOff(geo.event.mouseclick,m_this._handleMouseclick),m_this.geoOff(geo.event.brushend,m_this._handleBrushend),m_this.geoOff(geo.event.brush,m_this._handleBrush)},this.pointSearch=function(){return{index:[],found:[]}},this._handleMousemove=function(){var mouse=m_this.layer().map().interactor().mouse(),data=m_this.data(),over=m_this.pointSearch(mouse.geo),newFeatures=[],oldFeatures=[],lastTop=-1,top=-1;m_selectedFeatures.length&&(lastTop=m_selectedFeatures[m_selectedFeatures.length-1]),newFeatures=over.index.filter(function(i){return m_selectedFeatures.indexOf(i)<0}),oldFeatures=m_selectedFeatures.filter(function(i){return over.index.indexOf(i)<0}),geo.feature.eventID+=1,newFeatures.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.mouseover,{data:data[i],index:i,mouse:mouse,eventID:geo.feature.eventID,top:idx===newFeatures.length-1},!0)}),geo.feature.eventID+=1,oldFeatures.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.mouseout,{data:data[i],index:i,mouse:mouse,eventID:geo.feature.eventID,top:idx===oldFeatures.length-1},!0)}),geo.feature.eventID+=1,over.index.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.mousemove,{data:data[i],index:i,mouse:mouse,eventID:geo.feature.eventID,top:idx===over.index.length-1},!0)}),m_selectedFeatures=over.index,m_selectedFeatures.length&&(top=m_selectedFeatures[m_selectedFeatures.length-1]),lastTop!==top&&(-1!==lastTop&&m_this.geoTrigger(geo.event.feature.mouseoff,{data:data[lastTop],index:lastTop,mouse:mouse},!0),-1!==top&&m_this.geoTrigger(geo.event.feature.mouseon,{data:data[top],index:top,mouse:mouse},!0))},this._handleMouseclick=function(){var mouse=m_this.layer().map().interactor().mouse(),data=m_this.data(),over=m_this.pointSearch(mouse.geo);geo.feature.eventID+=1,over.index.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.mouseclick,{data:data[i],index:i,mouse:mouse,eventID:geo.feature.eventID,top:idx===over.index.length-1},!0)})},this._handleBrush=function(brush){var idx=m_this.boxSearch(brush.gcs.lowerLeft,brush.gcs.upperRight),data=m_this.data();geo.feature.eventID+=1,idx.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.brush,{data:data[i],index:i,mouse:brush.mouse,brush:brush,eventID:geo.feature.eventID,top:idx===idx.length-1},!0)})},this._handleBrushend=function(brush){var idx=m_this.boxSearch(brush.gcs.lowerLeft,brush.gcs.upperRight),data=m_this.data();geo.feature.eventID+=1,idx.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.brushend,{data:data[i],index:i,mouse:brush.mouse,brush:brush,eventID:geo.feature.eventID,top:idx===idx.length-1},!0)})},this.style=function(arg1,arg2){return void 0===arg1?m_style:"string"==typeof arg1&&void 0===arg2?m_style[arg1]:void 0===arg2?(m_style=$.extend({},m_style,arg1),m_this.modified(),m_this):(m_style[arg1]=arg2,m_this.modified(),m_this)},this.style.get=function(key){var tmp,out;if(void 0===key){var k,all={};for(k in m_style)m_style.hasOwnProperty(k)&&(all[k]=m_this.style.get(k));return all}return key.toLowerCase().match(/color$/)?geo.util.isFunction(m_style[key])?(tmp=geo.util.ensureFunction(m_style[key]),out=function(){return geo.util.convertColor(tmp.apply(this,arguments))}):out=geo.util.ensureFunction(geo.util.convertColor(m_style[key])):out=geo.util.ensureFunction(m_style[key]),out},this.layer=function(){return m_layer},this.renderer=function(){return m_renderer},this.drawables=function(){return m_this._drawables()},this.gcs=function(val){return void 0===val?m_gcs:(m_gcs=val,m_this.modified(),m_this)},this.visible=function(val){return void 0===val?m_visible:(m_visible=val,m_this.modified(),m_visible?m_this._bindMouseHandlers():m_this._unbindMouseHandlers(),m_this)},this.bin=function(val){return void 0===val?m_bin:(m_bin=val,m_this.modified(),m_this)},this.dataTime=function(val){return void 0===val?m_dataTime:(m_dataTime=val,m_this.modified(),m_this)},this.buildTime=function(val){return void 0===val?m_buildTime:(m_buildTime=val,m_this.modified(),m_this)},this.updateTime=function(val){return void 0===val?m_updateTime:(m_updateTime=val,m_this.modified(),m_this)},this.data=function(data){return void 0===data?m_this.style("data")||[]:(m_this.style("data",data),m_this.dataTime().modified(),m_this.modified(),m_this)},this.selectionAPI=function(){return m_selectionAPI},this._init=function(arg){if(!m_layer)throw"Feature requires a valid layer";m_style=$.extend({},{opacity:1},void 0===arg.style?{}:arg.style),m_this._bindMouseHandlers()},this._build=function(){},this._drawables=function(){},this._update=function(){},this._exit=function(){m_this._unbindMouseHandlers(),m_selectedFeatures=[],m_style={},arg={},s_exit()},this._init(arg),this},geo.feature.eventID=0,geo.feature.create=function(layer,spec){"use strict";var type=spec.type;if(!layer instanceof geo.layer)return console.warn("Invalid layer"),null;if("object"!=typeof spec)return console.warn("Invalid spec"),null;var feature=layer.createFeature(type);return feature?(spec=spec||{},spec.data=spec.data||[],feature.style(spec)):(console.warn("Could not create feature type '"+type+"'"),null)},inherit(geo.feature,geo.sceneObject),geo.pointFeature=function(arg){"use strict";if(!(this instanceof geo.pointFeature))return new geo.pointFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,s_init=this._init,m_rangeTree=null,m_rangeTreeTime=geo.timestamp(),s_data=this.data,m_maxRadius=0;return this.position=function(val){return void 0===val?m_this.style("position"):(m_this.style("position",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this._updateRangeTree=function(){if(!(m_rangeTreeTime.getMTime()>=m_this.dataTime().getMTime())){var pts,position,radius=m_this.style.get("radius"),stroke=m_this.style.get("stroke"),strokeWidth=m_this.style.get("strokeWidth");position=m_this.position(),m_maxRadius=0,pts=m_this.data().map(function(d,i){var pt=position(d);return pt.idx=i,m_maxRadius=Math.max(m_maxRadius,radius(d,i)+(stroke(d,i)?strokeWidth(d,i):0)),pt}),m_rangeTree=new geo.util.RangeTree(pts),m_rangeTreeTime.modified()}},this.pointSearch=function(p){var min,max,data,box,map,pt,idx=[],found=[],ifound=[],stroke=m_this.style.get("stroke"),strokeWidth=m_this.style.get("strokeWidth"),radius=m_this.style.get("radius");
-return 3!==numberOfComponents&&console.log("[warning] getPosition assumes three component data"),[data[offset+index*stride],data[offset+index*stride+1],data[offset+index*stride+2]]},this.getScalar=function(index){var numberOfComponents,sizeOfDataType,data,stride,offset,attr=vgl.vertexAttributeKeys.Scalar,sourceData=this.sourceData(attr);return sourceData?(numberOfComponents=sourceData.attributeNumberOfComponents(attr),sizeOfDataType=sourceData.sizeOfAttributeDataType(attr),data=sourceData.data(),stride=sourceData.attributeStride(attr)/sizeOfDataType,offset=sourceData.attributeOffset(attr)/sizeOfDataType,index*stride+offset>=data.length&&console.log("access out of bounds in getScalar"),data[index*stride+offset]):null},this},inherit(vgl.geometryData,vgl.data),vgl.mapper=function(arg){"use strict";function deleteVertexBufferObjects(){var i;for(i=0;ii;++i){for(bufferId=gl.createBuffer(),gl.bindBuffer(gl.ARRAY_BUFFER,bufferId),data=m_geomData.source(i).data(),data instanceof Float32Array||(data=new Float32Array(data)),gl.bufferData(gl.ARRAY_BUFFER,data,m_dynamicDraw?gl.DYNAMIC_DRAW:gl.STATIC_DRAW),keys=m_geomData.source(i).keys(),ks=[],j=0;jk;++k)bufferId=gl.createBuffer(),gl.bindBuffer(gl.ARRAY_BUFFER,bufferId),gl.bufferData(gl.ARRAY_BUFFER,m_geomData.primitive(k).indices(),gl.STATIC_DRAW),m_buffers[i++]=bufferId;m_glCompileTimestamp.modified()}}function cleanUpDrawObjects(){m_bufferVertexAttributeMap={},m_buffers=[]}function setupDrawObjects(){deleteVertexBufferObjects(),cleanUpDrawObjects(),createVertexBufferObjects(),m_dirty=!1}if(!(this instanceof vgl.mapper))return new vgl.mapper(arg);vgl.boundingObject.call(this),arg=arg||{};var m_dirty=!0,m_color=[0,1,1],m_geomData=null,m_buffers=[],m_bufferVertexAttributeMap={},m_dynamicDraw=void 0===arg.dynamicDraw?!1:arg.dynamicDraw,m_glCompileTimestamp=vgl.timestamp();return this.computeBounds=function(){if(null===m_geomData||"undefined"==typeof m_geomData)return void this.resetBounds();var computeBoundsTimestamp=this.computeBoundsTimestamp(),boundsDirtyTimestamp=this.boundsDirtyTimestamp(),geomBounds=null;boundsDirtyTimestamp.getMTime()>computeBoundsTimestamp.getMTime()&&(geomBounds=m_geomData.bounds(),this.setBounds(geomBounds[0],geomBounds[1],geomBounds[2],geomBounds[3],geomBounds[4],geomBounds[5]),computeBoundsTimestamp.modified())},this.color=function(){return m_color},this.setColor=function(r,g,b){m_color[0]=r,m_color[1]=g,m_color[2]=b,this.modified()},this.geometryData=function(){return m_geomData},this.setGeometryData=function(geom){m_geomData!==geom&&(m_geomData=geom,this.modified(),this.boundsDirtyTimestamp().modified())},this.updateSourceBuffer=function(sourceName,values){for(var bufferIndex=-1,i=0;ibufferIndex||bufferIndex>=m_buffers.length?!1:(values||(values=m_geomData.source(i).dataToFloat32Array()),gl.bindBuffer(gl.ARRAY_BUFFER,m_buffers[bufferIndex]),values instanceof Float32Array?gl.bufferSubData(gl.ARRAY_BUFFER,0,values):gl.bufferSubData(gl.ARRAY_BUFFER,0,new Float32Array(values)),!0)},this.getSourceBuffer=function(sourceName){var source=m_geomData.sourceByName(sourceName);return source?source.dataToFloat32Array():new Float32Array},this.render=function(renderState){this.getMTime()>m_glCompileTimestamp.getMTime()&&setupDrawObjects(renderState),gl.vertexAttrib3fv(vgl.vertexAttributeKeys.Color,this.color());var i,bufferIndex=0,j=0,noOfPrimitives=null,primitive=null;for(i in m_bufferVertexAttributeMap)if(m_bufferVertexAttributeMap.hasOwnProperty(i)){for(gl.bindBuffer(gl.ARRAY_BUFFER,m_buffers[bufferIndex]),j=0;jj;++j){switch(gl.bindBuffer(gl.ARRAY_BUFFER,m_buffers[bufferIndex++]),primitive=m_geomData.primitive(j),primitive.primitiveType()){case gl.POINTS:gl.drawArrays(gl.POINTS,0,primitive.numberOfIndices());break;case gl.LINES:gl.drawArrays(gl.LINES,0,primitive.numberOfIndices());break;case gl.LINE_STRIP:gl.drawArrays(gl.LINE_STRIP,0,primitive.numberOfIndices());break;case gl.TRIANGLES:gl.drawArrays(gl.TRIANGLES,0,primitive.numberOfIndices());break;case gl.TRIANGLE_STRIP:gl.drawArrays(gl.TRIANGLE_STRIP,0,primitive.numberOfIndices())}gl.bindBuffer(gl.ARRAY_BUFFER,null)}},this},inherit(vgl.mapper,vgl.boundingObject),vgl.groupMapper=function(){"use strict";if(!(this instanceof vgl.groupMapper))return new vgl.groupMapper;vgl.mapper.call(this);var m_createMappersTimestamp=vgl.timestamp(),m_mappers=[],m_geomDataArray=[];return this.geometryData=function(index){return void 0!==index&&index0?m_geomDataArray[0]:null},this.setGeometryData=function(geom){(1!==m_geomDataArray.length||m_geomDataArray[0]!==geom)&&(m_geomDataArray=[],m_geomDataArray.push(geom),this.modified())},this.geometryDataArray=function(){return m_geomDataArray},this.setGeometryDataArray=function(geoms){if(geoms instanceof Array){if(m_geomDataArray!==geoms)return m_geomDataArray=[],m_geomDataArray=geoms,this.modified(),!0}else console.log("[error] Requies array of geometry data");return!1},this.computeBounds=function(){if(null===m_geomDataArray||void 0===m_geomDataArray)return void this.resetBounds();var computeBoundsTimestamp=this.computeBoundsTimestamp(),boundsDirtyTimestamp=this.boundsDirtyTimestamp(),m_bounds=this.bounds(),geomBounds=null,i=null;if(boundsDirtyTimestamp.getMTime()>computeBoundsTimestamp.getMTime()){for(i=0;igeomBounds[0]&&(m_bounds[0]=geomBounds[0]),m_bounds[1]geomBounds[2]&&(m_bounds[2]=geomBounds[2]),m_bounds[3]geomBounds[4]&&(m_bounds[4]=geomBounds[4]),m_bounds[5]m_createMappersTimestamp.getMTime()){for(i=0;i0&&m_resetScene&&(this.resetCamera(),m_resetScene=!1),i=0;idiagonals[1]?diagonals[0]>diagonals[2]?diagonals[0]/2:diagonals[2]/2:diagonals[1]>diagonals[2]?diagonals[1]/2:diagonals[2]/2,angle=aspect>=1?2*Math.atan(Math.tan(.5*angle)/aspect):2*Math.atan(Math.tan(.5*angle)*aspect),distance=radius/Math.sin(.5*angle),vup=m_camera.viewUpDirection(),Math.abs(vec3.dot(vup,vn))>.999&&m_camera.setViewUpDirection(-vup[2],vup[0],vup[1]),m_camera.setFocalPoint(center[0],center[1],center[2]),m_camera.setPosition(center[0]+distance*-vn[0],center[1]+distance*-vn[1],center[2]+distance*-vn[2]),this.resetCameraClippingRange(visibleBounds)},this.hasValidBounds=function(bounds){return bounds[0]==Number.MAX_VALUE||bounds[1]==-Number.MAX_VALUE||bounds[2]==Number.MAX_VALUE||bounds[3]==-Number.MAX_VALUE||bounds[4]==Number.MAX_VALUE||bounds[5]==-Number.MAX_VALUE?!1:!0},this.resetCameraClippingRange=function(bounds){if("undefined"==typeof bounds&&(m_camera.computeBounds(),bounds=m_camera.bounds()),this.hasValidBounds(bounds)){var vn=m_camera.viewPlaneNormal(),position=m_camera.position(),a=-vn[0],b=-vn[1],c=-vn[2],d=-(a*position[0]+b*position[1]+c*position[2]),range=vec2.create(),dist=null,i=null,j=null,k=null;if(m_resetClippingRange){for(range[0]=a*bounds[0]+b*bounds[2]+c*bounds[4]+d,range[1]=1e-18,k=0;2>k;k++)for(j=0;2>j;j++)for(i=0;2>i;i++)dist=a*bounds[i]+b*bounds[2+j]+c*bounds[4+k]+d,range[0]=distrange[1]?dist:range[1];range[0]<0&&(range[0]=0),range[0]=.99*range[0]-.5*(range[1]-range[0]),range[1]=1.01*range[1]+.5*(range[1]-range[0]),range[0]=range[0]>=range[1]?.01*range[1]:range[0],m_nearClippingPlaneTolerance||(m_nearClippingPlaneTolerance=.01,null!==gl&&gl.getParameter(gl.DEPTH_BITS)>16&&(m_nearClippingPlaneTolerance=.001)),range[0]x||0>y||0>width||0>height)&&console.log("[error] Invalid position and resize values",x,y,width,height),m_resizable&&(m_width=width,m_height=height,m_camera.setViewAspect(m_width/m_height),this.modified())},this.addActor=function(actor){return actor instanceof vgl.actor?(m_sceneRoot.addChild(actor),this.modified(),!0):!1},this.hasActor=function(actor){return m_sceneRoot.hasChild(actor)},this.addActors=function(actors){var i=null;if(actors instanceof Array){for(i=0;im_width||0===m_renderers[i].width()||m_renderers[i].height()>m_height||0===m_renderers[i].height())&&m_renderers[i].resize(m_x,m_y,m_width,m_height);return!0}catch(e){}return gl||console("[ERROR] Unable to initialize WebGL. Your browser may not support it."),!1},this.deleteWindow=function(){},this.render=function(){var i;for(m_renderers.sort(function(a,b){return a.layer()-b.layer()}),i=0;iwidth?(m_currPos.x=0,m_outsideCanvas=!0):m_currPos.x=coords.x,coords.y<0||coords.y>height?(m_currPos.y=0,m_outsideCanvas=!0):m_currPos.y=coords.y,m_outsideCanvas!==!0?(fp=cam.focalPoint(),fwp=vec4.fromValues(fp[0],fp[1],fp[2],1),fdp=ren.worldToDisplay(fwp,cam.viewMatrix(),cam.projectionMatrix(),width,height),dp1=vec4.fromValues(m_currPos.x,m_currPos.y,fdp[2],1),dp2=vec4.fromValues(m_lastPos.x,m_lastPos.y,fdp[2],1),wp1=ren.displayToWorld(dp1,cam.viewMatrix(),cam.projectionMatrix(),width,height),wp2=ren.displayToWorld(dp2,cam.viewMatrix(),cam.projectionMatrix(),width,height),dx=wp1[0]-wp2[0],dy=wp1[1]-wp2[1],dz=wp1[2]-wp2[2],m_midMouseBtnDown&&(cam.pan(-dx,-dy,-dz),m_that.viewer().render()),m_leftMouseBtnDown&&(cam.rotate(m_lastPos.x-m_currPos.x,m_lastPos.y-m_currPos.y),ren.resetCameraClippingRange(),m_that.viewer().render()),m_rightMouseBtnDown&&(m_zTrans=2*(m_currPos.y-m_lastPos.y)/height,cam.zoom(m_zTrans>0?1-Math.abs(m_zTrans):1+Math.abs(m_zTrans)),ren.resetCameraClippingRange(),m_that.viewer().render()),m_lastPos.x=m_currPos.x,m_lastPos.y=m_currPos.y,!1):void 0},this.handleMouseDown=function(event){var coords;return 0===event.button&&(m_leftMouseBtnDown=!0),1===event.button&&(m_midMouseBtnDown=!0),2===event.button&&(m_rightMouseBtnDown=!0),coords=m_that.view.relMouseCoords(event),m_lastPos.x=coords.x<0?0:coords.x,m_lastPos.y=coords.y<0?0:coords.y,!1},this.handleMouseUp=function(event){return 0===event.button&&(m_leftMouseBtnDown=!1),1===event.button&&(m_midMouseBtnDown=!1),2===event.button&&(m_rightMouseBtnDown=!1),!1},this.handleMouseWheel=function(event){var ren=m_that.viewer().renderWindow().activeRenderer(),cam=ren.camera();return cam.zoom(event.originalEvent.wheelDelta<0?.9:1.1),ren.resetCameraClippingRange(),m_that.viewer().render(),!0},this},inherit(vgl.trackballInteractorStyle,vgl.interactorStyle),vgl.pvwInteractorStyle=function(){"use strict";function render(){m_renderer.resetCameraClippingRange(),m_that.viewer().render()}if(!(this instanceof vgl.pvwInteractorStyle))return new vgl.pvwInteractorStyle;vgl.trackballInteractorStyle.call(this);var m_width,m_height,m_renderer,m_camera,m_outsideCanvas,m_coords,m_currentMousePos,m_focalPoint,m_focusWorldPt,m_focusDisplayPt,m_displayPt1,m_displayPt2,m_worldPt1,m_worldPt2,m_dx,m_dy,m_dz,m_zTrans,m_that=this,m_leftMouseButtonDown=!1,m_rightMouseButtonDown=!1,m_middleMouseButtonDown=!1,m_mouseLastPos={
-x:0,y:0};return this.handleMouseMove=function(event){var rens=[],i=null,secCameras=[],deltaxy=null;for(m_width=m_that.viewer().renderWindow().windowSize()[0],m_height=m_that.viewer().renderWindow().windowSize()[1],m_renderer=m_that.viewer().renderWindow().activeRenderer(),m_camera=m_renderer.camera(),m_outsideCanvas=!1,m_coords=m_that.viewer().relMouseCoords(event),m_currentMousePos={x:0,y:0},rens=m_that.viewer().renderWindow().renderers(),i=0;im_width?(m_currentMousePos.x=0,m_outsideCanvas=!0):m_currentMousePos.x=m_coords.x,m_coords.y<0||m_coords.y>m_height?(m_currentMousePos.y=0,m_outsideCanvas=!0):m_currentMousePos.y=m_coords.y,m_outsideCanvas!==!0){if(m_focalPoint=m_camera.focalPoint(),m_focusWorldPt=vec4.fromValues(m_focalPoint[0],m_focalPoint[1],m_focalPoint[2],1),m_focusDisplayPt=m_renderer.worldToDisplay(m_focusWorldPt,m_camera.viewMatrix(),m_camera.projectionMatrix(),m_width,m_height),m_displayPt1=vec4.fromValues(m_currentMousePos.x,m_currentMousePos.y,m_focusDisplayPt[2],1),m_displayPt2=vec4.fromValues(m_mouseLastPos.x,m_mouseLastPos.y,m_focusDisplayPt[2],1),m_worldPt1=m_renderer.displayToWorld(m_displayPt1,m_camera.viewMatrix(),m_camera.projectionMatrix(),m_width,m_height),m_worldPt2=m_renderer.displayToWorld(m_displayPt2,m_camera.viewMatrix(),m_camera.projectionMatrix(),m_width,m_height),m_dx=m_worldPt1[0]-m_worldPt2[0],m_dy=m_worldPt1[1]-m_worldPt2[1],m_dz=m_worldPt1[2]-m_worldPt2[2],m_middleMouseButtonDown&&(m_camera.pan(-m_dx,-m_dy,-m_dz),render()),m_leftMouseButtonDown){for(deltaxy=[m_mouseLastPos.x-m_currentMousePos.x,m_mouseLastPos.y-m_currentMousePos.y],m_camera.rotate(deltaxy[0],deltaxy[1]),i=0;i0?1-Math.abs(m_zTrans):1+Math.abs(m_zTrans)),render()),m_mouseLastPos.x=m_currentMousePos.x,m_mouseLastPos.y=m_currentMousePos.y,!1}},this.handleMouseDown=function(event){return 0===event.button&&(m_leftMouseButtonDown=!0),1===event.button&&(m_middleMouseButtonDown=!0),2===event.button&&(m_rightMouseButtonDown=!0),m_coords=m_that.viewer().relMouseCoords(event),m_mouseLastPos.x=m_coords.x<0?0:m_coords.x,m_mouseLastPos.y=m_coords.y<0?0:m_coords.y,!1},this.handleMouseUp=function(event){m_that.viewer().canvas();return 0===event.button&&(m_leftMouseButtonDown=!1),1===event.button&&(m_middleMouseButtonDown=!1),2===event.button&&(m_rightMouseButtonDown=!1),!1},this},inherit(vgl.pvwInteractorStyle,vgl.trackballInteractorStyle),vgl.viewer=function(canvas){"use strict";if(!(this instanceof vgl.viewer))return new vgl.viewer(canvas);vgl.object.call(this);var m_that=this,m_canvas=canvas,m_ready=!0,m_interactorStyle=null,m_renderer=vgl.renderer(),m_renderWindow=vgl.renderWindow(m_canvas);return this.canvas=function(){return m_canvas},this.renderWindow=function(){return m_renderWindow},this.init=function(){null!==m_renderWindow?m_renderWindow.createWindow():console.log("[ERROR] No render window attached")},this.interactorStyle=function(){return m_interactorStyle},this.setInteractorStyle=function(style){style!==m_interactorStyle&&(m_interactorStyle=style,m_interactorStyle.setViewer(this),this.modified())},this.handleMouseDown=function(event){if(m_ready===!0){var fixedEvent=$.event.fix(event||window.event);2===event.button&&fixedEvent.preventDefault(),fixedEvent.state="down",fixedEvent.type=vgl.event.mousePress,$(m_that).trigger(fixedEvent)}return!0},this.handleMouseUp=function(event){if(m_ready===!0){var fixedEvent=$.event.fix(event||window.event);fixedEvent.preventDefault(),fixedEvent.state="up",fixedEvent.type=vgl.event.mouseRelease,$(m_that).trigger(fixedEvent)}return!0},this.handleMouseMove=function(event){if(m_ready===!0){var fixedEvent=$.event.fix(event||window.event);fixedEvent.preventDefault(),fixedEvent.type=vgl.event.mouseMove,$(m_that).trigger(fixedEvent)}return!0},this.handleMouseWheel=function(event){if(m_ready===!0){var fixedEvent=$.event.fix(event||window.event);fixedEvent.preventDefault(),fixedEvent.type=vgl.event.mouseWheel,$(m_that).trigger(fixedEvent)}return!0},this.handleMouseOut=function(event){if(m_ready===!0){var fixedEvent=$.event.fix(event||window.event);fixedEvent.preventDefault(),fixedEvent.type=vgl.event.mouseOut,$(m_that).trigger(fixedEvent)}return!0},this.handleKeyPress=function(event){if(m_ready===!0){var fixedEvent=$.event.fix(event||window.event);fixedEvent.preventDefault(),fixedEvent.type=vgl.event.keyPress,$(m_that).trigger(fixedEvent)}return!0},this.handleContextMenu=function(event){if(m_ready===!0){var fixedEvent=$.event.fix(event||window.event);fixedEvent.preventDefault(),fixedEvent.type=vgl.event.contextMenu,$(m_that).trigger(fixedEvent)}return!1},this.handleClick=function(event){if(m_ready===!0){var fixedEvent=$.event.fix(event||window.event);fixedEvent.preventDefault(),fixedEvent.type=vgl.event.click,$(m_that).trigger(fixedEvent)}return!1},this.handleDoubleClick=function(event){if(m_ready===!0){var fixedEvent=$.event.fix(event||window.event);fixedEvent.preventDefault(),fixedEvent.type=vgl.event.dblClick,$(m_that).trigger(fixedEvent)}return!1},this.relMouseCoords=function(event){if(void 0===event.pageX||void 0===event.pageY)throw"Missing attributes pageX and pageY on the event";var totalOffsetX=0,totalOffsetY=0,canvasX=0,canvasY=0,currentElement=m_canvas;do totalOffsetX+=currentElement.offsetLeft-currentElement.scrollLeft,totalOffsetY+=currentElement.offsetTop-currentElement.scrollTop;while(currentElement=currentElement.offsetParent);return canvasX=event.pageX-totalOffsetX,canvasY=event.pageY-totalOffsetY,{x:canvasX,y:canvasY}},this.render=function(){m_renderWindow.render()},this.bindEventHandlers=function(){$(m_canvas).on("mousedown",this.handleMouseDown),$(m_canvas).on("mouseup",this.handleMouseUp),$(m_canvas).on("mousemove",this.handleMouseMove),$(m_canvas).on("mousewheel",this.handleMouseWheel),$(m_canvas).on("contextmenu",this.handleContextMenu)},this.unbindEventHandlers=function(){$(m_canvas).off("mousedown",this.handleMouseDown),$(m_canvas).off("mouseup",this.handleMouseUp),$(m_canvas).off("mousemove",this.handleMouseMove),$(m_canvas).off("mousewheel",this.handleMouseWheel),$(m_canvas).off("contextmenu",this.handleContextMenu)},this._init=function(){this.bindEventHandlers(),m_renderWindow.addRenderer(m_renderer)},this._init(),this},inherit(vgl.viewer,vgl.object),vgl.shader=function(type){"use strict";if(!(this instanceof vgl.shader))return new vgl.shader(type);vgl.object.call(this);var m_shaderHandle=null,m_compileTimestamp=vgl.timestamp(),m_shaderType=type,m_shaderSource="";this.shaderHandle=function(){return m_shaderHandle},this.shaderType=function(){return m_shaderType},this.shaderSource=function(){return m_shaderSource},this.setShaderSource=function(source){m_shaderSource=source,this.modified()},this.compile=function(){return this.getMTime()-1)return!1;var i;for(i=0;i-1?!1:(m_uniforms.push(uniform),void this.modified())},this.addVertexAttribute=function(attr,key){m_vertexAttributes[key]=attr,this.modified()},this.uniformLocation=function(name){return m_uniformNameToLocation[name]},this.attributeLocation=function(name){return m_vertexAttributeNameToLocation[name]},this.uniform=function(name){var i;for(i=0;im_setupTimestamp.getMTime()&&this.setup(renderState),activateTextureUnit(),gl.bindTexture(gl.TEXTURE_2D,this.m_textureHandle)},this.undoBind=function(){gl.bindTexture(gl.TEXTURE_2D,null)},this.image=function(){return this.m_image},this.setImage=function(image){return null!==image?(this.m_image=image,this.updateDimensions(),this.modified(),!0):!1},this.textureUnit=function(){return this.m_textureUnit},this.setTextureUnit=function(unit){return this.m_textureUnit===unit?!1:(this.m_textureUnit=unit,this.modified(),!0)},this.width=function(){return this.m_width},this.setWidth=function(width){return null===this.m_image?!1:(this.m_width=width,this.modified(),!0)},this.depth=function(){return this.m_depth},this.setDepth=function(depth){return null===this.m_image?!1:(this.m_depth=depth,this.modified(),!0)},this.textureHandle=function(){return this.m_textureHandle},this.internalFormat=function(){return this.m_internalFormat},this.setInternalFormat=function(internalFormat){return this.m_internalFormat!==internalFormat?(this.m_internalFormat=internalFormat,this.modified(),!0):!1},this.pixelFormat=function(){return this.m_pixelFormat},this.setPixelFormat=function(pixelFormat){return null===this.m_image?!1:(this.m_pixelFormat=pixelFormat,this.modified(),!0)},this.pixelDataType=function(){return this.m_pixelDataType},this.setPixelDataType=function(pixelDataType){return null===this.m_image?!1:(this.m_pixelDataType=pixelDataType,this.modified(),!0)},this.computeInternalFormatUsingImage=function(){this.m_internalFormat=gl.RGBA,this.m_pixelFormat=gl.RGBA,this.m_pixelDataType=gl.UNSIGNED_BYTE},this.updateDimensions=function(){null!==this.m_image&&(this.m_width=this.m_image.width,this.m_height=this.m_image.height,this.m_depth=0)},this},inherit(vgl.texture,vgl.materialAttribute),vgl.lookupTable=function(){"use strict";if(!(this instanceof vgl.lookupTable))return new vgl.lookupTable;vgl.texture.call(this);var m_setupTimestamp=vgl.timestamp(),m_range=[0,0];return this.m_colorTable=[.07514311,.468049805,1,1,.247872569,.498782363,1,1,.339526309,.528909511,1,1,.409505078,.558608486,1,1,.468487184,.588057293,1,1,.520796675,.617435078,1,1,.568724526,.646924167,1,1,.613686735,.676713218,1,1,.656658579,.707001303,1,1,.698372844,.738002964,1,1,.739424025,.769954435,1,1,.780330104,.803121429,1,1,.821573924,.837809045,1,1,.863634967,.874374691,1,1,.907017747,.913245283,1,1,.936129275,.938743558,.983038586,1,.943467973,.943498599,.943398095,1,.990146732,.928791426,.917447482,1,1,.88332677,.861943246,1,1,.833985467,.803839606,1,1,.788626485,.750707739,1,1,.746206642,.701389973,1,1,.70590052,.654994046,1,1,.667019783,.610806959,1,1,.6289553,.568237474,1,1,.591130233,.526775617,1,1,.552955184,.485962266,1,1,.513776083,.445364274,1,1,.472800903,.404551679,1,1,.428977855,.363073592,1,1,.380759558,.320428137,1,.961891484,.313155629,.265499262,1,.916482116,.236630659,.209939162,1].map(function(x){return 255*x}),this.setup=function(){0===this.textureUnit()?gl.activeTexture(gl.TEXTURE0):1===this.textureUnit()&&gl.activeTexture(gl.TEXTURE1),gl.deleteTexture(this.m_textureHandle),this.m_textureHandle=gl.createTexture(),gl.bindTexture(gl.TEXTURE_2D,this.m_textureHandle),gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR),gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR),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),gl.pixelStorei(gl.UNPACK_ALIGNMENT,1),this.m_width=this.m_colorTable.length/4,this.m_height=1,this.m_depth=0,gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,this.m_width,this.m_height,this.m_depth,gl.RGBA,gl.UNSIGNED_BYTE,new Uint8Array(this.m_colorTable)),gl.bindTexture(gl.TEXTURE_2D,null),m_setupTimestamp.modified()},this.colorTable=function(){return this.m_colorTable},this.setColorTable=function(colors){return this.m_colorTable===colors?!1:(this.m_colorTable=colors,this.modified(),!0)},this.range=function(){return m_range},this.setRange=function(range){return m_range===range?!1:(m_range=range,this.modified(),!0)},this.updateRange=function(range){range instanceof Array||console.log("[error] Invalid data type for range. Requires array [min,max]"),range[0]m_range[1]&&(m_range[1]=range[1],this.modified())},this},inherit(vgl.lookupTable,vgl.texture),vgl.uniform=function(type,name){"use strict";if(!(this instanceof vgl.uniform))return new vgl.uniform;this.getTypeNumberOfComponents=function(type){switch(type){case gl.FLOAT:case gl.INT:case gl.BOOL:return 1;case gl.FLOAT_VEC2:case gl.INT_VEC2:case gl.BOOL_VEC2:return 2;case gl.FLOAT_VEC3:case gl.INT_VEC3:case gl.BOOLT_VEC3:return 3;case gl.FLOAT_VEC4:case gl.INT_VEC4:case gl.BOOL_VEC4:return 4;case gl.FLOAT_MAT3:return 9;case gl.FLOAT_MAT4:return 16;default:return 0}};var m_type=type,m_name=name,m_dataArray=[];return m_dataArray.length=this.getTypeNumberOfComponents(m_type),this.name=function(){return m_name},this.type=function(){return m_type},this.get=function(){return m_dataArray},this.set=function(value){var i=0;if(16===m_dataArray.length)for(i=0;16>i;++i)m_dataArray[i]=value[i];else if(9===m_dataArray.length)for(i=0;9>i;++i)m_dataArray[i]=value[i];else if(4===m_dataArray.length)for(i=0;4>i;++i)m_dataArray[i]=value[i];else if(3===m_dataArray.length)for(i=0;3>i;++i)m_dataArray[i]=value[i];else if(2===m_dataArray.length)for(i=0;2>i;++i)m_dataArray[i]=value[i];else m_dataArray[0]=value},this.callGL=function(location){if(!(this.m_numberElements<1))switch(m_type){case gl.BOOL:case gl.INT:gl.uniform1iv(location,m_dataArray);break;case gl.FLOAT:gl.uniform1fv(location,m_dataArray);break;case gl.FLOAT_VEC2:gl.uniform2fv(location,m_dataArray);break;case gl.FLOAT_VEC3:gl.uniform3fv(location,m_dataArray);break;case gl.FLOAT_VEC4:gl.uniform4fv(location,m_dataArray);break;case gl.FLOAT_MAT3:gl.uniformMatrix3fv(location,gl.FALSE,m_dataArray);break;case gl.FLOAT_MAT4:gl.uniformMatrix4fv(location,gl.FALSE,m_dataArray)}},this.update=function(){},this},vgl.modelViewUniform=function(name){"use strict";return this instanceof vgl.modelViewUniform?(0===name.length&&(name="modelViewMatrix"),vgl.uniform.call(this,gl.FLOAT_MAT4,name),this.set(mat4.create()),this.update=function(renderState){this.set(renderState.m_modelViewMatrix)},this):new vgl.modelViewUniform(name)},inherit(vgl.modelViewUniform,vgl.uniform),vgl.projectionUniform=function(name){"use strict";return this instanceof vgl.projectionUniform?(0===name.length&&(name="projectionMatrix"),vgl.uniform.call(this,gl.FLOAT_MAT4,name),this.set(mat4.create()),this.update=function(renderState){this.set(renderState.m_projectionMatrix)},this):new vgl.projectionUniform(name)},inherit(vgl.projectionUniform,vgl.uniform),vgl.floatUniform=function(name,value){"use strict";return this instanceof vgl.floatUniform?(0===name.length&&(name="floatUniform"),value=void 0===value?1:value,vgl.uniform.call(this,gl.FLOAT,name),void this.set(value)):new vgl.floatUniform(name,value)},inherit(vgl.floatUniform,vgl.uniform),vgl.normalMatrixUniform=function(name){"use strict";return this instanceof vgl.normalMatrixUniform?(0===name.length&&(name="normalMatrix"),vgl.uniform.call(this,gl.FLOAT_MAT4,name),this.set(mat4.create()),this.update=function(renderState){this.set(renderState.m_normalMatrix)},this):new vgl.normalMatrixUniform(name)},inherit(vgl.normalMatrixUniform,vgl.uniform),vgl.vertexAttributeKeys={Position:0,Normal:1,TextureCoordinate:2,Color:3,CountAttributeIndex:4},vgl.vertexAttributeKeysIndexed={Zero:0,One:1,Two:2,Three:3,Four:4,Five:5,Six:6,Seven:7,Eight:8,Nine:9},vgl.vertexAttribute=function(name){"use strict";if(!(this instanceof vgl.vertexAttribute))return new vgl.vertexAttribute(name);var m_name=name;this.name=function(){return m_name},this.bindVertexData=function(renderState,key){var geometryData=renderState.m_mapper.geometryData(),sourceData=geometryData.sourceData(key),program=renderState.m_material.shaderProgram();gl.vertexAttribPointer(program.attributeLocation(m_name),sourceData.attributeNumberOfComponents(key),sourceData.attributeDataType(key),sourceData.normalized(key),sourceData.attributeStride(key),sourceData.attributeOffset(key)),gl.enableVertexAttribArray(program.attributeLocation(m_name))},this.undoBindVertexData=function(renderState){var program=renderState.m_material.shaderProgram();gl.disableVertexAttribArray(program.attributeLocation(m_name))}},vgl.source=function(){"use strict";return this instanceof vgl.source?(vgl.object.call(this),this.create=function(){},this):new vgl.source},inherit(vgl.source,vgl.object),vgl.planeSource=function(){"use strict";if(!(this instanceof vgl.planeSource))return new vgl.planeSource;vgl.source.call(this);var m_origin=[0,0,0],m_point1=[1,0,0],m_point2=[0,1,0],m_normal=[0,0,1],m_xresolution=1,m_yresolution=1,m_geom=null;this.setOrigin=function(x,y,z){m_origin[0]=x,m_origin[1]=y,m_origin[2]=z},this.setPoint1=function(x,y,z){m_point1[0]=x,m_point1[1]=y,m_point1[2]=z},this.setPoint2=function(x,y,z){m_point2[0]=x,m_point2[1]=y,m_point2[2]=z},this.create=function(){m_geom=new vgl.geometryData;var i,j,k,ii,numPts,numPolys,sourceTexCoords,x=[],tc=[],v1=[],v2=[],pts=[],posIndex=0,normIndex=0,colorIndex=0,texCoordIndex=0,positions=[],normals=[],colors=[],texCoords=[],indices=[],tristrip=null,sourcePositions=null,sourceColors=null;for(x.length=3,tc.length=2,v1.length=3,v2.length=3,pts.length=3,i=0;3>i;i++)v1[i]=m_point1[i]-m_origin[i],v2[i]=m_point2[i]-m_origin[i];for(numPts=(m_xresolution+1)*(m_yresolution+1),numPolys=m_xresolution*m_yresolution*2,positions.length=3*numPts,normals.length=3*numPts,texCoords.length=2*numPts,indices.length=numPts,k=0,i=0;m_yresolution+1>i;i++)for(tc[1]=i/m_yresolution,j=0;m_xresolution+1>j;j++){for(tc[0]=j/m_xresolution,ii=0;3>ii;ii++)x[ii]=m_origin[ii]+tc[0]*v1[ii]+tc[1]*v2[ii];positions[posIndex++]=x[0],positions[posIndex++]=x[1],positions[posIndex++]=x[2],colors[colorIndex++]=1,colors[colorIndex++]=1,colors[colorIndex++]=1,normals[normIndex++]=m_normal[0],normals[normIndex++]=m_normal[1],normals[normIndex++]=m_normal[2],texCoords[texCoordIndex++]=tc[0],texCoords[texCoordIndex++]=tc[1]}for(i=0;m_yresolution>i;i++)for(j=0;m_xresolution>j;j++)pts[0]=j+i*(m_xresolution+1),pts[1]=pts[0]+1,pts[2]=pts[0]+m_xresolution+2,pts[3]=pts[0]+m_xresolution+1;for(i=0;numPts>i;++i)indices[i]=i;return tristrip=new vgl.triangleStrip,tristrip.setIndices(indices),sourcePositions=vgl.sourceDataP3fv(),sourcePositions.pushBack(positions),sourceColors=vgl.sourceDataC3fv(),sourceColors.pushBack(colors),sourceTexCoords=vgl.sourceDataT2fv(),sourceTexCoords.pushBack(texCoords),m_geom.addSource(sourcePositions),m_geom.addSource(sourceColors),m_geom.addSource(sourceTexCoords),m_geom.addPrimitive(tristrip),m_geom}},inherit(vgl.planeSource,vgl.source),vgl.pointSource=function(){"use strict";if(!(this instanceof vgl.pointSource))return new vgl.pointSource;vgl.source.call(this);var m_this=this,m_positions=[],m_colors=[],m_textureCoords=[],m_size=[],m_geom=null;this.getPositions=function(){return m_positions},this.setPositions=function(positions){positions instanceof Array?m_positions=positions:console.log("[ERROR] Invalid data type for positions. Array is required."),m_this.modified()},this.getColors=function(){return m_colors},this.setColors=function(colors){colors instanceof Array?m_colors=colors:console.log("[ERROR] Invalid data type for colors. Array is required."),m_this.modified()},this.getSize=function(){return m_size},this.setSize=function(size){m_size=size,this.modified()},this.setTextureCoordinates=function(texcoords){texcoords instanceof Array?m_textureCoords=texcoords:console.log("[ERROR] Invalid data type for texture coordinates. Array is required."),m_this.modified()},this.create=function(){if(m_geom=new vgl.geometryData,m_positions.length%3!==0)return void console.log("[ERROR] Invalid length of the points array");var pointsPrimitive,sourcePositions,sourceColors,sourceTexCoords,sourceSize,numPts=m_positions.length/3,i=0,indices=[];for(indices.length=numPts,i=0;numPts>i;++i)indices[i]=i;if(sourceSize=vgl.sourceDataDf(),numPts!==m_size.length)for(i=0;numPts>i;++i)sourceSize.pushBack(m_size);else sourceSize.setData(m_size);return m_geom.addSource(sourceSize),pointsPrimitive=new vgl.points,pointsPrimitive.setIndices(indices),sourcePositions=vgl.sourceDataP3fv(),sourcePositions.pushBack(m_positions),m_geom.addSource(sourcePositions),m_colors.length>0&&m_colors.length===m_positions.length?(sourceColors=vgl.sourceDataC3fv(),sourceColors.pushBack(m_colors),m_geom.addSource(sourceColors)):m_colors.length>0&&m_colors.length!==m_positions.length&&console.log("[ERROR] Number of colors are different than number of points"),m_textureCoords.length>0&&m_textureCoords.length===m_positions.length?(sourceTexCoords=vgl.sourceDataT2fv(),sourceTexCoords.pushBack(m_textureCoords),m_geom.addSource(sourceTexCoords)):m_textureCoords.length>0&&m_textureCoords.length/2!==m_positions.length/3&&console.log("[ERROR] Number of texture coordinates are different than number of points"),m_geom.addPrimitive(pointsPrimitive),m_geom}},inherit(vgl.pointSource,vgl.source),vgl.lineSource=function(positions,colors){"use strict";if(!(this instanceof vgl.lineSource))return new vgl.lineSource;vgl.source.call(this);var m_positions=positions,m_colors=colors;this.setPositions=function(positions){return positions instanceof Array?(m_positions=positions,this.modified(),!0):(console.log("[ERROR] Invalid data type for positions. Array is required."),!1)},this.setColors=function(colors){return colors instanceof Array?(m_colors=colors,this.modified(),!0):(console.log("[ERROR] Invalid data type for colors. Array is required."),!1)},this.create=function(){if(!m_positions)return void console.log("[error] Invalid positions");if(m_positions.length%3!==0)return void console.log("[error] Line source requires 3d points");if(m_positions.length%3!==0)return void console.log("[ERROR] Invalid length of the points array");var i,linesPrimitive,sourcePositions,sourceColors,m_geom=new vgl.geometryData,numPts=m_positions.length/3,indices=[];for(indices.length=numPts,i=0;numPts>i;++i)indices[i]=i;return linesPrimitive=new vgl.lines,linesPrimitive.setIndices(indices),sourcePositions=vgl.sourceDataP3fv(),sourcePositions.pushBack(m_positions),m_geom.addSource(sourcePositions),m_colors&&m_colors.length>0&&m_colors.length===m_positions.length?(sourceColors=vgl.sourceDataC3fv(),sourceColors.pushBack(m_colors),m_geom.addSource(sourceColors)):m_colors&&m_colors.length>0&&m_colors.length!==m_positions.length&&console.log("[error] Number of colors are different than number of points"),m_geom.addPrimitive(linesPrimitive),m_geom}},inherit(vgl.lineSource,vgl.source),vgl.utils=function(){"use strict";return this instanceof vgl.utils?(vgl.object.call(this),this):new vgl.utils},inherit(vgl.utils,vgl.object),vgl.utils.computePowerOfTwo=function(value,pow){"use strict";for(pow=pow||1;value>pow;)pow*=2;return pow},vgl.utils.createTextureVertexShader=function(){"use strict";var vertexShaderSource=["attribute vec3 vertexPosition;","attribute vec3 textureCoord;","uniform mediump float pointSize;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","varying highp vec3 iTextureCoord;","void main(void)","{","gl_PointSize = pointSize;","gl_Position = projectionMatrix * modelViewMatrix * vec4(vertexPosition, 1.0);"," iTextureCoord = textureCoord;","}"].join("\n"),shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader},vgl.utils.createTextureFragmentShader=function(){"use strict";var fragmentShaderSource=["varying highp vec3 iTextureCoord;","uniform sampler2D sampler2d;","uniform mediump float opacity;","void main(void) {","gl_FragColor = vec4(texture2D(sampler2d, vec2(iTextureCoord.s, iTextureCoord.t)).xyz, opacity);","}"].join("\n"),shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader},vgl.utils.createRgbaTextureFragmentShader=function(){"use strict";var fragmentShaderSource=["varying highp vec3 iTextureCoord;","uniform sampler2D sampler2d;","uniform mediump float opacity;","void main(void) {"," mediump vec4 color = vec4(texture2D(sampler2d, vec2(iTextureCoord.s, iTextureCoord.t)).xyzw);"," color.w *= opacity;"," gl_FragColor = color;","}"].join("\n"),shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader},vgl.utils.createVertexShader=function(){"use strict";var vertexShaderSource=["attribute vec3 vertexPosition;","attribute vec3 vertexColor;","uniform mediump float pointSize;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","varying mediump vec3 iVertexColor;","varying highp vec3 iTextureCoord;","void main(void)","{","gl_PointSize = pointSize;","gl_Position = projectionMatrix * modelViewMatrix * vec4(vertexPosition, 1.0);"," iVertexColor = vertexColor;","}"].join("\n"),shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader},vgl.utils.createPointVertexShader=function(){"use strict";var vertexShaderSource=["attribute vec3 vertexPosition;","attribute vec3 vertexColor;","attribute float vertexSize;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","varying mediump vec3 iVertexColor;","varying highp vec3 iTextureCoord;","void main(void)","{","gl_PointSize = vertexSize;","gl_Position = projectionMatrix * modelViewMatrix * vec4(vertexPosition, 1.0);"," iVertexColor = vertexColor;","}"].join("\n"),shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader},vgl.utils.createVertexShaderSolidColor=function(){"use strict";var vertexShaderSource=["attribute vec3 vertexPosition;","uniform mediump float pointSize;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","void main(void)","{","gl_PointSize = pointSize;","gl_Position = projectionMatrix * modelViewMatrix * vec4(vertexPosition, 1.0);","}"].join("\n"),shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader},vgl.utils.createVertexShaderColorMap=function(){"use strict";var vertexShaderSource=["attribute vec3 vertexPosition;","attribute float vertexScalar;","uniform mediump float pointSize;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float lutMin;","uniform float lutMax;","varying mediump float iVertexScalar;","void main(void)","{","gl_PointSize = pointSize;","gl_Position = projectionMatrix * modelViewMatrix * vec4(vertexPosition, 1.0);","iVertexScalar = (vertexScalar-lutMin)/(lutMax-lutMin);","}"].join("\n"),shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader},vgl.utils.createFragmentShader=function(){"use strict";var fragmentShaderSource=["varying mediump vec3 iVertexColor;","uniform mediump float opacity;","void main(void) {","gl_FragColor = vec4(iVertexColor, opacity);","}"].join("\n"),shader=new vgl.shader(gl.FRAGMENT_SHADER);
-
-return shader.setShaderSource(fragmentShaderSource),shader},vgl.utils.createPhongVertexShader=function(){"use strict";var vertexShaderSource=["attribute highp vec3 vertexPosition;","attribute mediump vec3 vertexNormal;","attribute mediump vec3 vertexColor;","uniform highp mat4 projectionMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 normalMatrix;","varying highp vec4 varPosition;","varying mediump vec3 varNormal;","varying mediump vec3 iVertexColor;","void main(void)","{","varPosition = modelViewMatrix * vec4(vertexPosition, 1.0);","gl_Position = projectionMatrix * varPosition;","varNormal = vec3(normalMatrix * vec4(vertexNormal, 0.0));","iVertexColor = vertexColor;","}"].join("\n"),shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader},vgl.utils.createPhongFragmentShader=function(){"use strict";var fragmentShaderSource=["precision mediump float;","varying vec3 varNormal;","varying vec4 varPosition;","varying mediump vec3 iVertexColor;","const vec3 lightPos = vec3(0.0, 0.0,10000.0);","const vec3 ambientColor = vec3(0.01, 0.01, 0.01);","const vec3 specColor = vec3(1.0, 1.0, 1.0);","void main() {","vec3 normal = normalize(varNormal);","vec3 lightDir = normalize(lightPos);","vec3 reflectDir = -reflect(lightDir, normal);","vec3 viewDir = normalize(-varPosition.xyz);","float lambertian = max(dot(lightDir,normal), 0.0);","float specular = 0.0;","if(lambertian > 0.0) {","float specAngle = max(dot(reflectDir, viewDir), 0.0);","specular = pow(specAngle, 64.0);","}","gl_FragColor = vec4(ambientColor +","lambertian*iVertexColor +","specular*specColor, 1.0);","}"].join("\n"),shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader},vgl.utils.createFragmentShaderSolidColor=function(context,color){"use strict";var fragmentShaderSource=["uniform mediump float opacity;","void main(void) {","gl_FragColor = vec4("+color[0]+","+color[1]+","+color[2]+", opacity);","}"].join("\n"),shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader},vgl.utils.createFragmentShaderColorMap=function(){"use strict";var fragmentShaderSource=["varying mediump float iVertexScalar;","uniform sampler2D sampler2d;","uniform mediump float opacity;","void main(void) {","gl_FragColor = vec4(texture2D(sampler2d, vec2(iVertexScalar, 0.0)).xyz, opacity);","}"].join("\n"),shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader},vgl.utils.createPointSpritesVertexShader=function(){"use strict";var vertexShaderSource=["attribute vec3 vertexPosition;","attribute vec3 vertexColor;","uniform mediump vec2 pointSize;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float height;","varying mediump vec3 iVertexColor;","varying highp float iVertexScalar;","void main(void)","{","mediump float realPointSize = pointSize.y;","if (pointSize.x > pointSize.y) {"," realPointSize = pointSize.x;}","gl_PointSize = realPointSize ;","iVertexScalar = vertexPosition.z;","gl_Position = projectionMatrix * modelViewMatrix * vec4(vertexPosition.xy, height, 1.0);"," iVertexColor = vertexColor;","}"].join("\n"),shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader},vgl.utils.createPointSpritesFragmentShader=function(){"use strict";var fragmentShaderSource=["varying mediump vec3 iVertexColor;","varying highp float iVertexScalar;","uniform sampler2D opacityLookup;","uniform highp float lutMin;","uniform highp float lutMax;","uniform sampler2D scalarsToColors;","uniform int useScalarsToColors;","uniform int useVertexColors;","uniform mediump vec2 pointSize;","uniform mediump float vertexColorWeight;","void main(void) {","mediump vec2 realTexCoord;","if (pointSize.x > pointSize.y) {"," realTexCoord = vec2(1.0, pointSize.y/pointSize.x) * gl_PointCoord;","} else {"," realTexCoord = vec2(pointSize.x/pointSize.y, 1.0) * gl_PointCoord;","}","highp float texOpacity = texture2D(opacityLookup, realTexCoord).w;","if (useScalarsToColors == 1) {"," gl_FragColor = vec4(texture2D(scalarsToColors, vec2((iVertexScalar - lutMin)/(lutMax - lutMin), 0.0)).xyz, texOpacity);","} else if (useVertexColors == 1) {"," gl_FragColor = vec4(iVertexColor, texOpacity);","} else {"," gl_FragColor = vec4(texture2D(opacityLookup, realTexCoord).xyz, texOpacity);","}}"].join("\n"),shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader},vgl.utils.createTextureMaterial=function(isRgba){"use strict";var mat=new vgl.material,blend=new vgl.blend,prog=new vgl.shaderProgram,vertexShader=vgl.utils.createTextureVertexShader(gl),fragmentShader=null,posVertAttr=new vgl.vertexAttribute("vertexPosition"),texCoordVertAttr=new vgl.vertexAttribute("textureCoord"),pointsizeUniform=new vgl.floatUniform("pointSize",5),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix"),samplerUniform=new vgl.uniform(gl.INT,"sampler2d"),opacityUniform=null;return samplerUniform.set(0),prog.addVertexAttribute(posVertAttr,vgl.vertexAttributeKeys.Position),prog.addVertexAttribute(texCoordVertAttr,vgl.vertexAttributeKeys.TextureCoordinate),prog.addUniform(pointsizeUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),fragmentShader=isRgba?vgl.utils.createRgbaTextureFragmentShader(gl):vgl.utils.createTextureFragmentShader(gl),opacityUniform=new vgl.floatUniform("opacity",1),prog.addUniform(opacityUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),mat},vgl.utils.createGeometryMaterial=function(){"use strict";var mat=new vgl.material,blend=new vgl.blend,prog=new vgl.shaderProgram,pointSize=5,opacity=.5,vertexShader=vgl.utils.createVertexShader(gl),fragmentShader=vgl.utils.createFragmentShader(gl),posVertAttr=new vgl.vertexAttribute("vertexPosition"),colorVertAttr=new vgl.vertexAttribute("vertexColor"),pointsizeUniform=new vgl.floatUniform("pointSize",pointSize),opacityUniform=new vgl.floatUniform("opacity",opacity),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix");return prog.addVertexAttribute(posVertAttr,vgl.vertexAttributeKeys.Position),prog.addVertexAttribute(colorVertAttr,vgl.vertexAttributeKeys.Color),prog.addUniform(pointsizeUniform),prog.addUniform(opacityUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),mat},vgl.utils.createPointGeometryMaterial=function(opacity){"use strict";var mat=new vgl.material,blend=new vgl.blend,prog=new vgl.shaderProgram,opacity=void 0===opacity?1:opacity,vertexShader=vgl.utils.createPointVertexShader(gl),fragmentShader=vgl.utils.createFragmentShader(gl),posVertAttr=new vgl.vertexAttribute("vertexPosition"),colorVertAttr=new vgl.vertexAttribute("vertexColor"),sizeVertAttr=new vgl.vertexAttribute("vertexSize"),opacityUniform=new vgl.floatUniform("opacity",opacity),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix");return prog.addVertexAttribute(posVertAttr,vgl.vertexAttributeKeys.Position),prog.addVertexAttribute(colorVertAttr,vgl.vertexAttributeKeys.Color),prog.addVertexAttribute(sizeVertAttr,vgl.vertexAttributeKeys.Scalar),prog.addUniform(opacityUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),mat},vgl.utils.createPhongMaterial=function(){"use strict";var mat=new vgl.material,blend=new vgl.blend,prog=new vgl.shaderProgram,vertexShader=vgl.utils.createPhongVertexShader(gl),fragmentShader=vgl.utils.createPhongFragmentShader(gl),posVertAttr=new vgl.vertexAttribute("vertexPosition"),normalVertAttr=new vgl.vertexAttribute("vertexNormal"),colorVertAttr=new vgl.vertexAttribute("vertexColor"),opacityUniform=new vgl.floatUniform("opacity",1),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),normalUniform=new vgl.normalMatrixUniform("normalMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix");return prog.addVertexAttribute(posVertAttr,vgl.vertexAttributeKeys.Position),prog.addVertexAttribute(normalVertAttr,vgl.vertexAttributeKeys.Normal),prog.addVertexAttribute(colorVertAttr,vgl.vertexAttributeKeys.Color),prog.addUniform(opacityUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addUniform(normalUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),mat},vgl.utils.createColorMaterial=function(){"use strict";var mat=new vgl.material,blend=new vgl.blend,prog=new vgl.shaderProgram,vertexShader=vgl.utils.createVertexShader(gl),fragmentShader=vgl.utils.createFragmentShader(gl),posVertAttr=new vgl.vertexAttribute("vertexPosition"),texCoordVertAttr=new vgl.vertexAttribute("textureCoord"),colorVertAttr=new vgl.vertexAttribute("vertexColor"),pointsizeUniform=new vgl.floatUniform("pointSize",5),opacityUniform=new vgl.floatUniform("opacity",.5),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix");return prog.addVertexAttribute(posVertAttr,vgl.vertexAttributeKeys.Position),prog.addVertexAttribute(colorVertAttr,vgl.vertexAttributeKeys.Color),prog.addVertexAttribute(texCoordVertAttr,vgl.vertexAttributeKeys.TextureCoordinate),prog.addUniform(pointsizeUniform),prog.addUniform(opacityUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),mat},vgl.utils.createColorMappedMaterial=function(lut){"use strict";lut||(lut=new vgl.lookupTable);var scalarRange=lut.range(),mat=new vgl.material,blend=new vgl.blend,prog=new vgl.shaderProgram,vertexShader=vgl.utils.createVertexShaderColorMap(gl,scalarRange[0],scalarRange[1]),fragmentShader=vgl.utils.createFragmentShaderColorMap(gl),posVertAttr=new vgl.vertexAttribute("vertexPosition"),scalarVertAttr=new vgl.vertexAttribute("vertexScalar"),pointsizeUniform=new vgl.floatUniform("pointSize",5),opacityUniform=new vgl.floatUniform("opacity",.5),lutMinUniform=new vgl.floatUniform("lutMin",scalarRange[0]),lutMaxUniform=new vgl.floatUniform("lutMax",scalarRange[1]),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix"),samplerUniform=new vgl.uniform(gl.FLOAT,"sampler2d"),lookupTable=lut;return samplerUniform.set(0),prog.addVertexAttribute(posVertAttr,vgl.vertexAttributeKeys.Position),prog.addVertexAttribute(scalarVertAttr,vgl.vertexAttributeKeys.Scalar),prog.addUniform(pointsizeUniform),prog.addUniform(opacityUniform),prog.addUniform(lutMinUniform),prog.addUniform(lutMaxUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),mat.addAttribute(lookupTable),mat},vgl.utils.updateColorMappedMaterial=function(mat,lut){"use strict";if(!mat)return void console.log("[warning] Invalid material. Nothing to update.");if(!lut)return void console.log("[warning] Invalid lookup table. Nothing to update.");var lutMin=mat.shaderProgram().uniform("lutMin"),lutMax=mat.shaderProgram().uniform("lutMax");lutMin.set(lut.range()[0]),lutMax.set(lut.range()[1]),mat.setAttribute(lut)},vgl.utils.createSolidColorMaterial=function(color){"use strict";color||(color=[1,1,1]);var mat=new vgl.material,blend=new vgl.blend,prog=new vgl.shaderProgram,vertexShader=vgl.utils.createVertexShaderSolidColor(gl),fragmentShader=vgl.utils.createFragmentShaderSolidColor(gl,color),posVertAttr=new vgl.vertexAttribute("vertexPosition"),pointsizeUniform=new vgl.floatUniform("pointSize",5),opacityUniform=new vgl.floatUniform("opacity",1),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix");return prog.addVertexAttribute(posVertAttr,vgl.vertexAttributeKeys.Position),prog.addUniform(pointsizeUniform),prog.addUniform(opacityUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),mat},vgl.utils.createPointSpritesMaterial=function(image,lut){"use strict";var scalarRange=void 0===lut?[0,1]:lut.range(),mat=new vgl.material,blend=new vgl.blend,prog=new vgl.shaderProgram,vertexShader=vgl.utils.createPointSpritesVertexShader(gl),fragmentShader=vgl.utils.createPointSpritesFragmentShader(gl),posVertAttr=new vgl.vertexAttribute("vertexPosition"),colorVertAttr=new vgl.vertexAttribute("vertexColor"),heightUniform=new vgl.floatUniform("height",0),vertexColorWeightUniform=new vgl.floatUniform("vertexColorWeight",0),lutMinUniform=new vgl.floatUniform("lutMin",scalarRange[0]),lutMaxUniform=new vgl.floatUniform("lutMax",scalarRange[1]),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix"),samplerUniform=new vgl.uniform(gl.INT,"opacityLookup"),scalarsToColors=new vgl.uniform(gl.INT,"scalarsToColors"),useScalarsToColors=new vgl.uniform(gl.INT,"useScalarsToColors"),useVertexColors=new vgl.uniform(gl.INT,"useVertexColors"),pointSize=new vgl.uniform(gl.FLOAT_VEC2,"pointSize"),texture=new vgl.texture;return samplerUniform.set(0),scalarsToColors.set(1),useScalarsToColors.set(0),useVertexColors.set(0),pointSize.set([1,1]),prog.addVertexAttribute(posVertAttr,vgl.vertexAttributeKeys.Position),prog.addVertexAttribute(colorVertAttr,vgl.vertexAttributeKeys.Color),prog.addUniform(heightUniform),prog.addUniform(vertexColorWeightUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addUniform(samplerUniform),prog.addUniform(useVertexColors),prog.addUniform(useScalarsToColors),prog.addUniform(pointSize),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),lut&&(prog.addUniform(scalarsToColors),useScalarsToColors.set(1),prog.addUniform(lutMinUniform),prog.addUniform(lutMaxUniform),lut.setTextureUnit(1),mat.addAttribute(lut)),texture.setImage(image),texture.setTextureUnit(0),mat.addAttribute(texture),mat},vgl.utils.createPlane=function(originX,originY,originZ,point1X,point1Y,point1Z,point2X,point2Y,point2Z){"use strict";var mapper=new vgl.mapper,planeSource=new vgl.planeSource,mat=vgl.utils.createGeometryMaterial(),actor=new vgl.actor;return planeSource.setOrigin(originX,originY,originZ),planeSource.setPoint1(point1X,point1Y,point1Z),planeSource.setPoint2(point2X,point2Y,point2Z),mapper.setGeometryData(planeSource.create()),actor.setMapper(mapper),actor.setMaterial(mat),actor},vgl.utils.createTexturePlane=function(originX,originY,originZ,point1X,point1Y,point1Z,point2X,point2Y,point2Z,isRgba){"use strict";var mapper=new vgl.mapper,planeSource=new vgl.planeSource,mat=vgl.utils.createTextureMaterial(isRgba),actor=new vgl.actor;return planeSource.setOrigin(originX,originY,originZ),planeSource.setPoint1(point1X,point1Y,point1Z),planeSource.setPoint2(point2X,point2Y,point2Z),mapper.setGeometryData(planeSource.create()),actor.setMapper(mapper),actor.setMaterial(mat),actor},vgl.utils.createPoints=function(positions,size,colors,texcoords,opacity){"use strict";if(!positions)return console.log("[ERROR] Cannot create points without positions"),null;var opacity=void 0===opacity?1:opacity,mapper=new vgl.mapper,pointSource=new vgl.pointSource,mat=vgl.utils.createPointGeometryMaterial(opacity),actor=new vgl.actor;return pointSource.setPositions(positions),colors&&pointSource.setColors(colors),texcoords&&pointSource.setTextureCoordinates(texcoords),pointSource.setSize(size?size:1),mapper.setGeometryData(pointSource.create()),actor.setMapper(mapper),actor.setMaterial(mat),actor},vgl.utils.createPointSprites=function(image,positions,colors,texcoords){"use strict";if(!image)return console.log("[ERROR] Point sprites requires an image"),null;if(!positions)return console.log("[ERROR] Cannot create points without positions"),null;var mapper=new vgl.mapper,pointSource=new vgl.pointSource,mat=vgl.utils.createPointSpritesMaterial(image),actor=new vgl.actor;return pointSource.setPositions(positions),colors&&pointSource.setColors(colors),texcoords&&pointSource.setTextureCoordinates(texcoords),mapper.setGeometryData(pointSource.create()),actor.setMapper(mapper),actor.setMaterial(mat),actor},vgl.utils.createLines=function(positions,colors){"use strict";if(!positions)return console.log("[ERROR] Cannot create points without positions"),null;var mapper=new vgl.mapper,lineSource=new vgl.lineSource,mat=vgl.utils.createGeometryMaterial(),actor=new vgl.actor;return lineSource.setPositions(positions),colors&&lineSource.setColors(colors),mapper.setGeometryData(lineSource.create()),actor.setMapper(mapper),actor.setMaterial(mat),actor},vgl.utils.createColorLegend=function(varname,lookupTable,origin,width,height,countMajor,countMinor){"use strict";function createLabels(varname,positions,range){if(!positions)return void console.log("[error] Create labels requires positions (x,y,z) array");if(positions.length%3!==0)return void console.log("[error] Create labels require positions array contain 3d points");if(!range)return void console.log("[error] Create labels requires Valid range");var i,actor=null,size=vgl.utils.computePowerOfTwo(48),index=0,actors=[],origin=[],pt1=[],pt2=[],delta=positions[6]-positions[0],axisLabelOffset=4;for(origin.length=3,pt1.length=3,pt2.length=3,i=0;2>i;++i)index=i*(positions.length-3),origin[0]=positions[index]-delta,origin[1]=positions[index+1]-2*delta,origin[2]=positions[index+2],pt1[0]=positions[index]+delta,pt1[1]=origin[1],pt1[2]=origin[2],pt2[0]=origin[0],pt2[1]=positions[1],pt2[2]=origin[2],actor=vgl.utils.createTexturePlane(origin[0],origin[1],origin[2],pt1[0],pt1[1],pt1[2],pt2[0],pt2[1],pt2[2],!0),actor.setReferenceFrame(vgl.boundingObject.ReferenceFrame.Absolute),actor.material().setBinNumber(vgl.material.RenderBin.Overlay),actor.material().addAttribute(vgl.utils.create2DTexture(range[i].toFixed(2).toString(),12,null)),actors.push(actor);return origin[0]=.5*(positions[0]+positions[positions.length-3]-size),origin[1]=positions[1]+axisLabelOffset,origin[2]=positions[2],pt1[0]=origin[0]+size,pt1[1]=origin[1],pt1[2]=origin[2],pt2[0]=origin[0],pt2[1]=origin[1]+size,pt2[2]=origin[2],actor=vgl.utils.createTexturePlane(origin[0],origin[1],origin[2],pt1[0],pt1[1],pt1[2],pt2[0],pt2[1],pt2[2],!0),actor.setReferenceFrame(vgl.boundingObject.ReferenceFrame.Absolute),actor.material().setBinNumber(vgl.material.RenderBin.Overlay),actor.material().addAttribute(vgl.utils.create2DTexture(varname,24,null)),actors.push(actor),actors}function createTicksAndLabels(varname,lut,originX,originY,originZ,pt1X,pt1Y,pt1Z,pt2X,pt2Y,pt2Z,countMajor,countMinor,heightMajor){var width=pt2X-pt1X,index=null,delta=width/countMajor,positions=[],actors=[];for(index=0;countMajor>=index;++index)positions.push(pt1X+delta*index),positions.push(pt1Y),positions.push(pt1Z),positions.push(pt1X+delta*index),positions.push(pt1Y+heightMajor),positions.push(pt1Z);return actors=actors.concat(createLabels(varname,positions,lut.range()))}if(!lookupTable)return console.log("[error] Invalid lookup table"),[];var pt1X=origin[0]+width,pt1Y=origin[1],pt1Z=0,pt2X=origin[0],pt2Y=origin[1]+height,pt2Z=0,actors=[],actor=null,mat=null,group=vgl.groupNode();return actor=vgl.utils.createTexturePlane(origin[0],origin[1],origin[2],pt1X,pt1Y,pt1Z,pt2X,pt2Y,pt2Z,!0),mat=actor.material(),mat.addAttribute(lookupTable),actor.setMaterial(mat),group.addChild(actor),actor.material().setBinNumber(vgl.material.RenderBin.Overlay),actor.setReferenceFrame(vgl.boundingObject.ReferenceFrame.Absolute),actors.push(actor),actors=actors.concat(createTicksAndLabels(varname,lookupTable,origin[0],origin[1],origin[1],pt2X,pt1Y,pt1Z,pt1X,pt1Y,pt1Z,countMajor,countMinor,5,3))},vgl.utils.create2DTexture=function(textToWrite,textSize,color,font,alignment,baseline,bold){"use strict";var canvas=document.getElementById("textRendering"),ctx=null,texture=vgl.texture();return font=font||"sans-serif",alignment=alignment||"center",baseline=baseline||"bottom","undefined"==typeof bold&&(bold=!0),canvas||(canvas=document.createElement("canvas")),ctx=canvas.getContext("2d"),canvas.setAttribute("id","textRendering"),canvas.style.display="none",canvas.height=vgl.utils.computePowerOfTwo(8*textSize),canvas.width=canvas.height,ctx.fillStyle="rgba(0, 0, 0, 0)",ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height),ctx.fillStyle="rgba(200, 85, 10, 1.0)",ctx.textAlign=alignment,ctx.textBaseline=baseline,ctx.font=4*textSize+"px "+font,bold&&(ctx.font="bold "+ctx.font),ctx.fillText(textToWrite,canvas.width/2,canvas.height/2,canvas.width),texture.setImage(canvas),texture.updateDimensions(),texture},vgl.picker=function(){"use strict";if(!(this instanceof vgl.picker))return new vgl.picker;vgl.object.call(this);var m_actors=[];return this.getActors=function(){return m_actors},this.pick=function(selectionX,selectionY,renderer){if("undefined"==typeof selectionX)return 0;if("undefined"==typeof selectionY)return 0;if("undefined"==typeof renderer)return 0;m_actors=[];var actors,count,i,bb,tmin,tmax,tymin,tymax,tzmin,tzmax,actor,camera=renderer.camera(),width=renderer.width(),height=renderer.height(),fpoint=camera.focalPoint(),focusWorldPt=vec4.fromValues(fpoint[0],fpoint[1],fpoint[2],1),focusDisplayPt=renderer.worldToDisplay(focusWorldPt,camera.viewMatrix(),camera.projectionMatrix(),width,height),displayPt=vec4.fromValues(selectionX,selectionY,focusDisplayPt[2],1),worldPt=renderer.displayToWorld(displayPt,camera.viewMatrix(),camera.projectionMatrix(),width,height),cameraPos=camera.position(),ray=[];for(i=0;3>i;++i)ray[i]=worldPt[i]-cameraPos[i];for(actors=renderer.sceneRoot().children(),count=0,i=0;i=0?(tmin=(bb[0]-cameraPos[0])/ray[0],tmax=(bb[1]-cameraPos[0])/ray[0]):(tmin=(bb[1]-cameraPos[0])/ray[0],tmax=(bb[0]-cameraPos[0])/ray[0]),ray[1]>=0?(tymin=(bb[2]-cameraPos[1])/ray[1],tymax=(bb[3]-cameraPos[1])/ray[1]):(tymin=(bb[3]-cameraPos[1])/ray[1],tymax=(bb[2]-cameraPos[1])/ray[1]),tmin>tymax||tymin>tmax)continue;if(tymin>tmin&&(tmin=tymin),tmax>tymax&&(tmax=tymax),ray[2]>=0?(tzmin=(bb[4]-cameraPos[2])/ray[2],tzmax=(bb[5]-cameraPos[2])/ray[2]):(tzmin=(bb[5]-cameraPos[2])/ray[2],tzmax=(bb[4]-cameraPos[2])/ray[2]),tmin>tzmax||tzmin>tmax)continue;tzmin>tmin&&(tmin=tzmin),tmax>tzmax&&(tmax=tzmax),m_actors[count++]=actor}return count},this},inherit(vgl.picker,vgl.object),vgl.shapefileReader=function(){"use strict";if(!(this instanceof vgl.shapefileReader))return new vgl.shapefileReader;var m_that=this,SHP_NULL=0,SHP_POINT=1,SHP_POLYGON=5,SHP_POLYLINE=3;return this.int8=function(data,offset){return data.charCodeAt(offset)},this.bint32=function(data,offset){return((255&data.charCodeAt(offset))<<24)+((255&data.charCodeAt(offset+1))<<16)+((255&data.charCodeAt(offset+2))<<8)+(255&data.charCodeAt(offset+3))},this.lint32=function(data,offset){return((255&data.charCodeAt(offset+3))<<24)+((255&data.charCodeAt(offset+2))<<16)+((255&data.charCodeAt(offset+1))<<8)+(255&data.charCodeAt(offset))},this.bint16=function(data,offset){return((255&data.charCodeAt(offset))<<8)+(255&data.charCodeAt(offset+1))},this.lint16=function(data,offset){return((255&data.charCodeAt(offset+1))<<8)+(255&data.charCodeAt(offset))},this.ldbl64=function(data,offset){var b0=255&data.charCodeAt(offset),b1=255&data.charCodeAt(offset+1),b2=255&data.charCodeAt(offset+2),b3=255&data.charCodeAt(offset+3),b4=255&data.charCodeAt(offset+4),b5=255&data.charCodeAt(offset+5),b6=255&data.charCodeAt(offset+6),b7=255&data.charCodeAt(offset+7),sign=1-2*(b7>>7),exp=((127&b7)<<4)+((240&b6)>>4)-1023,frac=(15&b6)*Math.pow(2,48)+b5*Math.pow(2,40)+b4*Math.pow(2,32)+b3*Math.pow(2,24)+b2*Math.pow(2,16)+b1*Math.pow(2,8)+b0;return sign*(1+frac*Math.pow(2,-52))*Math.pow(2,exp)},this.lfloat32=function(data,offset){var b0=255&data.charCodeAt(offset),b1=255&data.charCodeAt(offset+1),b2=255&data.charCodeAt(offset+2),b3=255&data.charCodeAt(offset+3),sign=1-2*(b3>>7),exp=((127&b3)<<1)+((254&b2)>>7)-127,frac=(127&b2)*Math.pow(2,16)+b1*Math.pow(2,8)+b0;return sign*(1+frac*Math.pow(2,-23))*Math.pow(2,exp)},this.str=function(data,offset,length){for(var chars=[],index=offset;offset+length>index;){var c=data[index];if(0===c.charCodeAt(0))break;chars.push(c),index++}return chars.join("")},this.readHeader=function(data){var code=this.bint32(data,0),length=this.bint32(data,24),version=this.lint32(data,28),shapetype=this.lint32(data,32),xmin=this.ldbl64(data,36),ymin=this.ldbl64(data,44),xmax=this.ldbl64(data,52),ymax=this.ldbl64(data,60);return{code:code,length:length,version:version,shapetype:shapetype,bounds:new Box(vect(xmin,ymin),vect(xmax,ymax))}},this.loadShx=function(data){for(var indices=[],appendIndex=function(offset){return indices.push(2*m_that.bint32(data,offset)),offset+8},offset=100;offsetheader_offset;)headers.push(readHeader(header_offset)),header_offset+=HEADER_LENGTH;for(var records=[],record_offset=header_size;header_size+num_entries*record_size>record_offset;){var declare=m_that.str(data,record_offset,1);if("*"==declare)record_offset+=record_size;else{record_offset++;for(var record={},i=0;i=start;i--){var x=m_that.ldbl64(data,offset+16*i),y=m_that.ldbl64(data,offset+16*i+8);ring.push([x,y])}return ring},readRecord=function(offset){var record_offset=(m_that.bint32(data,offset),m_that.bint32(data,offset+4),offset+8),geom_type=m_that.lint32(data,record_offset);if(geom_type==SHP_NULL)console.log("NULL Shape");else if(geom_type==SHP_POINT){var x=m_that.ldbl64(data,record_offset+4),y=m_that.ldbl64(data,record_offset+12);features.push({type:"Point",attr:{},geom:[[x,y]]})}else if(geom_type==SHP_POLYGON){for(var num_parts=m_that.lint32(data,record_offset+36),num_points=m_that.lint32(data,record_offset+40),parts_start=offset+52,points_start=offset+52+4*num_parts,rings=[],i=0;num_parts>i;i++){var end,start=m_that.lint32(data,parts_start+4*i);end=num_parts>i+1?m_that.lint32(data,parts_start+4*(i+1)):num_points;var ring=readRing(points_start,start,end);rings.push(ring)}features.push({type:"Polygon",attr:{},geom:[rings]})}else{if(geom_type!=SHP_POLYLINE)throw"Not Implemented: "+geom_type;for(var num_parts=m_that.lint32(data,record_offset+36),num_points=m_that.lint32(data,record_offset+40),parts_start=offset+52,points_start=offset+52+4*num_parts,rings=[],i=0;num_parts>i;i++){var end,start=m_that.lint32(data,parts_start+4*i);end=num_parts>i+1?m_that.lint32(data,parts_start+4*(i+1)):num_points;var ring=readRing(points_start,start,end);rings.push(ring)}features.push({type:"Polyline",attr:{},geom:[rings]})}},attr=this.loadDBF(dbf_data),i=0;i=m_base64Str.length)return END_OF_INPUT;if(nextCharacter=m_base64Str.charAt(m_base64Count),m_base64Count++,m_reverseBase64Chars[nextCharacter])return m_reverseBase64Chars[nextCharacter];if("A"===nextCharacter)return 0}return END_OF_INPUT},this.decode64=function(str){var result="",inBuffer=new Array(4),done=!1;for(m_base64Str=str,m_base64Count=0;!done&&(inBuffer[0]=this.readReverseBase64())!==END_OF_INPUT&&(inBuffer[1]=this.readReverseBase64())!==END_OF_INPUT;)inBuffer[2]=this.readReverseBase64(),inBuffer[3]=this.readReverseBase64(),result+=this.ntos(inBuffer[0]<<2&255|inBuffer[1]>>4),inBuffer[2]!==END_OF_INPUT?(result+=this.ntos(inBuffer[1]<<4&255|inBuffer[2]>>2),inBuffer[3]!==END_OF_INPUT?result+=this.ntos(inBuffer[2]<<6&255|inBuffer[3]):done=!0):done=!0;return result},this.readNumber=function(ss){var v=ss[m_pos++]+(ss[m_pos++]<<8)+(ss[m_pos++]<<16)+(ss[m_pos++]<<24);return v},this.readF3Array=function(numberOfPoints,ss){var i,size=4*numberOfPoints*3,test=new Int8Array(size),points=null;for(i=0;size>i;i++)test[i]=ss[m_pos++];return points=new Float32Array(test.buffer)},this.readColorArray=function(numberOfPoints,ss,vglcolors){var i,idx=0,tmp=new Array(3*numberOfPoints);for(i=0;numberOfPoints>i;i++)tmp[idx++]=ss[m_pos++]/255,tmp[idx++]=ss[m_pos++]/255,tmp[idx++]=ss[m_pos++]/255,m_pos++;vglcolors.insert(tmp)},this.parseObject=function(vtkObject){var size,actor,colorMapData,shaderProg,opacityUniform,lookupTable,colorTable,windowSize,width,height,position,geom=new vgl.geometryData,mapper=vgl.mapper(),ss=[],type=null,data=null,matrix=null,material=null;for(data=atob(vtkObject.data),i=0;ii;i++)p[idx++]=points[3*i],p[idx++]=points[3*i+1],p[idx++]=points[3*i+2];for(vglpoints.insert(p),geom.addSource(vglpoints),vglcolors=new vgl.sourceDataC3fv,this.readColorArray(numberOfPoints,ss,vglcolors),geom.addSource(vglcolors),vgllines=new vgl.lines,geom.addPrimitive(vgllines),numberOfIndex=this.readNumber(ss),temp=new Int8Array(2*numberOfIndex),i=0;2*numberOfIndex>i;i++)temp[i]=ss[m_pos++];for(index=new Uint16Array(temp.buffer),vgllines.setIndices(index),vgllines.setPrimitiveType(gl.LINES),size=64,temp=new Int8Array(size),i=0;size>i;i++)temp[i]=ss[m_pos++];return m=new Float32Array(temp.buffer),mat4.copy(matrix,m),matrix},this.parseMeshData=function(geom,ss){var numberOfIndex,numberOfPoints,points,temp,index,size,m,i,tcoord,vglpoints=null,vglcolors=null,normals=null,matrix=mat4.create(),vgltriangles=null,pn=null,idx=0;for(numberOfPoints=this.readNumber(ss),pn=new Array(6*numberOfPoints),vglpoints=new vgl.sourceDataP3N3f,points=this.readF3Array(numberOfPoints,ss),normals=this.readF3Array(numberOfPoints,ss),i=0;numberOfPoints>i;i++)pn[idx++]=points[3*i],pn[idx++]=points[3*i+1],pn[idx++]=points[3*i+2],pn[idx++]=normals[3*i],pn[idx++]=normals[3*i+1],pn[idx++]=normals[3*i+2];for(vglpoints.insert(pn),geom.addSource(vglpoints),vglcolors=new vgl.sourceDataC3fv,this.readColorArray(numberOfPoints,ss,vglcolors),geom.addSource(vglcolors),temp=[],vgltriangles=new vgl.triangles,numberOfIndex=this.readNumber(ss),temp=new Int8Array(2*numberOfIndex),i=0;2*numberOfIndex>i;i++)temp[i]=ss[m_pos++];for(index=new Uint16Array(temp.buffer),vgltriangles.setIndices(index),geom.addPrimitive(vgltriangles),size=64,temp=new Int8Array(size),i=0;size>i;i++)temp[i]=ss[m_pos++];return m=new Float32Array(temp.buffer),mat4.copy(matrix,m),tcoord=null,matrix},this.parsePointData=function(geom,ss){var numberOfPoints,points,indices,temp,size,m,matrix=mat4.create(),vglpoints=null,vglcolors=null,vglVertexes=null,p=null,idx=0;for(numberOfPoints=this.readNumber(ss),p=new Array(3*numberOfPoints),vglpoints=new vgl.sourceDataP3fv,points=this.readF3Array(numberOfPoints,ss),indices=new Uint16Array(numberOfPoints),i=0;numberOfPoints>i;i++)indices[i]=i,p[idx++]=points[3*i],p[idx++]=points[3*i+1],p[idx++]=points[3*i+2];for(vglpoints.insert(p),geom.addSource(vglpoints),vglcolors=new vgl.sourceDataC3fv,this.readColorArray(numberOfPoints,ss,vglcolors),geom.addSource(vglcolors),vglVertexes=new vgl.points,vglVertexes.setIndices(indices),geom.addPrimitive(vglVertexes),size=64,temp=new Int8Array(size),i=0;size>i;i++)temp[i]=ss[m_pos++];return m=new Float32Array(temp.buffer),mat4.copy(matrix,m),matrix},this.parseColorMapData=function(geom,ss,numColors){var tmpArray,size,xrgb,i,c,obj={};for(obj.numOfColors=numColors,size=8,tmpArray=new Int8Array(size),i=0;size>i;i++)tmpArray[i]=ss[m_pos++];for(obj.position=new Float32Array(tmpArray.buffer),size=8,tmpArray=new Int8Array(size),i=0;size>i;i++)tmpArray[i]=ss[m_pos++];for(obj.size=new Float32Array(tmpArray.buffer),obj.colors=[],c=0;ci;i++)tmpArray[i]=ss[m_pos++];xrgb=[new Float32Array(tmpArray.buffer)[0],ss[m_pos++],ss[m_pos++],ss[m_pos++]],obj.colors[c]=xrgb}for(obj.orientation=ss[m_pos++],obj.numOfLabels=ss[m_pos++],obj.title="";m_pos=0;layer--)renderer=this.getRenderer(layer),this.parseSceneMetadata(renderer,layer);return m_viewer},this.createViewer=function(node){var interactorStyle;return null===m_viewer&&(m_node=node,m_viewer=vgl.viewer(node),m_viewer.init(),m_vtkRenderedList[0]=m_viewer.renderWindow().activeRenderer(),m_viewer.renderWindow().resize(node.width,node.height),interactorStyle=vgl.pvwInteractorStyle(),m_viewer.setInteractorStyle(interactorStyle)),m_viewer},this.deleteViewer=function(){m_vtkRenderedList={},m_viewer=null},this.updateCanvas=function(node){return m_node=node,m_viewer.renderWindow().resize(node.width,node.height),m_viewer},this.numObjects=function(){return m_vtkObjectCount},this.getRenderer=function(layer){var renderer;return renderer=m_vtkRenderedList[layer],(null===renderer||"undefined"==typeof renderer)&&(renderer=new vgl.renderer,renderer.setResetScene(!1),renderer.setResetClippingRange(!1),m_viewer.renderWindow().addRenderer(renderer),0!==layer&&renderer.camera().setClearMask(vgl.GL.DepthBufferBit),m_vtkRenderedList[layer]=renderer),renderer},this.setVtkScene=function(scene){m_vtkScene=scene},this},vgl.DataBuffers=function(initialSize){if(!(this instanceof vgl.DataBuffers))return new vgl.DataBuffers(initialSize);var size,data={};size=initialSize||0===initialSize?initialSize:256;var current=0,copyArray=function(dst,src,start,count){dst||console.log("ack"),start||(start=0),count||(count=src.length);for(var i=0;count>i;i++)dst[start+i]=src[i]},resize=function(min_expand){var new_size=size;for(min_expand>2*new_size&&(new_size=min_expand);min_expand>new_size;)new_size*=2;size=new_size;for(var name in data){var newArray=new Float32Array(new_size*data[name].len),oldArray=data[name].array;copyArray(newArray,oldArray),data[name].array=newArray,data[name].dirty=!0}};this.create=function(name,len){if(!len)throw"Length of buffer must be a positive integer";var array=new Float32Array(size*len);return data[name]={array:array,len:len,dirty:!1},data[name].array},this.alloc=function(num){current+num>=size&&resize(current+num);var start=current;return current+=num,start},this.get=function(name){return data[name].array},this.write=function(name,array,start,count){copyArray(data[name].array,array,start*data[name].len,count*data[name].len),data[name].dirty=!0},this.repeat=function(name,elem,start,count){for(var i=0;count>i;i++)copyArray(data[name].array,elem,(start+i)*data[name].len,data[name].len);data[name].dirty=!0},this.count=function(){return current},this.data=function(name){return data[name].array}},function(){"use strict";function setNumeric(){var i;for(i=0;in?!1:(outer.forEach(function(vert,i){var j=(n+i-1)%n,intersect=outer[i].y>point.y!=outer[j].y>point.y&&point.x<(outer[j].x-outer[i].x)*(point.y-outer[i].y)/(outer[j].y-outer[i].y)+outer[i].x;intersect&&(inside=!inside)}),(inner||[]).forEach(function(hole){inside=inside&&!geo.util.pointInPolygon(point,hole)}),inside)},isFunction:function(f){return"function"==typeof f},ensureFunction:function(f){return geo.util.isFunction(f)?f:function(){return f}},randomString:function(n){var s,i,r;for(n=n||8,s="",i=0;n>i;i+=1)r=Math.floor(Math.random()*chars.length),s+=chars.substring(r,r+1);return s},convertColor:function(color){return void 0!==color.r&&void 0!==color.g&&void 0!==color.b?color:("string"==typeof color&&(geo.util.cssColors.hasOwnProperty(color)?color=geo.util.cssColors[color]:"#"===color.charAt(0)&&(color=parseInt(color.slice(1),16))),isFinite(color)&&(color={r:((16711680&color)>>16)/255,g:((65280&color)>>8)/255,b:(255&color)/255}),color)},normalizeCoordinates:function(p){return p=p||{},Array.isArray(p)?{x:p[0],y:p[1],z:p[2]||0}:p instanceof geo.latlng?{x:p.lng(),y:p.lat(),z:0}:{x:setNumeric(p.x,p.longitude,p.lng,p.lon,0),y:setNumeric(p.y,p.latitude,p.lat,0),z:setNumeric(p.z,p.elevation,p.elev,p.height,0)}}},geo.util.cssColors={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,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}}(),function(){"use strict";function vect(x,y){return new Vector2D(x,y)}var RangeNode=function(elem,start,end,current){this.data=elem[current],this.left=null,this.right=null,start!=current&&(this.left=new RangeNode(elem,start,current-1,parseInt((start+(current-1))/2,10))),end!=current&&(this.right=new RangeNode(elem,current+1,end,parseInt((end+(current+1))/2,10))),this.subtree=[];for(var i=start;end>=i;i++)this.subtree.push(elem[i]);this.subtree.sort(function(a,b){return a.y-b.y});var xrange=function(b){return b.x_in(elem[start])&&b.x_in(elem[end])};this.yrange=function(b,start,end){return b.y_in(this.subtree[start])&&b.y_in(this.subtree[end])},this.subquery=function(result,box,start,end,current){if(this.yrange(box,start,end))for(var i=start;end>=i;i++)result.push(this.subtree[i]);else box.y_in(this.subtree[current])&&result.push(this.subtree[current]),box.y_left(this.subtree[current])?current!=end&&this.subquery(result,box,current+1,end,parseInt((end+(current+1))/2,10)):box.x_right(this.subtree[current])?current!=start&&this.subquery(result,box,start,current-1,parseInt((start+(current-1))/2,10)):(current!=end&&this.subquery(result,box,current+1,end,parseInt((end+(current+1))/2,10)),current!=start&&this.subquery(result,box,start,current-1,parseInt((start+(current-1))/2,10)))},this.search=function(result,box){return xrange(box)?void this.subquery(result,box,0,this.subtree.length-1,parseInt((this.subtree.length-1)/2,10)):(box.contains(this.data)&&result.push(this.data),void(box.x_left(this.data)?this.right&&this.right.search(result,box):box.x_right(this.data)?this.left&&this.left.search(result,box):(this.left&&this.left.search(result,box),this.right&&this.right.search(result,box))))}},RangeTree=function(elem){elem.sort(function(a,b){return a.x-b.x}),this.root=elem.length>0?new RangeNode(elem,0,elem.length-1,parseInt((elem.length-1)/2,10)):null,this.search=function(_box){if(!this.root)return[];var box=_box.clone(),result=[];return this.root.search(result,box),result}},Box=function(v1,v2){this.min=v1.clone(),this.max=v2.clone(),this.contains=function(p){return v1.x<=p.x&&v2.x>=p.x&&v1.y<=p.y&&v2.y>=p.y},this.x_in=function(p){return v1.x<=p.x&&v2.x>=p.x},this.x_left=function(p){return v1.x>=p.x},this.x_right=function(p){return v2.x<=p.x},this.y_in=function(p){return v1.y<=p.y&&v2.y>=p.y},this.y_left=function(p){return v1.y>=p.y},this.y_right=function(p){return v2.y<=p.y},this.area=function(){return(this.max.x-this.min.x)*(this.max.y-this.min.y)},this.height=function(){return this.max.y-this.min.y},this.width=function(){return this.max.x-this.min.x},this.vertex=function(index){switch(index){case 0:return this.min.clone();case 1:return new vect(this.max.x,this.min.y);case 2:return this.max.clone();case 3:return new vect(this.min.x,this.max.y);default:throw"Index out of bounds: "+index}},this.intersects=function(box){for(var i=0;4>i;i++)for(var j=0;4>j;j++)if(vect.intersects(this.vertex(i),this.vertex((i+1)%4),box.vertex(j),box.vertex((j+1)%4)))return!0;return this.contains(box.min)&&this.contains(box.max)&&this.contains(new vect(box.min.x,box.max.y))&&this.contains(new vect(box.max.x,box.min.y))?!0:box.contains(this.min)&&box.contains(this.max)&&box.contains(new vect(this.min.x,this.max.y))&&box.contains(new vect(this.max.x,this.min.y))?!0:!1},this.union=function(b){this.min.x=Math.min(this.min.x,b.min.x),this.min.y=Math.min(this.min.y,b.min.y),this.max.x=Math.max(this.max.x,b.max.x),this.max.y=Math.max(this.max.y,b.max.y)},this.centroid=function(){return new vect((this.max.x+this.min.x)/2,(this.max.y+this.min.y)/2)},this.clone=function(){return new Box(v1,v2)}},Vector2D=function(x,y){this.x=x,this.y=y,this.add=function(v){return this.x+=v.x,this.y+=v.y,this},this.sub=function(v){return this.x-=v.x,this.y-=v.y,this},this.scale=function(s){return this.x*=s,this.y*=s,this},this.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},this.normalize=function(){var scale=this.length();return 0===scale?this:(this.x/=scale,this.y/=scale,this)},this.div=function(v){return this.x/=v.x,this.y/=v.y,this},this.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},this.zero=function(tol){return tol=tol||0,this.length()<=tol},this.dot=function(v){return this.x*v.x+this.y*v.y},this.cross=function(v){return this.x*v.y-this.y*v.x},this.rotate=function(omega){var cos=Math.cos(omega),sin=Math.sin(omega);return xp=cos*this.x-sin*this.y,yp=sin*this.x+cos*this.y,this.x=xp,this.y=yp,this},this.clone=function(){return new Vector2D(this.x,this.y)},this.array=function(){return[this.x,this.y]}};vect.scale=function(v,s){return v.clone().scale(s)},vect.add=function(v1,v2){return v1.clone().add(v2)},vect.sub=function(v1,v2){return v1.clone().sub(v2)},vect.dist=function(v1,v2){return v1.clone().sub(v2).length()},vect.dir=function(v1,v2){return v1.clone().sub(v2).normalize()},vect.dot=function(v1,v2){return v1.x*v2.x+v1.y*v2.y},vect.cross=function(v1,v2){return v1.x*v2.y-v1.y*v2.x},vect.left=function(a,b,c,tol){tol||(tol=0);var v1=vect.sub(b,a),v2=vect.sub(c,a);return vect.cross(v1,v2)>=-tol},vect.intersects=function(a,b,c,d,tol){return tol||(tol=0),vect.left(a,b,c,tol)!=vect.left(a,b,d,tol)&&vect.left(c,d,b,tol)!=vect.left(c,d,a,tol)},vect.intersect2dt=function(a,b,c,d){var denom=a.x*(d.y-c.y)+b.x*(c.y-d.y)+d.x*(b.y-a.y)+c.x*(a.y-b.y);if(0===denom)return 1/0;var num_t=(a.x*(d.y-c.y)+c.x*(a.y-d.y)+d.x*(c.y-a.y),-(a.x*(c.y-b.y)+b.x*(a.y-c.y)+c.x*(b.y-a.y))),t=num_t/denom;return t},vect.intersect2dpos=function(a,b,c,d){var denom=a.x*(d.y-c.y)+b.x*(c.y-d.y)+d.x*(b.y-a.y)+c.x*(a.y-b.y);if(0===denom)return 1/0;var num_s=a.x*(d.y-c.y)+c.x*(a.y-d.y)+d.x*(c.y-a.y),s=num_s/denom,dir=vect.sub(b,a);return dir.scale(s),vect.add(a,dir)},vect.rotate=function(v,omega){var cos=Math.cos(omega),sin=Math.sin(omega);xp=cos*v.x-sin*v.y,yp=sin*v.x+cos*v.y;var c=new vect(xp,yp);return c},vect.normalize=function(v){return v.clone().normalize()},geo.util.RangeTree=RangeTree,geo.util.Box=Box,geo.util.vect=vect}(),geo.object=function(){"use strict";if(!(this instanceof geo.object))return new geo.object;var m_this=this,m_eventHandlers={},m_idleHandlers=[],m_deferredCount=0;return this.onIdle=function(handler){return m_deferredCount?m_idleHandlers.push(handler):handler(),m_this},this.addDeferred=function(defer){return m_deferredCount+=1,defer.done(function(){m_deferredCount-=1,m_deferredCount||m_idleHandlers.splice(0,m_idleHandlers.length).forEach(function(handler){handler()})}),m_this},this.geoOn=function(event,handler){return Array.isArray(event)?(event.forEach(function(e){m_this.geoOn(e,handler)}),m_this):(m_eventHandlers.hasOwnProperty(event)||(m_eventHandlers[event]=[]),m_eventHandlers[event].push(handler),m_this)},this.geoTrigger=function(event,args){return Array.isArray(event)?(event.forEach(function(e){m_this.geoTrigger(e,args)}),m_this):(m_eventHandlers.hasOwnProperty(event)&&m_eventHandlers[event].forEach(function(handler){handler.call(m_this,args)}),m_this)},this.geoOff=function(event,arg){if(void 0===event&&(m_eventHandlers={},m_idleHandlers=[],m_deferredCount=0),Array.isArray(event))return event.forEach(function(e){m_this.geoOff(e,arg)}),m_this;if(arg){if(Array.isArray(arg))return arg.forEach(function(handler){m_this.geoOff(event,handler)}),m_this}else m_eventHandlers[event]=[];return m_eventHandlers.hasOwnProperty(event)&&(m_eventHandlers[event]=m_eventHandlers[event].filter(function(f){return f!==arg})),m_this},this._exit=function(){m_this.geoOff()},vgl.object.call(this),this},inherit(geo.object,vgl.object),geo.sceneObject=function(arg){"use strict";if(!(this instanceof geo.sceneObject))return new geo.sceneObject;geo.object.call(this,arg);var m_this=this,m_parent=null,m_children=[],s_exit=this._exit,s_trigger=this.geoTrigger,s_addDeferred=this.addDeferred,s_onIdle=this.onIdle;return this.addDeferred=function(defer){m_parent?m_parent.addDeferred(defer):s_addDeferred(defer)},this.onIdle=function(handler){m_parent?m_parent.onIdle(handler):s_onIdle(handler)},this.parent=function(arg){return void 0===arg?m_parent:(m_parent=arg,m_this)},this.addChild=function(child){return Array.isArray(child)?(child.forEach(m_this.addChild),m_this):(child.parent(m_this),m_children.push(child),m_this)},this.removeChild=function(child){return Array.isArray(child)?(child.forEach(m_this.removeChild),m_this):(m_children=m_children.filter(function(c){return c!==child}),m_this)},this.children=function(){return m_children.slice()},this.draw=function(arg){return m_this.children().forEach(function(child){child.draw(arg)}),m_this},this.geoTrigger=function(event,args,childrenOnly){var geoArgs;return args=args||{},geoArgs=args.geo||{},args.geo=geoArgs,geoArgs.stopPropagation?m_this:!childrenOnly&&m_parent&&geoArgs._triggeredBy!==m_parent?(geoArgs._triggeredBy=m_this,m_parent.geoTrigger(event,args),m_this):(s_trigger.call(m_this,event,args),geoArgs.stopPropagation?m_this:(m_children.forEach(function(child){geoArgs._triggeredBy=m_this,child.geoTrigger(event,args)}),m_this))},this._exit=function(){m_this.children=[],delete m_this.parent,s_exit()},this},inherit(geo.sceneObject,geo.object),geo.timestamp=function(){"use strict";return this instanceof geo.timestamp?void vgl.timestamp.call(this):new geo.timestamp},inherit(geo.timestamp,vgl.timestamp),geo.ellipsoid=function(x,y,z){"use strict";if(!(this instanceof geo.ellipsoid))return new geo.ellipsoid(x,y,z);if(x=vgl.defaultValue(x,0),y=vgl.defaultValue(y,0),z=vgl.defaultValue(z,0),0>x||0>y||0>z)return console.log("[error] Al radii components must be greater than zero");var m_this=this,m_radii=new vec3.fromValues(x,y,z),m_radiiSquared=new vec3.fromValues(x*x,y*y,z*z),m_minimumRadius=Math.min(x,y,z),m_maximumRadius=Math.max(x,y,z);return this.radii=function(){return m_radii},this.radiiSquared=function(){return m_radiiSquared},this.maximumRadius=function(){return m_maximumRadius},this.minimumRadius=function(){return m_minimumRadius},this.computeGeodeticSurfaceNormal=function(lat,lon){if("undefined"==typeof lat||"undefined"==typeof lon)throw"[error] Valid latitude and longitude is required";var cosLatitude=Math.cos(lat),result=vec3.create();return result[0]=cosLatitude*Math.cos(lon),result[1]=cosLatitude*Math.sin(lon),result[2]=Math.sin(lat),vec3.normalize(result,result),result},this.transformPoint=function(lat,lon,elev){lat*=Math.PI/180,lon*=Math.PI/180;var n=m_this.computeGeodeticSurfaceNormal(lat,lon),k=vec3.create(),gamma=Math.sqrt(vec3.dot(n,k)),result=vec3.create();return vec3.multiply(k,m_radiiSquared,n),vec3.scale(k,k,1/gamma),vec3.scale(n,n,elev),vec3.add(result,n,k),result},this.transformGeometry=function(geom){if(!geom)throw"[error] Failed to transform to cartesian. Invalid geometry.";var sourceData=geom.sourceData(vgl.vertexAttributeKeys.Position),sourceDataArray=sourceData.data(),noOfComponents=sourceData.attributeNumberOfComponents(vgl.vertexAttributeKeys.Position),stride=sourceData.attributeStride(vgl.vertexAttributeKeys.Position),offset=sourceData.attributeOffset(vgl.vertexAttributeKeys.Position),sizeOfDataType=sourceData.sizeOfAttributeDataType(vgl.vertexAttributeKeys.Position),index=null,count=sourceDataArray.length*(1/noOfComponents),gamma=null,n=null,j=0,k=vec3.create(),result=vec3.create();if(stride/=sizeOfDataType,offset/=sizeOfDataType,3!==noOfComponents)throw"[error] Requires positions with three components";for(j=0;count>j;j+=1)index=j*stride+offset,sourceDataArray[index]=sourceDataArray[index]*(Math.PI/180),sourceDataArray[index+1]=sourceDataArray[index+1]*(Math.PI/180),n=m_this.computeGeodeticSurfaceNormal(sourceDataArray[index+1],sourceDataArray[index]),vec3.multiply(k,m_radiiSquared,n),gamma=Math.sqrt(vec3.dot(n,k)),vec3.scale(k,k,1/gamma),vec3.scale(n,n,sourceDataArray[index+2]),vec3.add(result,n,k),sourceDataArray[index]=result[0],sourceDataArray[index+1]=result[1],sourceDataArray[index+2]=result[2]},m_this},geo.ellipsoid.WGS84=vgl.freezeObject(geo.ellipsoid(6378137,6378137,6356752.314245179)),geo.ellipsoid.UNIT_SPHERE=vgl.freezeObject(geo.ellipsoid(1,1,1)),geo.mercator={r_major:6378137},geo.mercator.r_minor=function(spherical){"use strict";var r_minor;return spherical=void 0!==spherical?spherical:!1,r_minor=spherical?6378137:6356752.314245179},geo.mercator.f=function(spherical){"use strict";return(geo.mercator.r_major-geo.mercator.r_minor(spherical))/geo.mercator.r_major},geo.mercator.long2tilex=function(lon,z){"use strict";var rad=(lon+180)/360,f=Math.floor(rad*Math.pow(2,z));return f},geo.mercator.lat2tiley=function(lat,z){"use strict";var rad=lat*Math.PI/180;return Math.floor((1-rad/Math.PI)/2*Math.pow(2,z))},geo.mercator.long2tilex2=function(lon,z){"use strict";var rad=(lon+180)/360,f=rad*Math.pow(2,z),ret=Math.floor(f),frac=f-ret;return[ret,frac]},geo.mercator.lat2tiley2=function(lat,z){"use strict";var rad=lat*Math.PI/180,f=(1-Math.log(Math.tan(rad)+1/Math.cos(rad))/Math.PI)/2*Math.pow(2,z),ret=Math.floor(f),frac=f-ret;return[ret,frac]},geo.mercator.tilex2long=function(x,z){"use strict";return x/Math.pow(2,z)*360-180},geo.mercator.tiley2lat=function(y,z){"use strict";var n=Math.PI-2*Math.PI*y/Math.pow(2,z);return 180/Math.PI*Math.atan(.5*(Math.exp(n)-Math.exp(-n)))},geo.mercator.y2lat=function(a){"use strict";return 180/Math.PI*(2*Math.atan(Math.exp(a*Math.PI/180))-Math.PI/2)},geo.mercator.lat2y=function(a){"use strict";return 180/Math.PI*Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2))},geo.mercator.deg2rad=function(d){"use strict";var r=d*(Math.PI/180);return r},geo.mercator.rad2deg=function(r){"use strict";var d=r/(Math.PI/180);return d},geo.mercator.ll2m=function(lon,lat,spherical){"use strict";lat>89.5&&(lat=89.5),-89.5>lat&&(lat=-89.5);var x=this.r_major*this.deg2rad(lon),temp=this.r_minor(spherical)/this.r_major,es=1-temp*temp,eccent=Math.sqrt(es),phi=this.deg2rad(lat),sinphi=Math.sin(phi),con=eccent*sinphi,com=.5*eccent,con2=Math.pow((1-con)/(1+con),com),ts=Math.tan(.5*(.5*Math.PI-phi))/con2,y=-this.r_major*Math.log(ts),ret={x:x,y:y};return ret},geo.mercator.m2ll=function(x,y,spherical){"use strict";var lon=this.rad2deg(x/this.r_major),temp=this.r_minor(spherical)/this.r_major,e=Math.sqrt(1-temp*temp),lat=this.rad2deg(this.pjPhi2(Math.exp(-(y/this.r_major)),e)),ret={lon:lon,lat:lat};return ret},geo.mercator.pjPhi2=function(ts,e){"use strict";var con,dphi,N_ITER=15,HALFPI=Math.PI/2,TOL=1e-10,i=N_ITER,eccnth=.5*e,Phi=HALFPI-2*Math.atan(ts);do con=e*Math.sin(Phi),dphi=HALFPI-2*Math.atan(ts*Math.pow((1-con)/(1+con),eccnth))-Phi,Phi+=dphi,i-=1;while(Math.abs(dphi)>TOL&&i);return Phi},geo.latlng=function(arg1,arg2,arg3){"use strict";if(!(this instanceof geo.latlng))return new geo.latlng(arg1,arg2,arg3);var m_this=this,m_lat=void 0===arg2&&void 0===arg3?arg1.lat():arg1,m_lng=void 0===arg2&&void 0===arg3?arg1.lng():arg2,m_elv=void 0===arg2&&void 0===arg3?arg1.elv():arg3;return this.lat=function(val){return void 0===val?m_lat:void(m_lat=val)},this.lng=function(val){return void 0===val?m_lng:void(m_lng=val)},this.elv=function(val){return void 0===val?m_elv:void(m_elv=val)},this.x=function(val){return void 0===val?m_this.lng():void(m_lng=val)},this.y=function(val){return void 0===val?m_this.lat():void(m_lat=val)},this.z=function(val){return void 0===val?m_this.elv():void(m_elv=val)},this},geo.layer=function(arg){"use strict";if(!(this instanceof geo.layer))return new geo.layer(arg);arg=arg||{},geo.sceneObject.call(this,arg);var m_this=this,s_exit=this._exit,m_style=void 0===arg.style?{opacity:.5,color:[.8,.8,.8],visible:!0,bin:100}:arg.style,m_id=void 0===arg.id?geo.layer.newLayerId():arg.id,m_name="",m_gcs="EPSG:4326",m_timeRange=null,m_source=arg.source||null,m_map=void 0===arg.map?null:arg.map,m_isReference=!1,m_x=0,m_y=0,m_width=0,m_height=0,m_node=null,m_canvas=null,m_renderer=null,m_initialized=!1,m_rendererName=void 0===arg.renderer?"vgl":arg.renderer,m_dataTime=geo.timestamp(),m_updateTime=geo.timestamp(),m_drawTime=geo.timestamp(),m_sticky=void 0===arg.sticky?!0:arg.sticky,m_active=void 0===arg.active?!0:arg.active;return this.sticky=function(){return m_sticky},this.active=function(){return m_active},this.node=function(){return m_node},this.id=function(val){return void 0===val?m_id:(m_id=geo.newLayerId(),m_this.modified(),m_this)},this.name=function(val){return void 0===val?m_name:(m_name=val,m_this.modified(),m_this)},this.opacity=function(val){return void 0===val?m_style.opacity:(m_style.opacity=val,m_this.modified(),m_this)},this.visible=function(val){return void 0===val?m_style.visible:(m_style.visible=val,m_this.modified(),m_this)},this.bin=function(val){return void 0===val?m_style.bin:(m_style.bin=val,m_this.modified(),m_this)},this.gcs=function(val){return void 0===val?m_gcs:(m_gcs=val,m_this.modified(),m_this)},this.transform=function(val){return geo.transform.transformLayer(val,m_this,m_map.baseLayer()),m_this},this.timeRange=function(val){return void 0===val?m_timeRange:(m_timeRange=val,m_this.modified(),m_this)},this.source=function(val){return void 0===val?m_source:(m_source=val,m_this.modified(),m_this)},this.map=function(val){return void 0===val?m_map:(m_map=val,m_map.node().append(m_node),m_this.modified(),m_this)},this.renderer=function(){return m_renderer},this.canvas=function(){return m_canvas},this.viewport=function(){return[m_x,m_y,m_width,m_height]},this.dataTime=function(){return m_dataTime},this.updateTime=function(){return m_updateTime},this.drawTime=function(){return m_drawTime},this.query=function(){},this.referenceLayer=function(val){return void 0!==val?(m_isReference=val,m_this.modified(),m_this):m_isReference},this.initialized=function(val){return void 0!==val?(m_initialized=val,m_this):m_initialized},this.toLocal=function(input){return input},this.fromLocal=function(input){return input},this._init=function(){return m_initialized?m_this:(m_node=$(document.createElement("div")),m_node.attr("id",m_name),m_node.css("position","absolute"),m_map&&m_map.node().append(m_node),m_canvas?m_renderer=geo.createRenderer(m_rendererName,m_this,m_canvas):(m_renderer=geo.createRenderer(m_rendererName,m_this),m_canvas=m_renderer.canvas()),m_this.active()||m_node.css("pointerEvents","none"),m_initialized=!0,m_this)},this._exit=function(){m_renderer._exit(),m_node.off(),m_node.remove(),m_node=null,arg={},m_canvas=null,m_renderer=null,s_exit()},this._update=function(){},this._resize=function(x,y,w,h){return m_x=x,m_y=y,m_width=w,m_height=h,m_node.width(w),m_node.height(h),m_this.modified(),m_this.geoTrigger(geo.event.resize,{x:x,y:y,width:m_width,height:m_height}),m_this},this.width=function(){return m_width},this.height=function(){return m_height},this},geo.layer.newLayerId=function(){"use strict";var currentId=1;return function(){var id=currentId;return currentId+=1,id}}(),geo.layer.create=function(map,spec){"use strict";if(spec=spec||{},spec.type="feature","feature"!==spec.type)return console.warn("Unsupported layer type"),null;if(spec.renderer=spec.renderer||"vgl","d3"!==spec.renderer&&"vgl"!==spec.renderer)return console.warn("Invalid renderer"),null;var layer=map.createLayer(spec.type,spec);return layer?(spec.features.forEach(function(f){f.data=f.data||spec.data,f.feature=geo.feature.create(layer,f)}),layer):(console.warn("Unable to create a layer"),null)},inherit(geo.layer,geo.sceneObject),
-geo.featureLayer=function(arg){"use strict";if(!(this instanceof geo.featureLayer))return new geo.featureLayer(arg);geo.layer.call(this,arg);var m_this=this,m_features=[],s_init=this._init,s_exit=this._exit,s_update=this._update,s_draw=this.draw;return this.createFeature=function(featureName,arg){var newFeature=geo.createFeature(featureName,m_this,m_this.renderer(),arg);return m_this.addChild(newFeature),m_features.push(newFeature),m_this.features(m_features),m_this.modified(),newFeature},this.deleteFeature=function(feature){var i;for(i=0;im_this.updateTime().getMTime())for(i=0;i=deltaT?30:deltaT;var sf=springForce(),speed=calcSpeed(v),vx=v.x/speed,vy=v.y/speed;return speed*=Math.exp(-m_options.momentum.drag*deltaT),calcSpeed(sf)*deltaT+speed0?(vx*=speed,vy*=speed):(vx=0,vy=0),{x:vx-sf.x*deltaT,y:vy-sf.y*deltaT})}function springForce(){var xplus,xminus,yplus,yminus;if(!m_options.spring.enabled)return{x:0,y:0};var ul=m_this.map().gcsToDisplay({x:-180,y:82}),lr=m_this.map().gcsToDisplay({x:180,y:-82}),c=m_options.spring.springConstant,width=m_this.map().node().width(),height=m_this.map().node().height();return xplus=c*Math.max(0,ul.x),xminus=c*Math.max(0,width-lr.x),yplus=c*Math.max(0,ul.y)/2,yminus=c*Math.max(0,height-lr.y)/2,{x:xplus-xminus,y:yplus-yminus}}if(!(this instanceof geo.mapInteractor))return new geo.mapInteractor(args);geo.object.call(this);var m_mouse,m_keyboard,m_state,$node,m_options=args||{},m_this=this,m_wheelQueue={x:0,y:0},m_throttleTime=10,m_wait=!1,m_disableThrottle=!0,m_selectionLayer=null,m_selectionPlane=null;return m_options=$.extend(!0,{panMoveButton:"left",panMoveModifiers:{},zoomMoveButton:"right",zoomMoveModifiers:{},panWheelEnabled:!1,panWheelModifiers:{},zoomWheelEnabled:!0,zoomWheelModifiers:{},wheelScaleX:1,wheelScaleY:1,zoomScale:1,selectionButton:"left",selectionModifiers:{shift:!0},momentum:{enabled:!0,maxSpeed:2.5,minSpeed:.01,drag:.01},spring:{enabled:!1,springConstant:5e-5}},m_options),m_mouse={page:{x:0,y:0},map:{x:0,y:0},buttons:{left:!1,right:!1,middle:!1},modifiers:{alt:!1,ctrl:!1,shift:!1,meta:!1},time:new Date,deltaTime:1,velocity:{x:0,y:0}},m_keyboard={},m_state={},this._connectEvents=function(){return m_options.map?(m_this._disconnectEvents(),$node=$(m_options.map.node()),$node.on("mousemove.geojs",m_this._handleMouseMove),$node.on("mousedown.geojs",m_this._handleMouseDown),$node.on("mouseup.geojs",m_this._handleMouseUp),$node.on("mousewheel.geojs",m_this._handleMouseWheel),("right"===m_options.panMoveButton||"right"===m_options.zoomMoveButton)&&$node.on("contextmenu.geojs",function(){return!1}),m_this):m_this},this._disconnectEvents=function(){return $node&&($node.off(".geojs"),$node=null),m_this},this.map=function(val){return void 0!==val?(m_options.map=val,m_this._connectEvents(),m_this):m_options.map},this.options=function(opts){return void 0===opts?$.extend({},m_options):($.extend(m_options,opts),m_this)},this._getMousePosition=function(evt){var dt,t,offset=$node.offset();t=(new Date).valueOf(),dt=t-m_mouse.time,m_mouse.time=t,m_mouse.deltaTime=dt,m_mouse.velocity={x:(evt.pageX-m_mouse.page.x)/dt,y:(evt.pageY-m_mouse.page.y)/dt},m_mouse.page={x:evt.pageX,y:evt.pageY},m_mouse.map={x:evt.pageX-offset.left,y:evt.pageY-offset.top};try{m_mouse.geo=m_this.map().displayToGcs(m_mouse.map)}catch(e){m_mouse.geo=null}},this._getMouseButton=function(evt){1===evt.which?m_mouse.buttons.left="mouseup"!==evt.type:3===evt.which?m_mouse.buttons.right="mouseup"!==evt.type:2===evt.which&&(m_mouse.buttons.middle="mouseup"!==evt.type)},this._getMouseModifiers=function(evt){m_mouse.modifiers.alt=evt.altKey,m_mouse.modifiers.ctrl=evt.ctrlKey,m_mouse.modifiers.meta=evt.metaKey,m_mouse.modifiers.shift=evt.shiftKey},this._getSelection=function(){var origin=m_state.origin,mouse=m_this.mouse(),map=m_this.map(),display={},gcs={};return display.upperLeft={x:Math.min(origin.map.x,mouse.map.x),y:Math.min(origin.map.y,mouse.map.y)},display.lowerRight={x:Math.max(origin.map.x,mouse.map.x),y:Math.max(origin.map.y,mouse.map.y)},display.upperRight={x:display.lowerRight.x,y:display.upperLeft.y},display.lowerLeft={x:display.upperLeft.x,y:display.lowerRight.y},gcs.upperLeft=map.displayToGcs(display.upperLeft),gcs.lowerRight=map.displayToGcs(display.lowerRight),gcs.upperRight=map.displayToGcs(display.upperRight),gcs.lowerLeft=map.displayToGcs(display.lowerLeft),m_selectionPlane.origin([display.lowerLeft.x,display.lowerLeft.y,0]),m_selectionPlane.upperLeft([display.upperLeft.x,display.upperLeft.y,0]),m_selectionPlane.lowerRight([display.lowerRight.x,display.lowerRight.y,0]),m_selectionPlane.draw(),{display:display,gcs:gcs,mouse:mouse,origin:$.extend({},m_state.origin)}},this.cancel=function(action){var out;return out=action?m_state.action===action:!!m_state.action,out&&(m_state={}),out},this._handleMouseDown=function(evt){var action=null;"momentum"===m_state.action&&(m_state={}),m_this._getMousePosition(evt),m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),eventMatch(m_options.panMoveButton,m_options.panMoveModifiers)?action="pan":eventMatch(m_options.zoomMoveButton,m_options.zoomMoveModifiers)?action="zoom":eventMatch(m_options.selectionButton,m_options.selectionModifiers)&&(action="select"),m_mouse.velocity={x:0,y:0},action&&(m_state={action:action,origin:$.extend(!0,{},m_mouse),delta:{x:0,y:0}},"select"===action&&(m_selectionLayer&&(m_selectionLayer.clear(),m_this.map().deleteLayer(m_selectionLayer),m_selectionLayer=null),m_selectionLayer=m_this.map().createLayer("feature",{renderer:"d3"}),m_selectionPlane=m_selectionLayer.createFeature("plane"),m_selectionPlane.style({screenCoordinates:!0,fillOpacity:function(){return.25}}),m_this.map().geoTrigger(geo.event.brushstart,m_this._getSelection())),$(document).on("mousemove.geojs",m_this._handleMouseMoveDocument),$(document).on("mouseup.geojs",m_this._handleMouseUpDocument))},this._handleMouseMove=function(evt){m_state.action||(m_this._getMousePosition(evt),m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),m_this.map().geoTrigger(geo.event.mousemove,m_this.mouse()))},this._handleMouseMoveDocument=function(evt){var dx,dy,selectionObj;return m_this._getMousePosition(evt),m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),m_state.action?void(doRespond()&&(dx=m_mouse.map.x-m_state.origin.map.x-m_state.delta.x,dy=m_mouse.map.y-m_state.origin.map.y-m_state.delta.y,m_state.delta.x+=dx,m_state.delta.y+=dy,"pan"===m_state.action?m_this.map().pan({x:dx,y:dy}):"zoom"===m_state.action?m_this.map().zoom(m_this.map().zoom()-dy*m_options.zoomScale/120):"select"===m_state.action&&(selectionObj=m_this._getSelection(),m_this.map().geoTrigger(geo.event.brush,selectionObj)),evt.preventDefault())):void console.log("WARNING: Invalid state in mapInteractor.")},this._handleMouseUpDocument=function(evt){var selectionObj,oldAction;m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),$(document).off(".geojs"),m_mouse.buttons.right&&evt.preventDefault(),"select"===m_state.action&&(selectionObj=m_this._getSelection(),m_selectionLayer.clear(),m_this.map().deleteLayer(m_selectionLayer),m_selectionLayer=null,m_selectionPlane=null,m_this.map().geoTrigger(geo.event.brushend,selectionObj)),oldAction=m_state.action,m_state={},m_options.momentum.enabled&&"pan"===oldAction&&m_this.springBack(!0)},this._handleMouseUp=function(evt){m_this._getMouseButton(evt),m_this._getMouseModifiers(evt),m_this.map().geoTrigger(geo.event.mouseclick,m_this.mouse())},this._handleMouseWheel=function(evt){var zoomFactor,direction;return evt.deltaFactor=evt.deltaFactor||1,m_this._getMouseModifiers(evt),evt.deltaX=evt.deltaX*m_options.wheelScaleX*evt.deltaFactor/120,evt.deltaY=evt.deltaY*m_options.wheelScaleY*evt.deltaFactor/120,evt.preventDefault(),doRespond()?(evt.deltaX+=m_wheelQueue.x,evt.deltaY+=m_wheelQueue.y,m_wheelQueue={x:0,y:0},void(m_options.panWheelEnabled&&eventMatch("wheel",m_options.panWheelModifiers)?m_this.map().pan({x:evt.deltaX,y:evt.deltaY}):m_options.zoomWheelEnabled&&eventMatch("wheel",m_options.zoomWheelModifiers)&&(zoomFactor=evt.deltaY,direction=m_mouse.map,m_this.map().zoom(m_this.map().zoom()+zoomFactor,direction)))):(m_wheelQueue.x+=evt.deltaX,void(m_wheelQueue.y+=evt.deltaY))},this.springBack=function(initialVelocity){"momentum"!==m_state.action&&(initialVelocity||(m_mouse.velocity={x:0,y:0}),m_state.action="momentum",m_state.origin=m_this.mouse(),m_state.start=new Date,m_state.handler=function(){var v,s,last,dt;if(dt=Math.min(m_mouse.deltaTime,30),"momentum"===m_state.action&&m_this.map()&&!m_this.map().transition()){if(last=m_state.start.valueOf(),m_state.start=new Date,v=modifyVelocity(m_mouse.velocity,m_state.start-last),!v)return void(m_state={});s=calcSpeed(v),s>m_options.momentum.maxSpeed&&(s=m_options.momentum.maxSpeed/s,v.x=v.x*s,v.y=v.y*s),isFinite(v.x)&&isFinite(v.y)||(v.x=0,v.y=0),m_mouse.velocity.x=v.x,m_mouse.velocity.y=v.y,m_this.map().pan({x:m_mouse.velocity.x*dt,y:m_mouse.velocity.y*dt}),m_state.handler&&window.requestAnimationFrame(m_state.handler)}},m_state.handler&&window.requestAnimationFrame(m_state.handler))},this._handleDoubleClick=function(){},this.destroy=function(){m_this._disconnectEvents(),m_this.map(null)},this.mouse=function(){return $.extend(!0,{},m_mouse)},this.keyboard=function(){return $.extend(!0,{},m_keyboard)},this.state=function(){return $.extend(!0,{},m_state)},this.simulateEvent=function(type,options){var evt,page,offset,which;return m_this.map()?(page=options.page||{},options.map&&(offset=$node.offset(),page.x=options.map.x+offset.left,page.y=options.map.y+offset.top),"left"===options.button?which=1:"right"===options.button?which=3:"middle"===options.button&&(which=2),options.modifiers=options.modifiers||[],options.wheelDelta=options.wheelDelta||{},evt=$.Event(type,{pageX:page.x,pageY:page.y,which:which,altKey:options.modifiers.indexOf("alt")>=0,ctrlKey:options.modifiers.indexOf("ctrl")>=0,metaKey:options.modifiers.indexOf("meta")>=0,shiftKey:options.modifiers.indexOf("shift")>=0,deltaX:options.wheelDelta.x,deltaY:options.wheelDelta.y,deltaFactor:1}),void $node.trigger(evt)):m_this},this._connectEvents(),this},inherit(geo.mapInteractor,geo.object),geo.clock=function(opts){"use strict";if(!(this instanceof geo.clock))return new geo.clock(opts);opts=opts||{},geo.object.call(this,opts);var m_this=this,m_now=new Date(0),m_start=null,m_end=null,m_step=null,m_rate=null,m_loop=Number.POSITIVE_INFINITY,m_currentLoop=0,m_state="stop",m_currentAnimation=null,m_object=null;this.object=function(arg){return void 0===arg?m_object:(m_object=arg,m_this)},this._attached=function(){return m_object instanceof geo.object},this.now=function(arg){var previous=m_now;return void 0===arg?m_now:(m_now=arg,m_now!==previous&&m_this._attached()&&m_this.object().geoTrigger(geo.event.clock.change,{previous:previous,current:m_now,clock:m_this}),m_this)},this.start=function(arg){return void 0===arg?m_start:(m_start=arg,m_this)},this.end=function(arg){return void 0===arg?m_end:(m_end=arg,m_this)},this.step=function(arg){return void 0===arg?m_step:(m_step=arg,m_this)},this.loop=function(arg){return void 0===arg?m_loop:(m_loop=arg,m_this)},this.state=function(arg,step){return void 0===arg?m_state:["stop","play","pause"].indexOf(arg)<0?(console.log("WARNING: Ignored invalid state: "+arg),m_this):("play"===arg&&"stop"===m_state&&(m_currentLoop=0,m_this.now(m_this.start())),"play"===arg&&"play"!==m_state&&(m_state=arg,m_this._animate(step||1)),m_state=arg,m_this)},this.framerate=function(arg){return void 0===arg?m_rate:(m_rate=arg,m_this)},this.stepForward=function(){return m_this.state("pause"),m_this._setNextFrame(1),m_this},this.stepBackward=function(){return m_this.state("pause"),m_this._setNextFrame(-1),m_this},this._setNextFrame=function(step){var next=new Date(m_this.now().valueOf()+step*m_this.step());return next>=m_this.end()||next<=m_this.start()?m_this.loop()<=m_currentLoop?void m_this.state("stop"):(m_currentLoop+=1,void m_this.now(step>=0?m_this.start():m_this.end())):void m_this.now(next)},this._animate=function(step){function frame(){myAnimation===m_currentAnimation&&(m_this._setNextFrame(step),"play"===m_this.state()?m_this.framerate()?window.setTimeout(frame,1e3/m_this.framerate()):window.requestAnimationFrame(frame):m_this._attached()&&m_this.object().geoTrigger(geo.event.clock[m_this.state()],{current:m_this.now(),clock:m_this}))}var myAnimation={};m_currentAnimation=myAnimation,m_this._attached()&&m_this.object().geoTrigger(geo.event.clock.play,{current:m_this.now(),clock:m_this}),m_this.framerate()?window.setTimeout(frame,1e3/m_this.framerate()):window.requestAnimationFrame(frame)}},inherit(geo.clock,geo.object),geo.fileReader=function(arg){"use strict";function newFileReader(done,progress){var reader=new FileReader;return progress&&(reader.onprogress=progress),reader.onloadend=function(){reader.result||done(reader.error),done(reader.result)},reader}if(!(this instanceof geo.fileReader))return new geo.fileReader(arg);if(geo.object.call(this),arg=arg||{},!(arg.layer instanceof geo.featureLayer))throw"fileReader must be given a feature layer";var m_layer=arg.layer;return this.layer=function(){return m_layer},this.canRead=function(){return!1},this.read=function(file,done){done(!1)},this._getString=function(file,done,progress){var reader=newFileReader(done,progress);reader.readAsText(file)},this._getArrayBuffer=function(file,done,progress){var reader=newFileReader(done,progress);reader.readAsText(file)},this},inherit(geo.fileReader,geo.object),geo.jsonReader=function(arg){"use strict";if(!(this instanceof geo.jsonReader))return new geo.jsonReader(arg);var m_this=this,m_style=arg.style||{};m_style=$.extend({strokeWidth:2,strokeColor:{r:0,g:0,b:0},strokeOpacity:1,fillColor:{r:1,g:0,b:0},fillOpacity:1},m_style),geo.fileReader.call(this,arg),this.canRead=function(file){if(file instanceof File)return"application/json"===file.type||file.name.match(/\.json$/);if("string"==typeof file){try{JSON.parse(file)}catch(e){return!1}return!0}try{if(Array.isArray(m_this._featureArray(file)))return!0}catch(e){}return!1},this._readObject=function(file,done,progress){function onDone(fileString){"string"!=typeof fileString&&done(!1);try{object=JSON.parse(fileString),done(object)}catch(e){object||$.ajax({type:"GET",url:fileString,dataType:"text"}).done(function(data){object=JSON.parse(data),done(object)}).fail(function(){done(!1)})}}var object;file instanceof File?m_this._getString(file,onDone,progress):"string"==typeof file?onDone(file):done(file)},this._featureArray=function(spec){if("FeatureCollection"===spec.type)return spec.features||[];if("GeometryCollection"===spec.type)throw"GeometryCollection not yet implemented.";if(Array.isArray(spec.coordinates))return spec;throw"Unsupported collection type: "+spec.type},this._featureType=function(spec){var geometry=spec.geometry||{};return"Point"===geometry.type||"MultiPoint"===geometry.type?"point":"LineString"===geometry.type?"line":"Polygon"===geometry.type?"polygon":null},this._getCoordinates=function(spec){var elv,geometry=spec.geometry||{},coordinates=geometry.coordinates||[];return(2===coordinates.length||3===coordinates.length)&&isFinite(coordinates[0])&&isFinite(coordinates[1])?(isFinite(coordinates[2])&&(elv=coordinates[2]),[{x:coordinates[0],y:coordinates[1],z:elv}]):(Array.isArray(coordinates[0][0])&&(coordinates=coordinates[0]),coordinates.map(function(c){return{x:c[0],y:c[1],z:c[2]}}))},this._getStyle=function(spec){return spec.properties},this.read=function(file,done,progress){function _done(object){var features,allFeatures=[];features=m_this._featureArray(object),features.forEach(function(feature){var type=m_this._featureType(feature),coordinates=m_this._getCoordinates(feature),style=m_this._getStyle(feature);type?"line"===type?(style.fill=style.fill||!1,allFeatures.push(m_this._addFeature(type,[coordinates],style,feature.properties))):"point"===type?(style.stroke=style.stroke||!1,allFeatures.push(m_this._addFeature(type,coordinates,style,feature.properties))):"polygon"===type&&(style.fill=void 0===style.fill?!0:style.fill,style.fillOpacity=void 0===style.fillOpacity?.25:style.fillOpacity,allFeatures.push(m_this._addFeature("line",[coordinates],style,feature.properties))):console.log("unsupported feature type: "+feature.geometry.type)}),done&&done(allFeatures)}m_this._readObject(file,_done,progress)},this._buildData=function(coordinates,properties,style){return coordinates.map(function(coord){return{coordinates:coord,properties:properties,style:style}})},this._addFeature=function(type,coordinates,style,properties){var _style=$.extend({},m_style,style),feature=m_this.layer().createFeature(type).data(m_this._buildData(coordinates,properties,style)).style(_style);return"line"===type?feature.line(function(d){return d.coordinates}):feature.position(function(d){return d.coordinates}),feature}},inherit(geo.jsonReader,geo.fileReader),geo.registerFileReader("jsonReader",geo.jsonReader),geo.map=function(arg){"use strict";function resizeSelf(){m_this.resize(0,0,m_node.width(),m_node.height())}if(!(this instanceof geo.map))return new geo.map(arg);arg=arg||{},geo.sceneObject.call(this,arg),arg.layers=void 0===arg.layers?[]:arg.layers;var m_this=this,s_exit=this._exit,m_x=0,m_y=0,m_node=$(arg.node),m_width=arg.width||m_node.width(),m_height=arg.height||m_node.height(),m_gcs=void 0===arg.gcs?"EPSG:4326":arg.gcs,m_uigcs=void 0===arg.uigcs?"EPSG:4326":arg.uigcs,m_center={x:0,y:0},m_zoom=void 0===arg.zoom?1:arg.zoom,m_baseLayer=null,m_fileReader=null,m_interactor=null,m_validZoomRange={min:0,max:16},m_transition=null,m_queuedTransition=null,m_clock=null,m_bounds={};return arg.center=geo.util.normalizeCoordinates(arg.center),arg.autoResize=void 0===arg.autoResize?!0:arg.autoResize,arg.clampBounds=void 0===arg.clampBounds?!0:arg.clampBounds,this.gcs=function(arg){return void 0===arg?m_gcs:(m_gcs=arg,m_this)},this.uigcs=function(){return m_uigcs},this.node=function(){return m_node},this.zoom=function(val,direction){var base,evt,recenter=!1;return void 0===val?m_zoom:(val=Math.min(m_validZoomRange.max,Math.max(val,m_validZoomRange.min)),val===m_zoom?m_this:(base=m_this.baseLayer(),evt={geo:{},zoomLevel:val,screenPosition:direction,eventType:geo.event.zoom},base&&base.renderer().geoTrigger(geo.event.zoom,evt,!0),recenter=evt.center,evt.geo.preventDefault||(m_zoom=val,m_this._updateBounds(),m_this.children().forEach(function(child){child.geoTrigger(geo.event.zoom,evt,!0)}),m_this.modified()),evt.center?m_this.center(recenter):m_this.pan({x:0,y:0}),m_this))},this.pan=function(delta,force){var evt,pt,corner1,corner2,base=m_this.baseLayer();return arg.clampBounds&&!force&&m_width&&m_height&&(pt=m_this.displayToGcs({x:delta.x,y:delta.y}),corner1=m_this.gcsToDisplay({x:-180,y:82}),corner2=m_this.gcsToDisplay({x:180,y:-82}),delta.x=corner1.x>0&&corner2.x0&&corner2.y0||input instanceof Object))throw"Conversion method latLonToDisplay does not handle "+input;return world=m_baseLayer.toLocal(input),output=m_baseLayer.renderer().worldToDisplay(world)},this.displayToGcs=function(input){var output;if(!(input instanceof Array&&input.length>0||input instanceof Object))throw"Conversion method displayToGcs does not handle "+input;return output=m_baseLayer.renderer().displayToWorld(input),output=m_baseLayer.fromLocal(output)},this.query=function(){},this.baseLayer=function(baseLayer){var save;return void 0!==baseLayer?(m_gcs!==baseLayer.gcs()&&m_this.gcs(baseLayer.gcs()),m_baseLayer=baseLayer,m_baseLayer.referenceLayer(!0),arg.center&&m_this.center(arg.center,!0),save=m_zoom,m_zoom=null,m_this.zoom(save),m_this._updateBounds(),m_this.pan({x:0,y:0}),m_this):m_baseLayer},this.draw=function(){var i,layers=m_this.children();for(m_this.geoTrigger(geo.event.draw,{type:geo.event.draw,target:m_this}),m_this._update(),i=0;i=m_transition.end.time||next)return next||(m_this.center(m_transition.end.center),m_this.zoom(m_transition.end.zoom)),m_transition=null,m_this.geoTrigger(geo.event.transitionend,defaultOpts),done&&done(),void(next&&(m_queuedTransition=null,m_this.transition(next)));var z=m_transition.ease((time-m_transition.start.time)/defaultOpts.duration),p=m_transition.interp(z);m_transition.zCoord&&(p[2]=z2zoom(p[2])),m_this.center({x:p[0],y:p[1]}),m_this.zoom(p[2]),window.requestAnimationFrame(anim)}if(void 0===opts)return m_transition;if(m_transition)return m_queuedTransition=opts,m_this;var defaultOpts={center:m_this.center(),zoom:m_this.zoom(),duration:1e3,ease:function(t){return t},interp:defaultInterp,done:null,zCoord:!0};return opts.center&&(opts.center=geo.util.normalizeCoordinates(opts.center)),$.extend(defaultOpts,opts),m_transition={start:{center:m_this.center(),zoom:m_this.zoom()},end:{center:defaultOpts.center,zoom:defaultOpts.zoom},ease:defaultOpts.ease,zCoord:defaultOpts.zCoord,done:defaultOpts.done,duration:defaultOpts.duration},m_transition.interp=defaultOpts.zCoord?defaultOpts.interp([m_transition.start.center.x,m_transition.start.center.y,zoom2z(m_transition.start.zoom)],[m_transition.end.center.x,m_transition.end.center.y,zoom2z(m_transition.end.zoom)]):defaultOpts.interp([m_transition.start.center.x,m_transition.start.center.y,m_transition.start.zoom],[m_transition.end.center.x,m_transition.end.center.y,m_transition.end.zoom]),m_this.geoTrigger(geo.event.transitionstart,defaultOpts),defaultOpts.cancelNavigation?(m_this.geoTrigger(geo.event.transitionend,defaultOpts),m_this):(defaultOpts.cancelAnimation?(defaultOpts.duration=0,anim(0)):window.requestAnimationFrame(anim),m_this)},this._updateBounds=function(){m_bounds.lowerLeft=m_this.displayToGcs({x:0,y:m_height}),m_bounds.lowerRight=m_this.displayToGcs({x:m_width,y:m_height}),m_bounds.upperLeft=m_this.displayToGcs({x:0,y:0}),m_bounds.upperRight=m_this.displayToGcs({x:m_width,y:0})},this.bounds=function(){return m_bounds},this.interactor(arg.interactor||geo.mapInteractor()),this.clock(arg.clock||geo.clock()),arg.autoResize&&$(window).resize(resizeSelf),this},geo.map.create=function(spec){"use strict";var map=geo.map(spec);return map?(spec.data=spec.data||[],spec.layers=spec.layers||[],spec.layers.forEach(function(l){l.data=l.data||spec.data,l.layer=geo.layer.create(map,l)}),map):(console.warn("Could not create map."),null)},inherit(geo.map,geo.sceneObject),geo.feature=function(arg){"use strict";if(!(this instanceof geo.feature))return new geo.feature(arg);geo.sceneObject.call(this),arg=arg||{};var m_this=this,s_exit=this._exit,m_selectionAPI=void 0===arg.selectionAPI?!1:arg.selectionAPI,m_style={},m_layer=void 0===arg.layer?null:arg.layer,m_gcs=void 0===arg.gcs?"EPSG:4326":arg.gcs,m_visible=void 0===arg.visible?!0:arg.visible,m_bin=void 0===arg.bin?0:arg.bin,m_renderer=void 0===arg.renderer?null:arg.renderer,m_dataTime=geo.timestamp(),m_buildTime=geo.timestamp(),m_updateTime=geo.timestamp(),m_selectedFeatures=[];return this._bindMouseHandlers=function(){m_selectionAPI&&(m_this._unbindMouseHandlers(),m_this.geoOn(geo.event.mousemove,m_this._handleMousemove),m_this.geoOn(geo.event.mouseclick,m_this._handleMouseclick),m_this.geoOn(geo.event.brushend,m_this._handleBrushend),m_this.geoOn(geo.event.brush,m_this._handleBrush))},this._unbindMouseHandlers=function(){m_this.geoOff(geo.event.mousemove,m_this._handleMousemove),m_this.geoOff(geo.event.mouseclick,m_this._handleMouseclick),m_this.geoOff(geo.event.brushend,m_this._handleBrushend),m_this.geoOff(geo.event.brush,m_this._handleBrush)},this.pointSearch=function(){return{index:[],found:[]}},this._handleMousemove=function(){var mouse=m_this.layer().map().interactor().mouse(),data=m_this.data(),over=m_this.pointSearch(mouse.geo),newFeatures=[],oldFeatures=[],lastTop=-1,top=-1;m_selectedFeatures.length&&(lastTop=m_selectedFeatures[m_selectedFeatures.length-1]),newFeatures=over.index.filter(function(i){return m_selectedFeatures.indexOf(i)<0}),oldFeatures=m_selectedFeatures.filter(function(i){return over.index.indexOf(i)<0}),geo.feature.eventID+=1,newFeatures.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.mouseover,{data:data[i],index:i,mouse:mouse,eventID:geo.feature.eventID,top:idx===newFeatures.length-1},!0)}),geo.feature.eventID+=1,oldFeatures.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.mouseout,{
-data:data[i],index:i,mouse:mouse,eventID:geo.feature.eventID,top:idx===oldFeatures.length-1},!0)}),geo.feature.eventID+=1,over.index.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.mousemove,{data:data[i],index:i,mouse:mouse,eventID:geo.feature.eventID,top:idx===over.index.length-1},!0)}),m_selectedFeatures=over.index,m_selectedFeatures.length&&(top=m_selectedFeatures[m_selectedFeatures.length-1]),lastTop!==top&&(-1!==lastTop&&m_this.geoTrigger(geo.event.feature.mouseoff,{data:data[lastTop],index:lastTop,mouse:mouse},!0),-1!==top&&m_this.geoTrigger(geo.event.feature.mouseon,{data:data[top],index:top,mouse:mouse},!0))},this._handleMouseclick=function(){var mouse=m_this.layer().map().interactor().mouse(),data=m_this.data(),over=m_this.pointSearch(mouse.geo);geo.feature.eventID+=1,over.index.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.mouseclick,{data:data[i],index:i,mouse:mouse,eventID:geo.feature.eventID,top:idx===over.index.length-1},!0)})},this._handleBrush=function(brush){var idx=m_this.boxSearch(brush.gcs.lowerLeft,brush.gcs.upperRight),data=m_this.data();geo.feature.eventID+=1,idx.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.brush,{data:data[i],index:i,mouse:brush.mouse,brush:brush,eventID:geo.feature.eventID,top:idx===idx.length-1},!0)})},this._handleBrushend=function(brush){var idx=m_this.boxSearch(brush.gcs.lowerLeft,brush.gcs.upperRight),data=m_this.data();geo.feature.eventID+=1,idx.forEach(function(i,idx){m_this.geoTrigger(geo.event.feature.brushend,{data:data[i],index:i,mouse:brush.mouse,brush:brush,eventID:geo.feature.eventID,top:idx===idx.length-1},!0)})},this.style=function(arg1,arg2){return void 0===arg1?m_style:"string"==typeof arg1&&void 0===arg2?m_style[arg1]:void 0===arg2?(m_style=$.extend({},m_style,arg1),m_this.modified(),m_this):(m_style[arg1]=arg2,m_this.modified(),m_this)},this.style.get=function(key){var tmp,out;if(void 0===key){var k,all={};for(k in m_style)m_style.hasOwnProperty(k)&&(all[k]=m_this.style.get(k));return all}return key.toLowerCase().match(/color$/)?geo.util.isFunction(m_style[key])?(tmp=geo.util.ensureFunction(m_style[key]),out=function(){return geo.util.convertColor(tmp.apply(this,arguments))}):out=geo.util.ensureFunction(geo.util.convertColor(m_style[key])):out=geo.util.ensureFunction(m_style[key]),out},this.layer=function(){return m_layer},this.renderer=function(){return m_renderer},this.drawables=function(){return m_this._drawables()},this.gcs=function(val){return void 0===val?m_gcs:(m_gcs=val,m_this.modified(),m_this)},this.visible=function(val){return void 0===val?m_visible:(m_visible=val,m_this.modified(),m_this)},this.bin=function(val){return void 0===val?m_bin:(m_bin=val,m_this.modified(),m_this)},this.dataTime=function(val){return void 0===val?m_dataTime:(m_dataTime=val,m_this.modified(),m_this)},this.buildTime=function(val){return void 0===val?m_buildTime:(m_buildTime=val,m_this.modified(),m_this)},this.updateTime=function(val){return void 0===val?m_updateTime:(m_updateTime=val,m_this.modified(),m_this)},this.data=function(data){return void 0===data?m_this.style("data")||[]:(m_this.style("data",data),m_this.dataTime().modified(),m_this.modified(),m_this)},this.selectionAPI=function(){return m_selectionAPI},this._init=function(arg){if(!m_layer)throw"Feature requires a valid layer";m_style=$.extend({},{opacity:1},void 0===arg.style?{}:arg.style),m_this._bindMouseHandlers()},this._build=function(){},this._drawables=function(){},this._update=function(){},this._exit=function(){m_this._unbindMouseHandlers(),m_selectedFeatures=[],m_style={},arg={},s_exit()},this._init(arg),this},geo.feature.eventID=0,geo.feature.create=function(layer,spec){"use strict";var type=spec.type;if(!layer instanceof geo.layer)return console.warn("Invalid layer"),null;if("object"!=typeof spec)return console.warn("Invalid spec"),null;var feature=layer.createFeature(type);return feature?(spec=spec||{},spec.data=spec.data||[],feature.style(spec)):(console.warn("Could not create feature type '"+type+"'"),null)},inherit(geo.feature,geo.sceneObject),geo.pointFeature=function(arg){"use strict";if(!(this instanceof geo.pointFeature))return new geo.pointFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,s_init=this._init,m_rangeTree=null,s_data=this.data,s_style=this.style,m_maxRadius=0;return this.position=function(val){return void 0===val?m_this.style("position"):(m_this.style("position",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this._updateRangeTree=function(){var pts,position,radius=m_this.style.get("radius"),stroke=m_this.style.get("stroke"),strokeWidth=m_this.style.get("strokeWidth");position=m_this.position(),m_maxRadius=0,pts=m_this.data().map(function(d,i){var pt=position(d);return pt.idx=i,m_maxRadius=Math.max(m_maxRadius,radius(d,i)+(stroke(d,i)?strokeWidth(d,i):0)),pt}),m_rangeTree=new geo.util.RangeTree(pts)},this.pointSearch=function(p){var min,max,data,box,map,pt,idx=[],found=[],ifound=[],stroke=m_this.style.get("stroke"),strokeWidth=m_this.style.get("strokeWidth"),radius=m_this.style.get("radius");return m_this.selectionAPI()?(data=m_this.data(),data&&data.length?(map=m_this.layer().map(),pt=map.gcsToDisplay(p),min=map.displayToGcs({x:pt.x-m_maxRadius,y:pt.y+m_maxRadius}),max=map.displayToGcs({x:pt.x+m_maxRadius,y:pt.y-m_maxRadius}),box=new geo.util.Box(geo.util.vect(min.x,min.y),geo.util.vect(max.x,max.y)),m_rangeTree.search(box).forEach(function(q){idx.push(q.idx)}),idx.forEach(function(i){var dx,dy,rad,d=data[i],p=m_this.position()(d,i);rad=radius(data[i],i),rad+=stroke(data[i],i)?strokeWidth(data[i],i):0,p=map.gcsToDisplay(p),dx=p.x-pt.x,dy=p.y-pt.y,Math.sqrt(dx*dx+dy*dy)<=rad&&(found.push(d),ifound.push(i))}),{data:found,index:ifound}):{found:[],index:[]}):[]},this.boxSearch=function(lowerLeft,upperRight){var pos=m_this.position(),idx=[];return m_this.data().forEach(function(d,i){var p=pos(d);p.x>=lowerLeft.x&&p.x<=upperRight.x&&p.y>=lowerLeft.y&&p.y<=upperRight.y&&idx.push(i)}),idx},this.data=function(data){return void 0===data?s_data():(s_data(data),m_this)},this.style=function(arg1,arg2){var val=s_style(arg1,arg2);return val===m_this&&m_this.selectionAPI()&&m_this._updateRangeTree(),val},this.style.get=s_style.get,this._boundingBox=function(d){var pt,radius;return pt=m_this.position()(d),pt=m_this.layer().map().gcsToDisplay(pt),radius=m_this.style().radius(d),{min:{x:pt.x-radius,y:pt.y-radius},max:{x:pt.x+radius,y:pt.y+radius}}},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{radius:10,stroke:!0,strokeColor:{r:0,g:1,b:0},strokeWidth:2,strokeOpacity:1,fillColor:{r:1,g:0,b:0},fill:!0,fillOpacity:1,sprites:!1,sprites_image:null,position:function(d){return d}},void 0===arg.style?{}:arg.style);void 0!==arg.position&&(defaultStyle.position=arg.position),m_this.style(defaultStyle),m_this.dataTime().modified()},m_this},geo.event.pointFeature=$.extend({},geo.event.feature),geo.pointFeature.create=function(layer,renderer,spec){"use strict";return spec.type="point",geo.feature.create(layer,spec)},inherit(geo.pointFeature,geo.feature),geo.lineFeature=function(arg){"use strict";if(!(this instanceof geo.lineFeature))return new geo.lineFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,s_init=this._init;return this.line=function(val){return void 0===val?m_this.style("line"):(m_this.style("line",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this.position=function(val){return void 0===val?m_this.style("position"):(m_this.style("position",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this.pointSearch=function(p){function lineDist2(q,u,v){var t,l2=dist2(u,v);return 1>l2?dist2(q,u):(t=((q.x-u.x)*(v.x-u.x)+(q.y-u.y)*(v.y-u.y))/l2,0>t?dist2(q,u):t>1?dist2(q,v):dist2(q,{x:u.x+t*(v.x-u.x),y:u.y+t*(v.y-u.y)}))}function dist2(u,v){var dx=u.x-v.x,dy=u.y-v.y;return dx*dx+dy*dy}var data,pt,map,line,width,pos,indices=[],found=[];return data=m_this.data(),data&&data.length?(map=m_this.layer().map(),line=m_this.line(),width=m_this.style.get("strokeWidth"),pos=m_this.position(),pt=map.gcsToDisplay(p),data.forEach(function(d,index){var last=null;try{line(d,index).forEach(function(current,j){var p=pos(current,j,d,index),s=map.gcsToDisplay(p),r=Math.ceil(width(p,j,d,index)/2)+2;if(r*=r,last&&lineDist2(pt,s,last)<=r)throw"found";last=s})}catch(err){if("found"!==err)throw err;found.push(d),indices.push(index)}}),{data:found,index:indices}):{found:[],index:[]}},this.boxSearch=function(lowerLeft,upperRight,opts){var pos=m_this.position(),idx=[],line=m_this.line();if(opts=opts||{},opts.partial=opts.partial||!1,opts.partial)throw"Unimplemented query method.";return m_this.data().forEach(function(d,i){var inside=!0;line(d,i).forEach(function(e,j){if(inside){var p=pos(e,j,d,i);p.x>=lowerLeft.x&&p.x<=upperRight.x&&p.y>=lowerLeft.y&&p.y<=upperRight.y||(inside=!1)}}),inside&&idx.push(i)}),idx},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{strokeWidth:1,strokeColor:{r:1,g:.8431372549,b:0},strokeStyle:"solid",strokeOpacity:1,line:function(d){return d},position:function(d){return d}},void 0===arg.style?{}:arg.style);void 0!==arg.line&&(defaultStyle.line=arg.line),void 0!==arg.position&&(defaultStyle.position=arg.position),m_this.style(defaultStyle),m_this.dataTime().modified()},this._init(arg),this},geo.lineFeature.create=function(layer,spec){"use strict";return spec.type="line",geo.feature.create(layer,spec)},inherit(geo.lineFeature,geo.feature),geo.pathFeature=function(arg){"use strict";if(!(this instanceof geo.pathFeature))return new geo.pathFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,m_position=void 0===arg.position?[]:arg.position,s_init=this._init;return this.position=function(val){return void 0===val?m_position:(m_position=val,m_this.dataTime().modified(),m_this.modified(),m_this)},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{strokeWidth:function(){return 1},strokeColor:function(){return{r:1,g:1,b:1}}},void 0===arg.style?{}:arg.style);m_this.style(defaultStyle),m_position&&m_this.dataTime().modified()},this._init(arg),this},inherit(geo.pathFeature,geo.feature),geo.polygonFeature=function(arg){"use strict";function getCoordinates(){var posFunc=m_this.position(),polyFunc=m_this.polygon();m_coordinates=m_this.data().map(function(d,i){var outer,inner,poly=polyFunc(d);return outer=(poly.outer||[]).map(function(d0,j){return posFunc.call(m_this,d0,j,d,i)}),inner=(poly.inner||[]).map(function(hole){return(hole||[]).map(function(d0,k){return posFunc.call(m_this,d0,k,d,i)})}),{outer:outer,inner:inner}})}if(!(this instanceof geo.polygonFeature))return new geo.polygonFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_position,m_polygon,m_this=this,s_init=this._init,s_data=this.data,m_coordinates={outer:[],inner:[]};return m_polygon=void 0===arg.line?function(d){return d}:arg.polygon,m_position=void 0===arg.position?function(d){return d}:arg.position,this.data=function(arg){var ret=s_data(arg);return void 0!==arg&&getCoordinates(),ret},this.polygon=function(val){return void 0===val?m_polygon:(m_polygon=val,m_this.dataTime().modified(),m_this.modified(),getCoordinates(),m_this)},this.position=function(val){return void 0===val?m_position:(m_position=val,m_this.dataTime().modified(),m_this.modified(),getCoordinates(),m_this)},this.pointSearch=function(coordinate){var found=[],indices=[],data=m_this.data();return m_coordinates.forEach(function(coord,i){var inside=geo.util.pointInPolygon(coordinate,coord.outer,coord.inner);inside&&(indices.push(i),found.push(data[i]))}),{index:indices,found:found}},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{fillColor:{r:0,g:.5,b:.5},fillOpacity:1},void 0===arg.style?{}:arg.style);m_this.style(defaultStyle),m_position&&m_this.dataTime().modified()},this._init(arg),this},inherit(geo.polygonFeature,geo.feature),geo.planeFeature=function(arg){"use strict";if(!(this instanceof geo.planeFeature))return new geo.planeFeature(arg);arg=arg||{},arg.ul=void 0===arg.ul?[0,1,0]:arg.ul,arg.lr=void 0===arg.lr?[1,0,0]:arg.lr,arg.depth=void 0===arg.depth?0:arg.depth,geo.polygonFeature.call(this,arg);var m_this=this,m_origin=[arg.ul.x,arg.lr.y,arg.depth],m_upperLeft=[arg.ul.x,arg.ul.y,arg.depth],m_lowerRight=[arg.lr.x,arg.lr.y,arg.depth],m_defaultDepth=arg.depth,m_drawOnAsyncResourceLoad=void 0===arg.drawOnAsyncResourceLoad?!0:!1,s_init=this._init;return this.origin=function(val){if(void 0===val)return m_origin;if(val instanceof Array){if(val.length>3||val.length<2)throw"Upper left point requires point in 2 or 3 dimension";m_origin=val.slice(0),2===m_origin.length&&(m_origin[2]=m_defaultDepth)}else val instanceof geo.latlng&&(m_origin=[val.x(),val.y(),m_defaultDepth]);return m_this.dataTime().modified(),m_this.modified(),m_this},this.upperLeft=function(val){if(void 0===val)return m_upperLeft;if(val instanceof Array){if(val.length>3||val.length<2)throw"Upper left point requires point in 2 or 3 dimension";m_upperLeft=val.slice(0),2===m_upperLeft.length&&(m_upperLeft[2]=m_defaultDepth)}else val instanceof geo.latlng&&(m_upperLeft=[val.x(),val.y(),m_defaultDepth]);return m_this.dataTime().modified(),m_this.modified(),m_this},this.lowerRight=function(val){if(void 0===val)return m_lowerRight;if(val instanceof Array){if(val.length>3||val.length<2)throw"Upper left point requires point in 2 or 3 dimension";m_lowerRight=val.slice(0),2===m_lowerRight.length&&(m_lowerRight[2]=m_defaultDepth),m_this.dataTime().modified()}else val instanceof geo.latlng&&(m_lowerRight=[val.x(),val.y(),m_defaultDepth]);return m_this.dataTime().modified(),m_this.modified(),m_this},this.drawOnAsyncResourceLoad=function(val){return void 0===val?m_drawOnAsyncResourceLoad:(m_drawOnAsyncResourceLoad=val,m_this)},this._init=function(arg){var style=null;s_init.call(m_this,arg),style=m_this.style(),void 0===style.image&&(style.image=null),m_this.style(style)},this._init(arg),this},inherit(geo.planeFeature,geo.polygonFeature),geo.vectorFeature=function(arg){"use strict";if(!(this instanceof geo.vectorFeature))return new geo.vectorFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,s_init=this._init,s_style=this.style;this.origin=function(val){return void 0===val?s_style("origin"):(s_style("origin",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this.delta=function(val){return void 0===val?s_style("delta"):(s_style("delta",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{strokeColor:"black",strokeWidth:2,strokeOpacity:1,origin:{x:0,y:0,z:0},delta:function(d){return d},scale:null},void 0===arg.style?{}:arg.style);void 0!==arg.origin&&(defaultStyle.origin=arg.origin),m_this.style(defaultStyle),m_this.dataTime().modified()}},inherit(geo.vectorFeature,geo.feature),geo.geomFeature=function(arg){"use strict";return this instanceof geo.geomFeature?(arg=arg||{},geo.feature.call(this,arg),arg.style=void 0===arg.style?$.extend({},{color:[1,1,1],point_sprites:!1,point_sprites_image:null},arg.style):arg.style,this.style(arg.style),this):new geo.geomFeature(arg)},inherit(geo.geomFeature,geo.feature),geo.graphFeature=function(arg){"use strict";if(!(this instanceof geo.graphFeature))return new geo.graphFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,s_draw=this.draw,s_style=this.style,m_nodes=null,m_points=null,m_children=function(d){return d.children},m_links=[],s_init=this._init,s_exit=this._exit;return this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend(!0,{},{nodes:{radius:5,fill:!0,fillColor:{r:1,g:0,b:0},strokeColor:{r:0,g:0,b:0}},links:{strokeColor:{r:0,g:0,b:0}},linkType:"path"},void 0===arg.style?{}:arg.style);m_this.style(defaultStyle),m_this.nodes(function(d){return d})},this._build=function(){m_this.children().forEach(function(child){child._build()})},this._update=function(){m_this.children().forEach(function(child){child._update()})},this._exit=function(){return m_this.data([]),m_links.forEach(function(link){link._exit(),m_this.removeChild(link)}),m_links=[],m_points._exit(),m_this.removeChild(m_points),s_exit(),m_this},this.style=function(arg,arg2){var out=s_style.call(m_this,arg,arg2);return out!==m_this?out:(m_points.style(arg.nodes),m_links.forEach(function(l){l.style(arg.links)}),m_this)},this.links=function(arg){return void 0===arg?m_children:(m_children=geo.util.ensureFunction(arg),m_this)},this.nodes=function(val){return void 0===val?m_nodes:(m_nodes=val,m_this.modified(),m_this)},this.nodeFeature=function(){return m_points},this.linkFeatures=function(){return m_links},this.draw=function(){var style,layer=m_this.layer(),data=m_this.data(),nLinks=0;return style=m_this.style(),m_points.data(data),m_points.style(style.nodes),data.forEach(function(source){(source.children||[]).forEach(function(target){var link;nLinks+=1,m_links.length0&&inPos[0]instanceof geo.latlng?(noOfComponents=2,pointOffset=1):(noOfComponents=count%2===0?2:count%3===0?3:null,pointOffset=noOfComponents),2!==noOfComponents&&3!==noOfComponents)throw"Transform points require points in 2D or 3D";for(outPos=inplace?inPos:inPos.slice(0),i=0;count>i;i+=pointOffset)yCoord=inPos[i]instanceof geo.latlng?inPos[i].lat():inPos[i+1],yCoord>85.0511&&(yCoord=85.0511),-85.0511>yCoord&&(yCoord=-85.0511),inPos[i]instanceof geo.latlng?outPos[i]=geo.latlng(geo.mercator.lat2y(yCoord),outPos[i].lng()):outPos[i+1]=geo.mercator.lat2y(yCoord);return inplace&&(feature.positions(outPos),feature.gcs(destGcs)),outPos}return null}},geo.transform.transformFeature=function(destGcs,feature,inplace){"use strict";if(!feature)throw"Invalid (null) feature";if(!(feature instanceof geo.pointFeature||feature instanceof geo.lineFeature))throw"Supports only point or line feature";if(feature.gcs()===destGcs)return feature.positions();if("EPSG:3857"===destGcs)return geo.transform.osmTransformFeature(destGcs,feature,inplace);var i,noOfComponents=null,pointOffset=0,count=null,inPos=null,outPos=null,projPoint=null,srcGcs=feature.gcs(),projSrcGcs=new proj4.Proj(srcGcs),projDestGcs=new proj4.Proj(destGcs);if(inplace=!!inplace,feature instanceof geo.pointFeature||feature instanceof geo.lineFeature){if(inPos=feature.positions(),count=inPos.length,!(inPos instanceof Array))throw"Supports Array of 2D and 3D points";if(inPos.length>0&&inPos[0]instanceof geo.latlng?(noOfComponents=2,pointOffset=1):(noOfComponents=count%2===0?2:count%3===0?3:null,pointOffset=noOfComponents),2!==noOfComponents&&3!==noOfComponents)throw"Transform points require points in 2D or 3D";for(inplace?outPos=inPos:(outPos=[],outPos.length=inPos.length),i=0;count>i;i+=pointOffset)projPoint=2===noOfComponents?new proj4.Point(inPos[i],inPos[i+1],0):new proj4.Point(inPos[i],inPos[i+1],inPos[i+2]),proj4.transform(projSrcGcs,projDestGcs,projPoint),2===noOfComponents?(outPos[i]=projPoint.x,outPos[i+1]=projPoint.y):(outPos[i]=projPoint.x,outPos[i+1]=projPoint.y,outPos[i+2]=projPoint.z);return inplace&&(feature.positions(outPos),feature.gcs(destGcs)),outPos}return null},geo.transform.transformLayer=function(destGcs,layer,baseLayer){"use strict";var features,count,i;if(!layer)throw"Requires valid layer for tranformation";if(!baseLayer)throw"Requires baseLayer used by the map";if(layer!==baseLayer){if(!(layer instanceof geo.featureLayer))throw"Only feature layer transformation is supported";for(features=layer.features(),count=features.length,i=0,i=0;count>i;i+=1)"EPSG:3857"===destGcs&&baseLayer instanceof geo.osmLayer?geo.transform.osmTransformFeature(destGcs,features[i],!0):geo.transform.transformFeature(destGcs,features[i],!0);layer.gcs(destGcs)}},geo.transform.transformCoordinates=function(srcGcs,destGcs,coordinates,numberOfComponents){"use strict";function handleLatLngCoordinates(){coordinates[0]&&coordinates[0]instanceof geo.latlng?(xAcc=function(index){return coordinates[index].x()},yAcc=function(index){return coordinates[index].y()},writer=function(index,x,y){output[index]=geo.latlng(y,x)}):(xAcc=function(){return coordinates.x()},yAcc=function(){return coordinates.y()},writer=function(index,x,y){output=geo.latlng(y,x)})}function handleArrayCoordinates(){if(coordinates[0]instanceof Array)if(2===coordinates[0].length)xAcc=function(index){return coordinates[index][0]},yAcc=function(index){return coordinates[index][1]},writer=function(index,x,y){output[index]=[x,y]};else{if(3!==coordinates[0].length)throw"Invalid coordinates. Requires two or three components per array";xAcc=function(index){return coordinates[index][0]},yAcc=function(index){return coordinates[index][1]},zAcc=function(index){return coordinates[index][2]},writer=function(index,x,y,z){output[index]=[x,y,z]}}else if(2===coordinates.length)offset=2,xAcc=function(index){return coordinates[index*offset]},yAcc=function(index){return coordinates[index*offset+1]},writer=function(index,x,y){output[index]=x,output[index+1]=y};else if(3===coordinates.length)offset=3,xAcc=function(index){return coordinates[index*offset]},yAcc=function(index){return coordinates[index*offset+1]},zAcc=function(index){return coordinates[index*offset+2]},writer=function(index,x,y,z){output[index]=x,output[index+1]=y,output[index+2]=z};else{if(!numberOfComponents)throw"Invalid coordinates";offset=numberOfComponents,xAcc=function(index){return coordinates[index]},yAcc=function(index){return coordinates[index+1]},2===numberOfComponents?writer=function(index,x,y){output[index]=x,output[index+1]=y}:(zAcc=function(index){return coordinates[index+2]},writer=function(index,x,y,z){output[index]=x,output[index+1]=y,output[index+2]=z})}}function handleObjectCoordinates(){if(coordinates[0]&&"x"in coordinates[0]&&"y"in coordinates[0])xAcc=function(index){return coordinates[index].x},yAcc=function(index){return coordinates[index].y},"z"in coordinates[0]?(zAcc=function(index){return coordinates[index].z},writer=function(index,x,y,z){output[i]={x:x,y:y,z:z}}):writer=function(index,x,y){output[index]={x:x,y:y}};else{if(!(coordinates&&"x"in coordinates&&"y"in coordinates))throw"Invalid coordinates";xAcc=function(){return coordinates.x},yAcc=function(){return coordinates.y},"z"in coordinates?(zAcc=function(){return coordinates.z},writer=function(index,x,y,z){output={x:x,y:y,z:z}}):writer=function(index,x,y){output={x:x,y:y}}}}var i,count,offset,xCoord,yCoord,zCoord,xAcc,yAcc,zAcc,writer,output,projPoint,projSrcGcs=new proj4.Proj(srcGcs),projDestGcs=new proj4.Proj(destGcs);if(zAcc=function(){return 0},destGcs===srcGcs)return coordinates;if(!destGcs||!srcGcs)throw"Invalid source or destination GCS";if(coordinates instanceof Array)output=[],output.length=coordinates.length,count=coordinates.length,coordinates[0]instanceof Array||coordinates[0]instanceof geo.latlng||coordinates[0]instanceof Object?(offset=1,coordinates[0]instanceof Array?handleArrayCoordinates():coordinates[0]instanceof geo.latlng?handleLatLngCoordinates():coordinates[0]instanceof Object&&handleObjectCoordinates()):handleArrayCoordinates();else if(coordinates&&coordinates instanceof Object)if(count=1,offset=1,coordinates instanceof geo.latlng)handleLatLngCoordinates();else{if(!(coordinates&&"x"in coordinates&&"y"in coordinates))throw"Coordinates are not valid";handleObjectCoordinates()}if("EPSG:3857"===destGcs&&"EPSG:4326"===srcGcs){for(i=0;count>i;i+=offset)xCoord=xAcc(i),yCoord=yAcc(i),zCoord=zAcc(i),yCoord>85.0511&&(yCoord=85.0511),-85.0511>yCoord&&(yCoord=-85.0511),writer(i,xCoord,geo.mercator.lat2y(yCoord),zCoord);return output}for(i=0;count>i;i+=offset)return projPoint=new proj4.Point(xAcc(i),yAcc(i),zAcc(i)),proj4.transform(projSrcGcs,projDestGcs,projPoint),writer(i,projPoint.x,projPoint.y,projPoint.z),output},geo.renderer=function(arg){"use strict";if(!(this instanceof geo.renderer))return new geo.renderer(arg);geo.object.call(this),arg=arg||{};var m_this=this,m_layer=void 0===arg.layer?null:arg.layer,m_canvas=void 0===arg.canvas?null:arg.canvas,m_initialized=!1;return this.layer=function(){return m_layer},this.canvas=function(val){return void 0===val?m_canvas:(m_canvas=val,void m_this.modified())},this.map=function(){return m_layer?m_layer.map():null},this.baseLayer=function(){return m_this.map()?m_this.map().baseLayer():void 0},this.initialized=function(val){return void 0===val?m_initialized:(m_initialized=val,m_this)},this.api=function(){throw"Should be implemented by derivied classes"},this.reset=function(){return!0},this.worldToGcs=function(){throw"Should be implemented by derivied classes"},this.displayToGcs=function(){throw"Should be implemented by derivied classes"},this.gcsToDisplay=function(){throw"Should be implemented by derivied classes"},this.worldToDisplay=function(){throw"Should be implemented by derivied classes"},this.displayToWorld=function(){throw"Should be implemented by derivied classes"},this.relMouseCoords=function(event){var totalOffsetX=0,totalOffsetY=0,canvasX=0,canvasY=0,currentElement=m_this.canvas();do totalOffsetX+=currentElement.offsetLeft-currentElement.scrollLeft,totalOffsetY+=currentElement.offsetTop-currentElement.scrollTop,currentElement=currentElement.offsetParent;while(currentElement);return canvasX=event.pageX-totalOffsetX,canvasY=event.pageY-totalOffsetY,{x:canvasX,y:canvasY}},this._init=function(){},this._resize=function(){},this._render=function(){},this},inherit(geo.renderer,geo.object),geo.osmLayer=function(arg){"use strict";function isTileVisible(tile){return tile.zoom in m_visibleTilesRange&&tile.index_x>=m_visibleTilesRange[tile.zoom].startX&&tile.index_x<=m_visibleTilesRange[tile.zoom].endX&&tile.index_y>=m_visibleTilesRange[tile.zoom].startY&&tile.index_y<=m_visibleTilesRange[tile.zoom].endY?!0:!1}function drawTiles(){m_this._removeTiles(),m_this.draw(),delete m_pendingNewTilesStat[m_updateTimerId]}function updateOSMTiles(request){void 0===request&&(request={}),m_zoom||(m_zoom=m_this.map().zoom()),m_lastVisibleZoom||(m_lastVisibleZoom=m_zoom),m_this._addTiles(request),m_lastVisibleZoom!==m_zoom&&(m_lastVisibleZoom=m_zoom),m_this.updateTime().modified()}if(!(this instanceof geo.osmLayer))return new geo.osmLayer(arg);geo.featureLayer.call(this,arg);var m_tileUrl,m_tileUrlFromTemplate,m_this=this,s_exit=this._exit,m_tiles={},m_hiddenBinNumber=-1,m_lastVisibleBinNumber=-1,m_visibleBinNumber=1e3,m_pendingNewTiles=[],m_pendingInactiveTiles=[],m_numberOfCachedTiles=0,m_tileCacheSize=100,m_baseUrl="http://tile.openstreetmap.org/",m_mapOpacity=1,m_imageFormat="png",m_updateTimerId=null,m_lastVisibleZoom=null,m_visibleTilesRange={},s_init=this._init,m_pendingNewTilesStat={},s_update=this._update,m_updateDefer=null,m_zoom=null;return arg&&void 0!==arg.baseUrl&&(m_baseUrl=arg.baseUrl),"/"!==m_baseUrl.charAt(m_baseUrl.length-1)&&(m_baseUrl+="/"),arg&&void 0!==arg.mapOpacity&&(m_mapOpacity=arg.mapOpacity),arg&&void 0!==arg.imageFormat&&(m_imageFormat=arg.imageFormat),arg&&void 0!==arg.displayLast&&arg.displayLast&&(m_lastVisibleBinNumber=999),m_tileUrl=function(zoom,x,y){return m_baseUrl+zoom+"/"+x+"/"+y+"."+m_imageFormat},m_tileUrlFromTemplate=function(base){return function(zoom,x,y){return base.replace("",zoom).replace("",x).replace("",y)}},this.tileCacheSize=function(val){return void 0===val?m_tileCacheSize:(m_tileCacheSize=val,void m_this.modified())},this.tileUrl=function(val){return void 0===val?m_tileUrl:(m_tileUrl="string"==typeof val?m_tileUrlFromTemplate(val):val,m_this.modified(),m_this)},this.toLocal=function(input){var i,output,delta;if(input instanceof Array&&input.length>0)if(output=[],output.length=input.length,input[0]instanceof geo.latlng)for(i=0;i=2&&(output=input.slice(0),output[1]=geo.mercator.lat2y(input[1]));else input instanceof geo.latlng?(output={},output.x=input.x(),output.y=geo.mercator.lat2y(input.y())):(output={},output.x=input.x,output.y=geo.mercator.lat2y(input.y));return output},this.fromLocal=function(input){var i,output;if(input instanceof Array&&input.length>0)if(output=[],output.length=input.length,input[0]instanceof Object)for(i=0;im_tileCacheSize&&i=m_pendingNewTilesStat[m_updateTimerId].total&&drawTiles(),defer.resolve())}}var feature,lastStartX,lastStartY,lastEndX,lastEndY,currStartX,currStartY,currEndX,currEndY,distWorldDeltaPerTile,ren=m_this.renderer(),llx=0,lly=m_this.height(),urx=m_this.width(),ury=0,temp=null,tile=null,tile1x=null,tile1y=null,tile2x=null,tile2y=null,invJ=null,i=0,j=0,worldPt1=ren.displayToWorld([llx,lly]),worldPt2=ren.displayToWorld([urx,ury]),worldDeltaY=null,displayDeltaY=null,worldDelta=null,displayDelta=null,noOfTilesRequired=null,worldDeltaPerTile=null,minDistWorldDeltaPerTile=null;for(worldPt1[0]=Math.max(worldPt1[0],-180),worldPt1[0]=Math.min(worldPt1[0],180),worldPt1[1]=Math.max(worldPt1[1],-180),worldPt1[1]=Math.min(worldPt1[1],180),worldPt2[0]=Math.max(worldPt2[0],-180),worldPt2[0]=Math.min(worldPt2[0],180),worldPt2[1]=Math.max(worldPt2[1],-180),worldPt2[1]=Math.min(worldPt2[1],180),worldDelta=Math.abs(worldPt2[0]-worldPt1[0]),worldDeltaY=Math.abs(worldPt2[1]-worldPt1[1]),displayDelta=urx-llx,displayDeltaY=lly-ury,displayDeltaY>displayDelta&&(displayDelta=displayDeltaY,worldDelta=worldDeltaY),noOfTilesRequired=Math.round(displayDelta/256),worldDeltaPerTile=worldDelta/noOfTilesRequired,minDistWorldDeltaPerTile=Number.POSITIVE_INFINITY,i=20;i>=2;i-=1)distWorldDeltaPerTile=Math.abs(360/Math.pow(2,i)-worldDeltaPerTile),minDistWorldDeltaPerTile>distWorldDeltaPerTile&&(minDistWorldDeltaPerTile=distWorldDeltaPerTile,m_zoom=i);for(tile1x=geo.mercator.long2tilex(worldPt1[0],m_zoom),tile1y=geo.mercator.lat2tiley(worldPt1[1],m_zoom),tile2x=geo.mercator.long2tilex(worldPt2[0],m_zoom),tile2y=geo.mercator.lat2tiley(worldPt2[1],m_zoom),tile1x=Math.max(tile1x,0),tile1x=Math.min(Math.pow(2,m_zoom)-1,tile1x),tile1y=Math.max(tile1y,0),tile1y=Math.min(Math.pow(2,m_zoom)-1,tile1y),tile2x=Math.max(tile2x,0),tile2x=Math.min(Math.pow(2,m_zoom)-1,tile2x),tile2y=Math.max(tile2y,0),tile2y=Math.min(Math.pow(2,m_zoom)-1,tile2y),tile1x>tile2x&&(temp=tile1x,tile1x=tile2x,tile2x=temp),tile2y>tile1y&&(temp=tile1y,tile1y=tile2y,tile2y=temp),currStartX=tile1x,currEndX=tile2x,currStartY=Math.pow(2,m_zoom)-1-tile1y,currEndY=Math.pow(2,m_zoom)-1-tile2y,currStartY>currEndY&&(temp=currStartY,currStartY=currEndY,currEndY=temp),lastStartX=geo.mercator.long2tilex(worldPt1[0],m_lastVisibleZoom),lastStartY=geo.mercator.lat2tiley(worldPt1[1],m_lastVisibleZoom),lastEndX=geo.mercator.long2tilex(worldPt2[0],m_lastVisibleZoom),lastEndY=geo.mercator.lat2tiley(worldPt2[1],m_lastVisibleZoom),lastStartY=Math.pow(2,m_lastVisibleZoom)-1-lastStartY,lastEndY=Math.pow(2,m_lastVisibleZoom)-1-lastEndY,lastStartY>lastEndY&&(temp=lastStartY,lastStartY=lastEndY,lastEndY=temp),m_visibleTilesRange={},m_visibleTilesRange[m_zoom]={startX:currStartX,endX:currEndX,startY:currStartY,endY:currEndY},m_visibleTilesRange[m_lastVisibleZoom]={startX:lastStartX,endX:lastEndX,startY:lastStartY,endY:lastEndY},m_pendingNewTilesStat[m_updateTimerId]={total:(tile2x-tile1x+1)*(tile1y-tile2y+1),count:0},i=tile1x;tile2x>=i;i+=1)for(j=tile2y;tile1y>=j;j+=1)invJ=Math.pow(2,m_zoom)-1-j,m_this._hasTile(m_zoom,i,invJ)?(tile=m_tiles[m_zoom][i][invJ],tile.feature.bin(m_visibleBinNumber),tile.LOADED&&m_updateTimerId in m_pendingNewTilesStat&&(m_pendingNewTilesStat[m_updateTimerId].count+=1),tile.lastused=new Date,tile.feature._update()):tile=m_this._addTile(request,m_zoom,i,invJ),tile.updateTimerId=m_updateTimerId;for(i=0;i=m_pendingNewTilesStat[m_updateTimerId].total&&drawTiles()},this._updateTiles=function(request){var defer=$.Deferred();return m_this.addDeferred(defer),null!==m_updateTimerId?(clearTimeout(m_updateTimerId),m_updateDefer.resolve(),m_updateDefer=defer,m_updateTimerId in m_pendingNewTilesStat&&delete m_pendingNewTilesStat[m_updateTimerId],m_updateTimerId=setTimeout(function(){updateOSMTiles(request),m_updateDefer.resolve()},100)):(m_updateDefer=defer,m_updateTimerId=setTimeout(function(){updateOSMTiles(request),m_updateDefer.resolve()},0)),m_this},this._init=function(){return s_init.call(m_this),m_this.gcs("EPSG:3857"),m_this.map().zoomRange({min:0,max:18}),m_this},this._update=function(request){m_this._updateTiles(request),s_update.call(m_this,request)},this.updateBaseUrl=function(baseUrl){if(baseUrl&&"/"!==baseUrl.charAt(m_baseUrl.length-1)&&(baseUrl+="/"),baseUrl!==m_baseUrl){void 0!==baseUrl&&(m_baseUrl=baseUrl);var tile,x,y,zoom;for(zoom in m_tiles)for(x in m_tiles[zoom])for(y in m_tiles[zoom][x])tile=m_tiles[zoom][x][y],tile.INVALID=!0,m_this.deleteFeature(tile.feature);m_tiles={},m_pendingNewTiles=[],m_pendingInactiveTiles=[],m_numberOfCachedTiles=0,m_visibleTilesRange={},m_pendingNewTilesStat={},null!==m_updateTimerId&&(clearTimeout(m_updateTimerId),m_updateTimerId=null),this._update()}},this.mapOpacity=function(val){if(void 0===val)return m_mapOpacity;if(val!==m_mapOpacity){m_mapOpacity=val;var zoom,x,y,tile;for(zoom in m_tiles)for(x in m_tiles[zoom])for(y in m_tiles[zoom][x])tile=m_tiles[zoom][x][y],tile.feature.style().opacity=val,tile.feature._update();m_this.modified()}return m_this},this._exit=function(){m_tiles={},m_pendingNewTiles=[],m_pendingInactiveTiles=[],m_numberOfCachedTiles=0,m_visibleTilesRange={},m_pendingNewTilesStat={},s_exit()},arg&&void 0!==arg.tileUrl&&this.tileUrl(arg.tileUrl),this},inherit(geo.osmLayer,geo.featureLayer),geo.registerLayer("osm",geo.osmLayer),geo.gl={},geo.gl.renderer=function(arg){"use strict";return this instanceof geo.gl.renderer?(geo.renderer.call(this,arg),this.contextRenderer=function(){throw"Should be implemented by derived classes"},this):new geo.gl.renderer(arg)},inherit(geo.gl.renderer,geo.renderer),geo.gl.lineFeature=function(arg){"use strict";function createVertexShader(){var vertexShaderSource=["#ifdef GL_ES"," precision highp float;","#endif","attribute vec3 pos;","attribute vec3 prev;","attribute vec3 next;","attribute float offset;","attribute vec3 strokeColor;","attribute float strokeOpacity;","attribute float strokeWidth;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float pixelWidth;","uniform float aspect;","varying vec3 strokeColorVar;","varying float strokeWidthVar;","varying float strokeOpacityVar;","void main(void)","{"," if (strokeOpacity < 0.0) {"," gl_Position = vec4(2, 2, 0, 1);"," return;"," }"," const float PI = 3.14159265358979323846264;"," vec4 worldPos = projectionMatrix * modelViewMatrix * vec4(pos.xyz, 1);"," if (worldPos.w != 0.0) {"," worldPos = worldPos/worldPos.w;"," }"," vec4 worldNext = projectionMatrix * modelViewMatrix * vec4(next.xyz, 1);"," if (worldNext.w != 0.0) {"," worldNext = worldNext/worldNext.w;"," }"," vec4 worldPrev = projectionMatrix* modelViewMatrix * vec4(prev.xyz, 1);"," if (worldPrev.w != 0.0) {"," worldPrev = worldPrev/worldPrev.w;"," }"," strokeColorVar = strokeColor;"," strokeWidthVar = strokeWidth;"," strokeOpacityVar = strokeOpacity;"," vec2 deltaNext = worldNext.xy - worldPos.xy;"," vec2 deltaPrev = worldPos.xy - worldPrev.xy;"," float angleNext = 0.0, anglePrev = 0.0;"," if (deltaNext.xy != vec2(0.0, 0.0))"," angleNext = atan(deltaNext.y / aspect, deltaNext.x);"," if (deltaPrev.xy == vec2(0.0, 0.0)) anglePrev = angleNext;"," else anglePrev = atan(deltaPrev.y / aspect, deltaPrev.x);"," if (deltaNext.xy == vec2(0.0, 0.0)) angleNext = anglePrev;"," float angle = (anglePrev + angleNext) / 2.0;"," float cosAngle = cos(anglePrev - angle);"," if (cosAngle < 0.1) { cosAngle = sign(cosAngle) * 1.0; angle = 0.0; }"," float distance = (offset * strokeWidth * pixelWidth) /"," cosAngle;"," worldPos.x += distance * sin(angle);"," worldPos.y -= distance * cos(angle) * aspect;"," gl_Position = worldPos;","}"].join("\n"),shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader}function createFragmentShader(){var fragmentShaderSource=["#ifdef GL_ES"," precision highp float;","#endif","varying vec3 strokeColorVar;","varying float strokeWidthVar;","varying float strokeOpacityVar;","void main () {"," gl_FragColor = vec4 (strokeColorVar, strokeOpacityVar);","}"].join("\n"),shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader}function createGLLines(){var i,j,k,v,len,lineItem,lineItemData,vertTemp,pos,posIdx3,posBuf,nextBuf,prevBuf,offsetBuf,indicesBuf,strokeWidthBuf,strokeColorBuf,strokeOpacityBuf,dest,dest3,data=m_this.data(),numSegments=0,vert=[{},{}],position=[],posFunc=m_this.position(),strkWidthFunc=m_this.style.get("strokeWidth"),strkColorFunc=m_this.style.get("strokeColor"),strkOpacityFunc=m_this.style.get("strokeOpacity"),order=m_this.featureVertices(),geom=m_mapper.geometryData();for(i=0;i=m_this.buildTime().getMTime()||m_this.updateTime().getMTime()<=m_this.getMTime())&&m_this._build(),m_pixelWidthUnif.set(1/m_this.renderer().width()),m_aspectUniform.set(m_this.renderer().width()/m_this.renderer().height()),m_actor.setVisible(m_this.visible()),m_actor.material().setBinNumber(m_this.bin()),m_this.updateTime().modified()},this._exit=function(){m_this.renderer().contextRenderer().removeActor(m_actor),s_exit()},this._init(arg),this},inherit(geo.gl.lineFeature,geo.lineFeature),geo.registerFeature("vgl","line",geo.gl.lineFeature),geo.gl.pointFeature=function(arg){"use strict";function createVertexShader(){var shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader}function createFragmentShader(){var shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader}function pointPolygon(x,y,w,h){var verts;switch(m_primitiveShape){case"triangle":verts=[x,y-2*h,x-w*Math.sqrt(3),y+h,x+w*Math.sqrt(3),y+h];break;case"sprite":verts=[x,y];break;default:verts=[x-w,y+h,x-w,y-h,x+w,y+h,x-w,y-h,x+w,y-h,x+w,y+h]}return verts}function createGLPoints(){var i,j,posBuf,posVal,posFunc,unitBuf,indices,radius,radiusVal,radFunc,stroke,strokeVal,strokeFunc,strokeWidth,strokeWidthVal,strokeWidthFunc,strokeOpacity,strokeOpacityVal,strokeOpactityFunc,strokeColor,strokeColorVal,strokeColorFunc,fill,fillVal,fillFunc,fillOpacity,fillOpacityVal,fillOpacityFunc,fillColor,fillColorVal,fillColorFunc,item,ivpf,ivpf3,iunit,i3,numPts=m_this.data().length,unit=pointPolygon(0,0,1,1),position=new Array(3*numPts),vpf=m_this.verticesPerFeature(),data=m_this.data(),geom=m_mapper.geometryData();for(posFunc=m_this.position(),radFunc=m_this.style.get("radius"),strokeFunc=m_this.style.get("stroke"),strokeWidthFunc=m_this.style.get("strokeWidth"),strokeOpactityFunc=m_this.style.get("strokeOpacity"),strokeColorFunc=m_this.style.get("strokeColor"),fillFunc=m_this.style.get("fill"),fillOpacityFunc=m_this.style.get("fillOpacity"),fillColorFunc=m_this.style.get("fillColor"),i=i3=0;numPts>i;i+=1,i3+=3)posVal=posFunc(data[i]),position[i3]=posVal.x,position[i3+1]=posVal.y,position[i3+2]=posVal.z||0;for(position=geo.transform.transformCoordinates(m_this.gcs(),m_this.layer().map().gcs(),position,3),posBuf=getBuffer(geom,"pos",vpf*numPts*3),"sprite"!==m_primitiveShape&&(unitBuf=getBuffer(geom,"unit",vpf*numPts*2)),radius=getBuffer(geom,"rad",vpf*numPts*1),stroke=getBuffer(geom,"stroke",vpf*numPts*1),strokeWidth=getBuffer(geom,"strokeWidth",vpf*numPts*1),strokeOpacity=getBuffer(geom,"strokeOpacity",vpf*numPts*1),strokeColor=getBuffer(geom,"strokeColor",vpf*numPts*3),fill=getBuffer(geom,"fill",vpf*numPts*1),fillOpacity=getBuffer(geom,"fillOpacity",vpf*numPts*1),fillColor=getBuffer(geom,"fillColor",vpf*numPts*3),indices=geom.primitive(0).indices(),indices instanceof Uint16Array&&indices.length===vpf*numPts||(indices=new Uint16Array(vpf*numPts),geom.primitive(0).setIndices(indices)),i=ivpf=ivpf3=iunit=i3=0;numPts>i;i+=1,i3+=3){if(item=data[i],"sprite"!==m_primitiveShape)for(j=0;jj;j+=1,ivpf+=1,ivpf3+=3)posBuf[ivpf3]=position[i3],posBuf[ivpf3+1]=position[i3+1],posBuf[ivpf3+2]=position[i3+2],radius[ivpf]=radiusVal,stroke[ivpf]=strokeVal,strokeWidth[ivpf]=strokeWidthVal,strokeOpacity[ivpf]=strokeOpacityVal,strokeColor[ivpf3]=strokeColorVal.r,strokeColor[ivpf3+1]=strokeColorVal.g,strokeColor[ivpf3+2]=strokeColorVal.b,fill[ivpf]=fillVal,fillOpacity[ivpf]=fillOpacityVal,fillColor[ivpf3]=fillColorVal.r,fillColor[ivpf3+1]=fillColorVal.g,fillColor[ivpf3+2]=fillColorVal.b}geom.boundsDirty(!0),m_mapper.modified(),m_mapper.boundsDirtyTimestamp().modified()}function getBuffer(geom,srcName,len){var data,src=geom.sourceByName(srcName);return data=src.data(),data instanceof Float32Array&&data.length===len?data:(data=new Float32Array(len),src.setData(data),data)}if(!(this instanceof geo.gl.pointFeature))return new geo.gl.pointFeature(arg);arg=arg||{},geo.pointFeature.call(this,arg);var m_this=this,s_exit=this._exit,m_actor=null,m_mapper=null,m_pixelWidthUniform=null,m_aspectUniform=null,m_dynamicDraw=void 0===arg.dynamicDraw?!1:arg.dynamicDraw,m_primitiveShape="sprite",s_init=this._init,s_update=this._update,vertexShaderSource=null,fragmentShaderSource=null;return("triangle"===arg.primitiveShape||"square"===arg.primitiveShape||"sprite"===arg.primitiveShape)&&(m_primitiveShape=arg.primitiveShape),vertexShaderSource=["#ifdef GL_ES"," precision highp float;","#endif","attribute vec3 pos;","attribute float rad;","attribute vec3 fillColor;","attribute vec3 strokeColor;","attribute float fillOpacity;","attribute float strokeWidth;","attribute float strokeOpacity;","attribute float fill;","attribute float stroke;","uniform float pixelWidth;","uniform float aspect;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","varying vec4 fillColorVar;","varying vec4 strokeColorVar;","varying float radiusVar;","varying float strokeWidthVar;","varying float fillVar;","varying float strokeVar;"],"sprite"!==m_primitiveShape&&(vertexShaderSource=vertexShaderSource.concat(["attribute vec2 unit;","varying vec3 unitVar;"])),vertexShaderSource.push.apply(vertexShaderSource,["void main(void)","{"," strokeWidthVar = strokeWidth;"," // No stroke or fill implies nothing to draw"," if (stroke < 1.0 || strokeWidth <= 0.0 || strokeOpacity <= 0.0) {"," strokeVar = 0.0;"," strokeWidthVar = 0.0;"," }"," else"," strokeVar = 1.0;"," if (fill < 1.0 || rad <= 0.0 || fillOpacity <= 0.0)"," fillVar = 0.0;"," else"," fillVar = 1.0;"," if (fillVar == 0.0 && strokeVar == 0.0) {"," gl_Position = vec4(2, 2, 0, 1);"," return;"," }"," fillColorVar = vec4 (fillColor, fillOpacity);"," strokeColorVar = vec4 (strokeColor, strokeOpacity);"," radiusVar = rad;"]),"sprite"===m_primitiveShape?vertexShaderSource.push.apply(vertexShaderSource,[" gl_Position = (projectionMatrix * modelViewMatrix * vec4(pos, 1.0)).xyzw;"," gl_PointSize = 2.0 * (rad + strokeWidthVar); ","}"]):vertexShaderSource.push.apply(vertexShaderSource,[" unitVar = vec3 (unit, 1.0);"," vec4 p = (projectionMatrix * modelViewMatrix * vec4(pos, 1.0)).xyzw;"," if (p.w != 0.0) {"," p = p / p.w;"," }"," p += (rad + strokeWidthVar) * "," vec4 (unit.x * pixelWidth, unit.y * pixelWidth * aspect, 0.0, 1.0);"," gl_Position = vec4(p.xyz, 1.0);","}"]),vertexShaderSource=vertexShaderSource.join("\n"),fragmentShaderSource=["#ifdef GL_ES"," precision highp float;","#endif","uniform float aspect;","varying vec4 fillColorVar;","varying vec4 strokeColorVar;","varying float radiusVar;","varying float strokeWidthVar;","varying float fillVar;","varying float strokeVar;"],"sprite"!==m_primitiveShape&&fragmentShaderSource.push("varying vec3 unitVar;"),fragmentShaderSource.push.apply(fragmentShaderSource,["void main () {"," vec4 strokeColor, fillColor;"," float endStep;"," // No stroke or fill implies nothing to draw"," if (fillVar == 0.0 && strokeVar == 0.0)"," discard;"]),fragmentShaderSource.push("sprite"===m_primitiveShape?" float rad = 2.0 * length (gl_PointCoord - vec2(0.5));":" float rad = length (unitVar.xy);"),fragmentShaderSource.push.apply(fragmentShaderSource,[" if (rad > 1.0)"," discard;"," // If there is no stroke, the fill region should transition to nothing"," if (strokeVar == 0.0) {"," strokeColor = vec4 (fillColorVar.rgb, 0.0);"," endStep = 1.0;"," } else {"," strokeColor = strokeColorVar;"," endStep = radiusVar / (radiusVar + strokeWidthVar);"," }"," // Likewise, if there is no fill, the stroke should transition to nothing"," if (fillVar == 0.0)"," fillColor = vec4 (strokeColor.rgb, 0.0);"," else"," fillColor = fillColorVar;"," // Distance to antialias over"," float antialiasDist = 3.0 / (2.0 * radiusVar);"," if (rad < endStep) {"," float step = smoothstep (endStep - antialiasDist, endStep, rad);"," gl_FragColor = mix (fillColor, strokeColor, step);"," } else {"," float step = smoothstep (1.0 - antialiasDist, 1.0, rad);"," gl_FragColor = mix (strokeColor, vec4 (strokeColor.rgb, 0.0), step);"," }","}"]),fragmentShaderSource=fragmentShaderSource.join("\n"),this.actors=function(){return m_actor?[m_actor]:[]},this.verticesPerFeature=function(){var unit=pointPolygon(0,0,1,1);return unit.length/2},this._init=function(){var prog=vgl.shaderProgram(),vertexShader=createVertexShader(),fragmentShader=createFragmentShader(),posAttr=vgl.vertexAttribute("pos"),unitAttr=vgl.vertexAttribute("unit"),radAttr=vgl.vertexAttribute("rad"),strokeWidthAttr=vgl.vertexAttribute("strokeWidth"),fillColorAttr=vgl.vertexAttribute("fillColor"),fillAttr=vgl.vertexAttribute("fill"),strokeColorAttr=vgl.vertexAttribute("strokeColor"),strokeAttr=vgl.vertexAttribute("stroke"),fillOpacityAttr=vgl.vertexAttribute("fillOpacity"),strokeOpacityAttr=vgl.vertexAttribute("strokeOpacity"),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix"),mat=vgl.material(),blend=vgl.blend(),geom=vgl.geometryData(),sourcePositions=vgl.sourceDataP3fv({name:"pos"}),sourceUnits=vgl.sourceDataAnyfv(2,vgl.vertexAttributeKeysIndexed.One,{name:"unit"}),sourceRadius=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Two,{name:"rad"}),sourceStrokeWidth=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Three,{name:"strokeWidth"}),sourceFillColor=vgl.sourceDataAnyfv(3,vgl.vertexAttributeKeysIndexed.Four,{name:"fillColor"}),sourceFill=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Five,{name:"fill"}),sourceStrokeColor=vgl.sourceDataAnyfv(3,vgl.vertexAttributeKeysIndexed.Six,{name:"strokeColor"}),sourceStroke=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Seven,{name:"stroke"}),sourceAlpha=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Eight,{name:"fillOpacity"}),sourceStrokeOpacity=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Nine,{name:"strokeOpacity"}),primitive=new vgl.triangles;"sprite"===m_primitiveShape&&(primitive=new vgl.points),m_pixelWidthUniform=new vgl.floatUniform("pixelWidth",2/m_this.renderer().width()),m_aspectUniform=new vgl.floatUniform("aspect",m_this.renderer().width()/m_this.renderer().height()),s_init.call(m_this,arg),m_mapper=vgl.mapper({dynamicDraw:m_dynamicDraw}),prog.addVertexAttribute(posAttr,vgl.vertexAttributeKeys.Position),"sprite"!==m_primitiveShape&&prog.addVertexAttribute(unitAttr,vgl.vertexAttributeKeysIndexed.One),prog.addVertexAttribute(radAttr,vgl.vertexAttributeKeysIndexed.Two),prog.addVertexAttribute(strokeWidthAttr,vgl.vertexAttributeKeysIndexed.Three),prog.addVertexAttribute(fillColorAttr,vgl.vertexAttributeKeysIndexed.Four),prog.addVertexAttribute(fillAttr,vgl.vertexAttributeKeysIndexed.Five),prog.addVertexAttribute(strokeColorAttr,vgl.vertexAttributeKeysIndexed.Six),prog.addVertexAttribute(strokeAttr,vgl.vertexAttributeKeysIndexed.Seven),prog.addVertexAttribute(fillOpacityAttr,vgl.vertexAttributeKeysIndexed.Eight),prog.addVertexAttribute(strokeOpacityAttr,vgl.vertexAttributeKeysIndexed.Nine),prog.addUniform(m_pixelWidthUniform),prog.addUniform(m_aspectUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),m_actor=vgl.actor(),m_actor.setMaterial(mat),m_actor.setMapper(m_mapper),geom.addSource(sourcePositions),geom.addSource(sourceUnits),geom.addSource(sourceRadius),geom.addSource(sourceStrokeWidth),geom.addSource(sourceFillColor),geom.addSource(sourceFill),geom.addSource(sourceStrokeColor),geom.addSource(sourceStroke),geom.addSource(sourceAlpha),geom.addSource(sourceStrokeOpacity),geom.addPrimitive(primitive),m_mapper.setGeometryData(geom)},this._build=function(){m_actor&&m_this.renderer().contextRenderer().removeActor(m_actor),createGLPoints(),m_this.renderer().contextRenderer().addActor(m_actor),m_this.renderer().contextRenderer().render(),m_this.buildTime().modified()},this._update=function(){s_update.call(m_this),(m_this.dataTime().getMTime()>=m_this.buildTime().getMTime()||m_this.updateTime().getMTime()i;i+=1)buffers.write("pos",position[i],start+i,1),buffers.write("indices",[i],start+i,1),buffers.write("fillColor",fillColorNew[i],start+i,1),buffers.write("fillOpacity",[fillOpacityNew[i]],start+i,1);sourcePositions.pushBack(buffers.get("pos")),geom.addSource(sourcePositions),sourceFillColor.pushBack(buffers.get("fillColor")),geom.addSource(sourceFillColor),sourceFillOpacity.pushBack(buffers.get("fillOpacity")),geom.addSource(sourceFillOpacity),trianglePrimitive.setIndices(buffers.get("indices")),geom.addPrimitive(trianglePrimitive),m_mapper.setGeometryData(geom)}if(!(this instanceof geo.gl.polygonFeature))return new geo.gl.polygonFeature(arg);arg=arg||{},geo.polygonFeature.call(this,arg);var m_this=this,s_exit=this._exit,m_actor=vgl.actor(),m_mapper=vgl.mapper(),m_material=vgl.material(),s_init=this._init,s_update=this._update;return this._init=function(arg){var blend=vgl.blend(),prog=vgl.shaderProgram(),posAttr=vgl.vertexAttribute("pos"),fillColorAttr=vgl.vertexAttribute("fillColor"),fillOpacityAttr=vgl.vertexAttribute("fillOpacity"),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix"),vertexShader=createVertexShader(),fragmentShader=createFragmentShader();s_init.call(m_this,arg),prog.addVertexAttribute(posAttr,vgl.vertexAttributeKeys.Position),prog.addVertexAttribute(fillColorAttr,vgl.vertexAttributeKeysIndexed.Two),prog.addVertexAttribute(fillOpacityAttr,vgl.vertexAttributeKeysIndexed.Three),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),m_material.addAttribute(prog),m_material.addAttribute(blend),m_actor.setMapper(m_mapper),m_actor.setMaterial(m_material)},this._build=function(){m_actor&&m_this.renderer().contextRenderer().removeActor(m_actor),createGLPolygons(),m_this.renderer().contextRenderer().addActor(m_actor),m_this.buildTime().modified()},this._update=function(){s_update.call(m_this),(m_this.dataTime().getMTime()>=m_this.buildTime().getMTime()||m_this.updateTime().getMTime()<=m_this.getMTime())&&m_this._build(),m_actor.setVisible(m_this.visible()),m_actor.material().setBinNumber(m_this.bin()),m_this.updateTime().modified()},this._exit=function(){m_this.renderer().contextRenderer().removeActor(m_actor),s_exit()},this._init(arg),this},inherit(geo.gl.polygonFeature,geo.polygonFeature),geo.registerFeature("vgl","polygon",geo.gl.polygonFeature),geo.gl._vglViewerInstances={viewers:[],maps:[]},geo.gl.vglViewerInstance=function(map){"use strict";function makeViewer(){canvas=$(document.createElement("canvas")),canvas.attr("class","webgl-canvas");var viewer=vgl.viewer(canvas.get(0));return viewer.renderWindow().removeRenderer(viewer.renderWindow().activeRenderer()),viewer.init(),viewer}var mapIdx,canvas,maps=geo.gl._vglViewerInstances.maps,viewers=geo.gl._vglViewerInstances.viewers;for(mapIdx=0;mapIdx0)if(output=[],input[0]instanceof Object)for(delta=1,i=0;i0)if(output=[],input[0]instanceof Object)for(delta=1,i=0;i0&&(m_contextRenderer.setLayer(m_viewer.renderWindow().renderers().length),m_contextRenderer.setResetScene(!1)),m_viewer.renderWindow().addRenderer(m_contextRenderer),m_this.layer().node().append(m_this.canvas()),m_this)},this._resize=function(x,y,w,h){return m_width=w,m_height=h,m_this.canvas().attr("width",w),m_this.canvas().attr("height",h),m_viewer.renderWindow().positionAndResize(x,y,w,h),m_this._render(),m_this},this._render=function(){return m_viewer.render(),m_this},this._exit=function(){geo.gl.vglViewerInstance.deleteCache(m_viewer),s_exit()},this._updateRendererCamera=function(){var pos,fp,cr,vglRenderer=m_this.contextRenderer(),renderWindow=m_viewer.renderWindow(),camera=vglRenderer.camera();vglRenderer.resetCameraClippingRange(),pos=camera.position(),fp=camera.focalPoint(),cr=camera.clippingRange(),renderWindow.renderers().forEach(function(renderer){var cam=renderer.camera();cam!==camera&&(cam.setPosition(pos[0],pos[1],pos[2]),cam.setFocalPoint(fp[0],fp[1],fp[2]),cam.setClippingRange(cr[0],cr[1]),renderer.render())})},this.geoOn(geo.event.pan,function(evt){var camera,focusPoint,centerDisplay,centerGeo,newCenterDisplay,newCenterGeo,renderWindow,vglRenderer=m_this.contextRenderer(),layer=m_this.layer();layer.map().baseLayer()===layer&&(vglRenderer&&vglRenderer.camera()||console.log("Pan event triggered on unconnected vgl renderer."),renderWindow=m_viewer.renderWindow(),camera=vglRenderer.camera(),focusPoint=renderWindow.focusDisplayPoint(),centerDisplay=[m_width/2,m_height/2,0],centerGeo=renderWindow.displayToWorld(centerDisplay[0],centerDisplay[1],focusPoint,vglRenderer),newCenterDisplay=[centerDisplay[0]+evt.screenDelta.x,centerDisplay[1]+evt.screenDelta.y],newCenterGeo=renderWindow.displayToWorld(newCenterDisplay[0],newCenterDisplay[1],focusPoint,vglRenderer),camera.pan(centerGeo[0]-newCenterGeo[0],centerGeo[1]-newCenterGeo[1],centerGeo[2]-newCenterGeo[2]),evt.center={x:newCenterGeo[0],y:newCenterGeo[1],z:newCenterGeo[2]},m_this._updateRendererCamera())}),this.geoOn(geo.event.zoom,function(evt){var camera,renderWindow,center,dir,focusPoint,position,newZ,vglRenderer=m_this.contextRenderer(),layer=m_this.layer();layer.map().baseLayer()===layer&&(vglRenderer&&vglRenderer.camera()||console.log("Zoom event triggered on unconnected vgl renderer."),renderWindow=m_viewer.renderWindow(),camera=vglRenderer.camera(),focusPoint=camera.focalPoint(),position=camera.position(),newZ=360*Math.pow(2,-evt.zoomLevel),evt.pan=null,evt.screenPosition&&(center=renderWindow.displayToWorld(evt.screenPosition.x,evt.screenPosition.y,focusPoint,vglRenderer),dir=[center[0]-position[0],center[1]-position[1],center[2]-position[2]],evt.center=layer.fromLocal({x:position[0]+dir[0]*(1-newZ/position[2]),y:position[1]+dir[1]*(1-newZ/position[2])})),camera.setPosition(position[0],position[1],360*Math.pow(2,-evt.zoomLevel)),m_this._updateRendererCamera())}),this},inherit(geo.gl.vglRenderer,geo.gl.renderer),geo.registerRenderer("vgl",geo.gl.vglRenderer),geo.d3={},function(){"use strict";var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",strLength=8;geo.d3.uniqueID=function(){var i,strArray=[];for(strArray.length=strLength,i=0;strLength>i;i+=1)strArray[i]=chars.charAt(Math.floor(Math.random()*chars.length));return strArray.join("")},geo.event.d3Rescale="geo_d3_rescale"}(),geo.d3.object=function(arg){"use strict";if(!(this instanceof geo.object))return new geo.d3.object(arg);geo.sceneObject.call(this);var m_id="d3-"+geo.d3.uniqueID(),s_exit=this._exit,m_this=this,s_draw=this.draw;return this._d3id=function(){return m_id},this.select=function(){return m_this.renderer().select(m_this._d3id())},this.draw=function(){return m_this._update(),s_draw(),m_this},this._exit=function(){m_this.renderer()._removeFeature(m_this._d3id()),s_exit()},this},inherit(geo.d3.object,geo.sceneObject),geo.d3.pointFeature=function(arg){"use strict";if(!(this instanceof geo.d3.pointFeature))return new geo.d3.pointFeature(arg);arg=arg||{},geo.pointFeature.call(this,arg),geo.d3.object.call(this);var m_sticky,m_this=this,s_init=this._init,s_update=this._update,m_buildTime=geo.timestamp(),m_style={};return this._init=function(arg){return s_init.call(m_this,arg),m_sticky=m_this.layer().sticky(),m_this},this._build=function(){var data=m_this.data(),s_style=m_this.style.get(),m_renderer=m_this.renderer(),pos_func=m_this.position();return s_update.call(m_this),data||(data=[]),m_style.id=m_this._d3id(),m_style.data=data,m_style.append="circle",m_style.attributes={r:m_renderer._convertScale(s_style.radius),cx:function(d){return m_renderer.worldToDisplay(pos_func(d)).x},cy:function(d){return m_renderer.worldToDisplay(pos_func(d)).y}},m_style.style=s_style,m_style.classes=["d3PointFeature"],m_this.renderer()._drawFeatures(m_style),m_buildTime.modified(),m_this.updateTime().modified(),m_this},this._update=function(){return s_update.call(m_this),m_this.getMTime()>=m_buildTime.getMTime()&&m_this._build(),m_this},this._init(arg),this},inherit(geo.d3.pointFeature,geo.pointFeature),geo.registerFeature("d3","point",geo.d3.pointFeature),geo.d3.lineFeature=function(arg){"use strict";if(!(this instanceof geo.d3.lineFeature))return new geo.d3.lineFeature(arg);arg=arg||{},geo.lineFeature.call(this,arg),geo.d3.object.call(this);var m_this=this,s_init=this._init,m_buildTime=geo.timestamp(),s_update=this._update;return this._init=function(arg){return s_init.call(m_this,arg),m_this},this._build=function(){var data=m_this.data()||[],s_style=m_this.style(),m_renderer=m_this.renderer(),pos_func=m_this.position(),line=d3.svg.line().x(function(d){return m_renderer.worldToDisplay(d).x}).y(function(d){return m_renderer.worldToDisplay(d).y});return s_update.call(m_this),s_style.fill=function(){return!1},data.forEach(function(item,idx){function wrapStyle(func){return geo.util.isFunction(func)?function(){return func(ln[0],0,item,idx)}:func}var m_style,key,ln=m_this.line()(item,idx),style={};for(key in s_style)s_style.hasOwnProperty(key)&&(style[key]=wrapStyle(s_style[key]));m_style={data:[ln.map(function(d,i){return pos_func(d,i,item,idx)})],append:"path",attributes:{d:line},id:m_this._d3id()+idx,classes:["d3LineFeature","d3SubLine-"+idx],style:style},m_renderer._drawFeatures(m_style)}),m_buildTime.modified(),m_this.updateTime().modified(),m_this},this._update=function(){return s_update.call(m_this),m_this.getMTime()>=m_buildTime.getMTime()&&m_this._build(),m_this},this._init(arg),this},inherit(geo.d3.lineFeature,geo.lineFeature),geo.registerFeature("d3","line",geo.d3.lineFeature),geo.d3.pathFeature=function(arg){"use strict";if(!(this instanceof geo.d3.pathFeature))return new geo.d3.pathFeature(arg);arg=arg||{},geo.pathFeature.call(this,arg),geo.d3.object.call(this);var m_this=this,s_init=this._init,m_buildTime=geo.timestamp(),s_update=this._update,m_style={};return m_style.style={},this._init=function(arg){return s_init.call(m_this,arg),m_this},this._build=function(){var tmp,diag,data=m_this.data()||[],s_style=m_this.style(),m_renderer=m_this.renderer();return s_update.call(m_this),diag=function(d){var p={source:d.source,target:d.target};return d3.svg.diagonal()(p)},tmp=[],data.forEach(function(d,i){var src,trg;i=m_buildTime.getMTime()&&m_this._build(),m_this},this._init(arg),this},inherit(geo.d3.pathFeature,geo.pathFeature),geo.registerFeature("d3","path",geo.d3.pathFeature),geo.d3.graphFeature=function(arg){"use strict";var m_this=this;return this instanceof geo.d3.graphFeature?(geo.graphFeature.call(this,arg),this.select=function(){var renderer=m_this.renderer(),selection={},node=m_this.nodeFeature(),links=m_this.linkFeatures();return selection.nodes=renderer.select(node._d3id()),selection.links=links.map(function(link){return renderer.select(link._d3id())}),selection},this):new geo.d3.graphFeature(arg)},inherit(geo.d3.graphFeature,geo.graphFeature),geo.registerFeature("d3","graph",geo.d3.graphFeature),geo.d3.planeFeature=function(arg){"use strict";function normalize(pt){return Array.isArray(pt)?{x:pt[0],y:pt[1]}:pt instanceof geo.latlng?{x:pt.x(),y:pt.y()}:pt}if(!(this instanceof geo.d3.planeFeature))return new geo.d3.planeFeature(arg);geo.planeFeature.call(this,arg),geo.d3.object.call(this);var m_this=this,m_style={},s_update=this._update,s_init=this._init,m_buildTime=geo.timestamp();return this._build=function(){var origin=normalize(m_this.origin()),ul=normalize(m_this.upperLeft()),lr=normalize(m_this.lowerRight()),renderer=m_this.renderer(),s=m_this.style();return delete s.fill_color,delete s.color,delete s.opacity,s.screenCoordinates||(origin=renderer.worldToDisplay(origin),ul=renderer.worldToDisplay(ul),lr=renderer.worldToDisplay(lr)),m_style.id=m_this._d3id(),m_style.style=s,m_style.attributes={x:ul.x,y:ul.y,width:lr.x-origin.x,height:origin.y-ul.y},m_style.append="rect",m_style.data=[0],m_style.classes=["d3PlaneFeature"],renderer._drawFeatures(m_style),m_buildTime.modified(),m_this},this._update=function(){return s_update.call(m_this),m_this.dataTime().getMTime()>=m_buildTime.getMTime()&&m_this._build(),m_this},this._init=function(arg){return s_init.call(m_this,arg||{}),m_this.style({stroke:function(){return!1},fill:function(){return!0},fillColor:function(){return{r:.3,g:.3,b:.3}},fillOpacity:function(){return.5}}),m_this},this._init(),this},inherit(geo.d3.planeFeature,geo.planeFeature),geo.registerFeature("d3","plane",geo.d3.planeFeature),geo.d3.vectorFeature=function(arg){"use strict";function markerID(d,i){return m_this._d3id()+"_marker_"+i}function updateMarkers(data,stroke,opacity){var renderer=m_this.renderer(),sel=m_this.renderer()._definitions().selectAll("marker.geo-vector").data(data);sel.enter().append("marker").attr("id",markerID).attr("class","geo-vector").attr("viewBox","0 0 10 10").attr("refX","1").attr("refY","5").attr("markerWidth","5").attr("markerHeight","5").attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z"),sel.exit().remove(),sel.style("stroke",renderer._convertColor(stroke)).style("fill",renderer._convertColor(stroke)).style("opacity",opacity)}if(!(this instanceof geo.d3.vectorFeature))return new geo.d3.vectorFeature(arg);arg=arg||{},geo.vectorFeature.call(this,arg),geo.d3.object.call(this);var m_sticky,m_this=this,s_init=this._init,s_exit=this._exit,s_update=this._update,m_buildTime=geo.timestamp(),m_style={};return this._init=function(arg){return s_init.call(m_this,arg),m_sticky=m_this.layer().sticky(),m_this},this._build=function(){function getScale(){return scale/m_renderer.scaleFactor()}var data=m_this.data(),s_style=m_this.style.get(),m_renderer=m_this.renderer(),orig_func=m_this.origin(),size_func=m_this.delta(),cache=[],scale=m_this.style("scale"),max=Number.NEGATIVE_INFINITY;return s_update.call(m_this),data||(data=[]),cache=data.map(function(d,i){var origin=m_renderer.worldToDisplay(orig_func(d,i)),delta=size_func(d,i);return max=Math.max(max,delta.x*delta.x+delta.y*delta.y),{x1:origin.x,y1:origin.y,dx:delta.x,dy:-delta.y}}),max=Math.sqrt(max),scale||(scale=75/max),m_style.id=m_this._d3id(),m_style.data=data,m_style.append="line",m_style.attributes={x1:function(d,i){return cache[i].x1},y1:function(d,i){return cache[i].y1},x2:function(d,i){return cache[i].x1+getScale()*cache[i].dx},y2:function(d,i){return cache[i].y1+getScale()*cache[i].dy},"marker-end":function(d,i){return"url(#"+markerID(d,i)+")"}},m_style.style={stroke:function(){return!0},strokeColor:s_style.strokeColor,strokeWidth:s_style.strokeWidth,strokeOpacity:s_style.strokeOpacity},m_style.classes=["d3VectorFeature"],updateMarkers(data,s_style.strokeColor,s_style.strokeOpacity),m_this.renderer()._drawFeatures(m_style),m_buildTime.modified(),m_this.updateTime().modified(),m_this},this._update=function(){return s_update.call(m_this),m_this.getMTime()>=m_buildTime.getMTime()?m_this._build():updateMarkers(m_style.data,m_style.style.strokeColor,m_style.style.strokeOpacity),m_this},this._exit=function(){s_exit.call(m_this),m_style={},updateMarkers([],null,null)},this._init(arg),this},inherit(geo.d3.vectorFeature,geo.vectorFeature),geo.registerFeature("d3","vector",geo.d3.vectorFeature),geo.d3.d3Renderer=function(arg){"use strict";function setAttrs(select,attrs){var key;for(key in attrs)attrs.hasOwnProperty(key)&&select.attr(key,attrs[key])}function setStyles(select,styles){function fillFunc(){return styles.fill.apply(this,arguments)?null:"none"}function strokeFunc(){return styles.stroke.apply(this,arguments)?null:"none"}var key,k,f;for(key in styles)styles.hasOwnProperty(key)&&(f=null,k=null,"strokeColor"===key?(k="stroke",f=m_this._convertColor(styles[key],styles.stroke)):"stroke"===key&&styles[key]?(k="stroke",f=strokeFunc):"strokeWidth"===key?(k="stroke-width",f=m_this._convertScale(styles[key])):"strokeOpacity"===key?(k="stroke-opacity",f=styles[key]):"fillColor"===key?(k="fill",f=m_this._convertColor(styles[key],styles.fill)):"fill"!==key||styles.hasOwnProperty("fillColor")?"fillOpacity"===key&&(k="fill-opacity",f=styles[key]):(k="fill",f=fillFunc),k&&select.style(k,f))}function getMap(){var layer=m_this.layer();return layer?layer.map():null}function getGroup(){return m_svg.select(".group-"+m_this._d3id())}function initCorners(){var layer=m_this.layer(),map=layer.map(),width=m_this.layer().width(),height=m_this.layer().height();if(m_width=width,m_height=height,!m_width||!m_height)throw"Map layer has size 0";m_corners={upperLeft:map.displayToGcs({x:0,y:0}),lowerRight:map.displayToGcs({x:width,y:height})}}function setTransform(){if(m_corners||initCorners(),m_sticky){var dx,dy,scale,layer=m_this.layer(),map=layer.map(),upperLeft=map.gcsToDisplay(m_corners.upperLeft),lowerRight=map.gcsToDisplay(m_corners.lowerRight),group=getGroup();dx=upperLeft.x,dy=upperLeft.y,scale=(lowerRight.y-upperLeft.y)/m_height,group.attr("transform","matrix("+[scale,0,0,scale,dx,dy].join()+")"),m_scale=scale,m_dx=dx,m_dy=dy}}function baseToLocal(pt){return{x:(pt.x-m_dx)/m_scale,y:(pt.y-m_dy)/m_scale}}function localToBase(pt){return{x:pt.x*m_scale+m_dx,y:pt.y*m_scale+m_dy}}if(!(this instanceof geo.d3.d3Renderer))return new geo.d3.d3Renderer(arg);geo.renderer.call(this,arg);var s_exit=this._exit;geo.d3.object.call(this,arg),arg=arg||{};var m_this=this,m_sticky=null,m_features={},m_corners=null,m_width=null,m_height=null,m_scale=1,m_dx=0,m_dy=0,m_svg=null,m_defs=null;return this._convertColor=function(f,g){return f=geo.util.ensureFunction(f),g=g||function(){return!0},function(){var c="none";return g.apply(this,arguments)&&(c=f.apply(this,arguments),c.hasOwnProperty("r")&&c.hasOwnProperty("g")&&c.hasOwnProperty("b")&&(c=d3.rgb(255*c.r,255*c.g,255*c.b))),c}},this._convertPosition=function(f){return f=geo.util.ensureFunction(f),function(){return m_this.worldToDisplay(f.apply(this,arguments))}},this._convertScale=function(f){return f=geo.util.ensureFunction(f),function(){return f.apply(this,arguments)/m_scale}},this._init=function(){if(!m_this.canvas()){var canvas;m_svg=d3.select(m_this.layer().node().get(0)).append("svg"),m_defs=m_svg.append("defs");var shadow=m_defs.append("filter").attr("id","geo-highlight").attr("x","-100%").attr("y","-100%").attr("width","300%").attr("height","300%");shadow.append("feMorphology").attr("operator","dilate").attr("radius",2).attr("in","SourceAlpha").attr("result","dilateOut"),shadow.append("feGaussianBlur").attr("stdDeviation",5).attr("in","dilateOut").attr("result","blurOut"),shadow.append("feColorMatrix").attr("type","matrix").attr("values","-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0").attr("in","blurOut").attr("result","invertOut"),shadow.append("feBlend").attr("in","SourceGraphic").attr("in2","invertOut").attr("mode","normal"),canvas=m_svg.append("g"),shadow=m_defs.append("filter").attr("id","geo-blur").attr("x","-100%").attr("y","-100%").attr("width","300%").attr("height","300%"),shadow.append("feGaussianBlur").attr("stdDeviation",20).attr("in","SourceGraphic"),m_sticky=m_this.layer().sticky(),m_svg.attr("class",m_this._d3id()),m_svg.attr("width",m_this.layer().node().width()),m_svg.attr("height",m_this.layer().node().height()),canvas.attr("class","group-"+m_this._d3id()),m_this.canvas(canvas)}},this.displayToWorld=function(pt){var map=getMap();if(!map)throw"Cannot project until this layer is connected to a map.";return pt=Array.isArray(pt)?pt.map(function(x){return map.displayToGcs(localToBase(x))}):map.displayToGcs(localToBase(pt))},this.worldToDisplay=function(pt){var map=getMap();if(!map)throw"Cannot project until this layer is connected to a map.";var v;return v=Array.isArray(pt)?pt.map(function(x){return baseToLocal(map.gcsToDisplay(x))}):baseToLocal(map.gcsToDisplay(pt))},this.api=function(){return"d3"},this.scaleFactor=function(){return m_scale},this._resize=function(x,y,w,h){m_corners||initCorners(),m_svg.attr("width",w),m_svg.attr("height",h),setTransform(),m_this.layer().geoTrigger(geo.event.d3Rescale,{scale:m_scale},!0)},this._update=function(){},this._exit=function(){m_features={},m_this.canvas().remove(),s_exit()},this._definitions=function(){return m_defs},this._drawFeatures=function(arg){return m_features[arg.id]={data:arg.data,index:arg.dataIndex,style:arg.style,attributes:arg.attributes,classes:arg.classes,append:arg.append},m_this.__render(arg.id)},this.__render=function(id){var key;if(void 0===id){for(key in m_features)m_features.hasOwnProperty(key)&&m_this.__render(key);return m_this}var data=m_features[id].data,index=m_features[id].index,style=m_features[id].style,attributes=m_features[id].attributes,classes=m_features[id].classes,append=m_features[id].append,selection=m_this.select(id).data(data,index);return selection.enter().append(append),selection.exit().remove(),setAttrs(selection,attributes),selection.attr("class",classes.concat([id]).join(" ")),setStyles(selection,style),m_this},this.select=function(id){return getGroup().selectAll("."+id)},this._removeFeature=function(id){return m_this.select(id).remove(),delete m_features[id],m_this},this.draw=function(){},this.layer().geoOn(geo.event.pan,setTransform),this.layer().geoOn(geo.event.zoom,function(){setTransform(),m_this.__render(),m_this.layer().geoTrigger(geo.event.d3Rescale,{scale:m_scale},!0)}),this.layer().geoOn(geo.event.resize,function(event){m_this._resize(event.x,event.y,event.width,event.height)}),this._init(arg),this},inherit(geo.d3.d3Renderer,geo.renderer),geo.registerRenderer("d3",geo.d3.d3Renderer),geo.gui={},geo.gui.uiLayer=function(arg){"use strict";if(arg.renderer="d3",arg.sticky=!1,!(this instanceof geo.gui.uiLayer))return new geo.gui.uiLayer(arg);geo.layer.call(this,arg);var m_this=this,s_exit=this._exit;this.createWidget=function(widgetName,arg){var newWidget=geo.createWidget(widgetName,m_this,m_this.renderer(),arg);return m_this.addChild(newWidget),newWidget._init(),m_this.modified(),newWidget},this.deleteWidget=function(widget){return widget._exit(),m_this.removeChild(widget),m_this.modified(),m_this},this._exit=function(){m_this.children().forEach(function(child){m_this.deleteWidget(child)}),s_exit()}},inherit(geo.gui.uiLayer,geo.layer),geo.registerLayer("ui",geo.gui.uiLayer),geo.gui.widget=function(arg){"use strict";if(!(this instanceof geo.gui.widget))return new geo.gui.widget(arg);geo.sceneObject.call(this,arg);var m_this=this,s_exit=this._exit,m_layer=arg.layer;this._init=function(){m_this.modified()},this._exit=function(){m_this.children().forEach(function(child){m_this._deleteFeature(child)}),s_exit()},this._createFeature=function(featureName,arg){var newFeature=geo.createFeature(featureName,m_this,m_this.renderer(),arg);return m_this.addChild(newFeature),m_this.modified(),newFeature},this._deleteFeature=function(feature){return m_this.removeChild(feature),feature._exit(),m_this},this.layer=function(){return m_layer}},inherit(geo.gui.widget,geo.sceneObject),geo.gui.sliderWidget=function(arg){"use strict";function put_icon(icon,base,cx,cy,size){var g=base.append("g"),s=size/1024;return g.append("g").append("g").attr("transform","translate("+cx+","+cy+") scale("+s+") translate(-512,-512)").append("path").attr("d",icon).attr("class","geo-glyphicon"),g}if(!(this instanceof geo.gui.sliderWidget))return new geo.gui.sliderWidget(arg);
-
-geo.gui.widget.call(this,arg);var m_xscale,m_yscale,m_plus,m_minus,m_track,m_nub,m_plusIcon,m_minusIcon,m_group,m_lowContrast,m_this=this,s_exit=this._exit,m_width=20,m_height=100,m_nubSize=10,m_highlightDur=100;m_plusIcon="M512 81.92c-237.568 0-430.080 192.614-430.080 430.080 0 237.568 192.563 430.080 430.080 430.080s430.080-192.563 430.080-430.080c0-237.517-192.563-430.080-430.080-430.080zM564.326 564.326v206.182h-104.653v-206.182h-206.234v-104.653h206.182v-206.234h104.704v206.182h206.182v104.704h-206.182z",m_minusIcon="M512 81.92c-237.568 0-430.080 192.614-430.080 430.080 0 237.568 192.563 430.080 430.080 430.080s430.080-192.563 430.080-430.080c0-237.517-192.563-430.080-430.080-430.080zM770.56 459.674v104.704h-517.12v-104.704h517.12z",m_lowContrast={white:"#f4f4f4",black:"#505050"},this._init=function(){function respond(evt,trans){var z=m_yscale.invert(d3.mouse(m_this.layer().node()[0])[1]),zrange=map.zoomRange();z=(1-z)*(zrange.max-zrange.min)+zrange.min,trans?map.transition({zoom:z,ease:d3.ease("cubic-in-out"),duration:500,done:m_this._update()}):(map.zoom(z),m_this._update()),evt.stopPropagation()}var svg=m_this.layer().renderer().canvas(),x0=40,y0=40+m_width,map=m_this.layer().map();m_xscale=d3.scale.linear().domain([-4,4]).range([x0,x0+m_width]),m_yscale=d3.scale.linear().domain([0,1]).range([y0,y0+m_height]),svg=svg.append("g").classed("geo-ui-slider",!0),m_group=svg,m_plus=svg.append("g"),m_plus.append("circle").datum({fill:"white",stroke:null}).classed("geo-zoom-in",!0).attr("cx",m_xscale(0)).attr("cy",m_yscale(0)-m_width+2).attr("r",m_width/2).style({cursor:"pointer"}).on("click",function(){var z=map.zoom();map.transition({zoom:z+1,ease:d3.ease("cubic-in-out"),duration:500})}).on("mousedown",function(){d3.event.stopPropagation()}),put_icon(m_plusIcon,m_plus,m_xscale(0),m_yscale(0)-m_width+2,m_width+5).style("cursor","pointer").style("pointer-events","none").select("path").datum({fill:"black",stroke:null}),m_minus=svg.append("g"),m_minus.append("circle").datum({fill:"white",stroke:null}).classed("geo-zoom-out",!0).attr("cx",m_xscale(0)).attr("cy",m_yscale(1)+m_width-2).attr("r",m_width/2).style({cursor:"pointer"}).on("click",function(){var z=map.zoom();map.transition({zoom:z-1,ease:d3.ease("cubic-in-out"),duration:500})}).on("mousedown",function(){d3.event.stopPropagation()}),put_icon(m_minusIcon,m_minus,m_xscale(0),m_yscale(1)+m_width-2,m_width+5).style("cursor","pointer").style("pointer-events","none").select("path").datum({fill:"black",stroke:null}),m_track=svg.append("rect").datum({fill:"white",stroke:"black"}).classed("geo-zoom-track",!0).attr("x",m_xscale(0)-m_width/6).attr("y",m_yscale(0)).attr("rx",m_width/10).attr("ry",m_width/10).attr("width",m_width/3).attr("height",m_height).style({cursor:"pointer"}).on("click",function(){respond(d3.event,!0)}),m_nub=svg.append("rect").datum({fill:"black",stroke:null}).classed("geo-zoom-nub",!0).attr("x",m_xscale(-4)).attr("y",m_yscale(.5)-m_nubSize/2).attr("rx",3).attr("ry",3).attr("width",m_width).attr("height",m_nubSize).style({cursor:"pointer"}).on("mousedown",function(){d3.select(document).on("mousemove.geo.slider",function(){respond(d3.event)}),d3.select(document).on("mouseup.geo.slider",function(){respond(d3.event),d3.select(document).on(".geo.slider",null)}),d3.event.stopPropagation()});var mouseOver=function(){d3.select(this).attr("filter","url(#geo-highlight)"),m_group.selectAll("rect,path,circle").transition().duration(m_highlightDur).style("fill",function(d){return d.fill||null}).style("stroke",function(d){return d.stroke||null})},mouseOut=function(){d3.select(this).attr("filter",null),m_group.selectAll("circle,rect,path").transition().duration(m_highlightDur).style("fill",function(d){return m_lowContrast[d.fill]||null}).style("stroke",function(d){return m_lowContrast[d.stroke]||null})};m_group.selectAll("*").on("mouseover",mouseOver).on("mouseout",mouseOut),m_this.layer().geoOn(geo.event.zoom,function(){m_this._update()}),mouseOut(),m_this._update()},this._exit=function(){m_group.remove(),m_this.layer().geoOff(geo.event.zoom),s_exit()},this._update=function(obj){var map=m_this.layer().map(),zoomRange=map.zoomRange(),zoom=map.zoom(),zoomScale=d3.scale.linear();obj=obj||{},zoom=obj.value||zoom,zoomScale.domain([zoomRange.min,zoomRange.max]).range([1,0]).clamp(!0),m_nub.attr("y",m_yscale(zoomScale(zoom))-m_nubSize/2)}},inherit(geo.gui.sliderWidget,geo.gui.widget),geo.registerWidget("d3","slider",geo.gui.sliderWidget),geo.gui.legendWidget=function(arg){"use strict";if(!(this instanceof geo.gui.legendWidget))return new geo.gui.legendWidget(arg);geo.gui.widget.call(this,arg);var m_this=this,m_categories=[],m_top=null,m_group=null,m_border=null,m_spacing=20,m_padding=12;this.categories=function(arg){return void 0===arg?m_categories.slice():(m_categories=arg.slice().map(function(d){return"line"===d.type&&(d.style.fill=!1,d.style.stroke=!0),d}),m_this.draw(),m_this)},this.size=function(){var height,width=1,test=m_this.layer().renderer().canvas().append("text").style("opacity",1e-6);return m_categories.forEach(function(d){test.text(d.name),width=Math.max(width,test.node().getBBox().width)}),test.remove(),height=m_spacing*(m_categories.length+1),{width:width+50,height:height}},this.draw=function(){function applyColor(selection){selection.style("fill",function(d){return d.style.fill||void 0===d.style.fill?d.style.fillColor:"none"}).style("fill-opacity",function(d){return void 0===d.style.fillOpacity?1:d.style.fillOpacity}).style("stroke",function(d){return d.style.stroke||void 0===d.style.stroke?d.style.strokeColor:"none"}).style("stroke-opacity",function(d){return void 0===d.style.strokeOpacity?1:d.style.strokeOpacity}).style("stroke-width",function(d){return void 0===d.style.strokeWidth?1.5:d.style.strokeWidth})}m_this._init(),m_border.attr("height",m_this.size().height+2*m_padding).style("display",null);var scale=m_this._scale(),labels=m_group.selectAll("g.geo-label").data(m_categories,function(d){return d.name}),g=labels.enter().append("g").attr("class","geo-label").attr("transform",function(d,i){return"translate(0,"+scale.y(i)+")"});return applyColor(g.filter(function(d){return"point"!==d.type&&"line"!==d.type}).append("rect").attr("x",0).attr("y",-6).attr("rx",5).attr("ry",5).attr("width",40).attr("height",12)),applyColor(g.filter(function(d){return"point"===d.type}).append("circle").attr("cx",20).attr("cy",0).attr("r",6)),applyColor(g.filter(function(d){return"line"===d.type}).append("line").attr("x1",0).attr("y1",0).attr("x2",40).attr("y2",0)),g.append("text").attr("x","50px").attr("y",0).attr("dy","0.3em").text(function(d){return d.name}),m_this},this._scale=function(){return{x:d3.scale.linear().domain([0,1]).range([0,m_this.size().width]),y:d3.scale.linear().domain([0,m_categories.length-1]).range([m_padding/2,m_this.size().height-m_padding/2])}},this._init=function(){var w=m_this.size().width+2*m_padding,h=m_this.size().height+2*m_padding,nw=m_this.layer().map().node().width(),margin=20;m_top&&m_top.remove(),m_top=m_this.layer().renderer().canvas().append("g").attr("transform","translate("+(nw-w-margin)+","+margin+")"),m_group=m_top.append("g").attr("transform","translate("+[m_padding-1.5,m_padding]+")"),m_border=m_group.append("rect").attr("x",-m_padding).attr("y",-m_padding).attr("width",w).attr("height",h).attr("rx",3).attr("ry",3).style({stroke:"black","stroke-width":"1.5px",fill:"white","fill-opacity":.75,display:"none"}),m_group.on("mousedown",function(){d3.event.stopPropagation()}),m_group.on("mouseover",function(){m_border.transition().duration(250).style("fill-opacity",1)}),m_group.on("mouseout",function(){m_border.transition().duration(250).style("fill-opacity",.75)})},this.geoOn(geo.event.resize,function(){this.draw()})},inherit(geo.gui.legendWidget,geo.gui.widget),geo.registerWidget("d3","legend",geo.gui.legendWidget),function($,geo,d3){"use strict";var load=function(){function isColorKey(key){return"color"===key.slice(key.length-5,key.length).toLowerCase()}function makeColorScale(data,acc){function wrap(func){return geo.util.isFunction(func)?function(){return func(acc.apply(this,arguments))}:func(acc)}if(!d3)return console.warn("d3 is unavailable, cannot apply color scales."),acc;var domain,cannotHandle=!1,doNotHandle=!0,categorical=!1,min=Number.POSITIVE_INFINITY,max=Number.NEGATIVE_INFINITY;return domain=geo.util.isFunction(acc)?d3.set(data.map(acc)).values():[acc],domain.forEach(function(v){("string"!=typeof v||"object"!=typeof geo.util.convertColor(v))&&(doNotHandle=!1),"string"==typeof v?categorical=!0:isFinite(v)?+v>max?max=+v:min>+v&&(min=+v):cannotHandle=!0}),cannotHandle?acc:doNotHandle?acc:wrap(categorical?domain.length<=10?d3.scale.category10().domain(domain):domain.length<=20?d3.scale.category20().domain(domain):d3.scale.category20().domain(domain):d3.scale.linear().range(["rgb(252,141,89)","rgb(255,255,191)","rgb(145,191,219)"]).domain([min,(min+max)/2,max]))}if(!$.widget)return void($.fn.geojsMap=function(){throw new Error("The geojs jquery plugin requires jquery ui to be available.")});var initialized=!1;$.widget("geojs.geojsMap",{options:{center:{latitude:0,longitude:0},zoom:0,width:null,height:null,layers:[],data:[],tileUrl:"http://tile.openstreetmap.org///.png",baseLayer:"osm",baseRenderer:"vgl"},_create:function(){!this._map&&this.element.length&&(initialized&&(console.warn("Geojs already initialized in this window."),delete window.gl),initialized=!0,this._map=geo.map({width:this.options.width,height:this.options.height,zoom:this.options.zoom,center:this.options.center,node:this.element.get(0)}),this._baseLayer=this._map.createLayer(this.options.baseLayer,{renderer:this.options.baseRenderer,tileUrl:this.options.tileUrl}),this._resize({width:800,height:600}),this._layers=[],this.update())},update:function(layers){var m_this=this;return this.options.layers=layers||this.options.layers||[],this._layers.forEach(function(layer){layer.clear(),m_this._map.deleteLayer(layer)}),this._layers=this.options.layers.map(function(layer){return layer.data=layer.data||m_this.options.data,(layer.features||[]).forEach(function(feature){var scl,data=feature.data||layer.data||[];"point"===feature.type&&(feature.size?feature._size=feature.size:null===feature.size&&delete feature._size,data.length&&feature._size&&(scl=d3.scale.linear().domain(d3.extent(data,feature._size)).range([5,20]),feature.radius=function(){return scl(feature._size.apply(this,arguments))}),delete feature.size);var key;for(key in feature)feature.hasOwnProperty(key)&&isColorKey(key)&&(feature[key]=makeColorScale(data,feature[key]))}),geo.layer.create(m_this._map,layer)}),this.redraw(),this},map:function(){return this._map},tileUrl:function(url){return this._baseLayer.tileUrl(url),this._baseLayer.updateBaseUrl(),this},_resize:function(size){var width=this.options.width,height=this.options.height;size&&(width=size.width,height=size.height),width||(width=this.element.width()),height||(height=this.element.height()),this._map.resize(0,0,width,height)},redraw:function(){return this._resize(),this}})};$(load)}($||window.$,geo||window.geo,d3||window.d3);
\ No newline at end of file
+return m_this.selectionAPI()?(data=m_this.data(),data&&data.length?(map=m_this.layer().map(),pt=map.gcsToDisplay(p),min=map.displayToGcs({x:pt.x-m_maxRadius,y:pt.y+m_maxRadius}),max=map.displayToGcs({x:pt.x+m_maxRadius,y:pt.y-m_maxRadius}),box=new geo.util.Box(geo.util.vect(min.x,min.y),geo.util.vect(max.x,max.y)),m_this._updateRangeTree(),m_rangeTree.search(box).forEach(function(q){idx.push(q.idx)}),idx.forEach(function(i){var dx,dy,rad,d=data[i],p=m_this.position()(d,i);rad=radius(data[i],i),rad+=stroke(data[i],i)?strokeWidth(data[i],i):0,p=map.gcsToDisplay(p),dx=p.x-pt.x,dy=p.y-pt.y,Math.sqrt(dx*dx+dy*dy)<=rad&&(found.push(d),ifound.push(i))}),{data:found,index:ifound}):{found:[],index:[]}):[]},this.boxSearch=function(lowerLeft,upperRight){var pos=m_this.position(),idx=[];return m_this.data().forEach(function(d,i){var p=pos(d);p.x>=lowerLeft.x&&p.x<=upperRight.x&&p.y>=lowerLeft.y&&p.y<=upperRight.y&&idx.push(i)}),idx},this.data=function(data){return void 0===data?s_data():(s_data(data),m_this)},this._boundingBox=function(d){var pt,radius;return pt=m_this.position()(d),pt=m_this.layer().map().gcsToDisplay(pt),radius=m_this.style().radius(d),{min:{x:pt.x-radius,y:pt.y-radius},max:{x:pt.x+radius,y:pt.y+radius}}},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{radius:10,stroke:!0,strokeColor:{r:0,g:1,b:0},strokeWidth:2,strokeOpacity:1,fillColor:{r:1,g:0,b:0},fill:!0,fillOpacity:1,sprites:!1,sprites_image:null,position:function(d){return d}},void 0===arg.style?{}:arg.style);void 0!==arg.position&&(defaultStyle.position=arg.position),m_this.style(defaultStyle),m_this.dataTime().modified()},m_this},geo.event.pointFeature=$.extend({},geo.event.feature),geo.pointFeature.create=function(layer,renderer,spec){"use strict";return spec.type="point",geo.feature.create(layer,spec)},inherit(geo.pointFeature,geo.feature),geo.lineFeature=function(arg){"use strict";if(!(this instanceof geo.lineFeature))return new geo.lineFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,s_init=this._init;return this.line=function(val){return void 0===val?m_this.style("line"):(m_this.style("line",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this.position=function(val){return void 0===val?m_this.style("position"):(m_this.style("position",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this.pointSearch=function(p){function lineDist2(q,u,v){var t,l2=dist2(u,v);return 1>l2?dist2(q,u):(t=((q.x-u.x)*(v.x-u.x)+(q.y-u.y)*(v.y-u.y))/l2,0>t?dist2(q,u):t>1?dist2(q,v):dist2(q,{x:u.x+t*(v.x-u.x),y:u.y+t*(v.y-u.y)}))}function dist2(u,v){var dx=u.x-v.x,dy=u.y-v.y;return dx*dx+dy*dy}var data,pt,map,line,width,pos,indices=[],found=[];return data=m_this.data(),data&&data.length?(map=m_this.layer().map(),line=m_this.line(),width=m_this.style.get("strokeWidth"),pos=m_this.position(),pt=map.gcsToDisplay(p),data.forEach(function(d,index){var last=null;try{line(d,index).forEach(function(current,j){var p=pos(current,j,d,index),s=map.gcsToDisplay(p),r=Math.ceil(width(p,j,d,index)/2)+2;if(r*=r,last&&lineDist2(pt,s,last)<=r)throw"found";last=s})}catch(err){if("found"!==err)throw err;found.push(d),indices.push(index)}}),{data:found,index:indices}):{found:[],index:[]}},this.boxSearch=function(lowerLeft,upperRight,opts){var pos=m_this.position(),idx=[],line=m_this.line();if(opts=opts||{},opts.partial=opts.partial||!1,opts.partial)throw"Unimplemented query method.";return m_this.data().forEach(function(d,i){var inside=!0;line(d,i).forEach(function(e,j){if(inside){var p=pos(e,j,d,i);p.x>=lowerLeft.x&&p.x<=upperRight.x&&p.y>=lowerLeft.y&&p.y<=upperRight.y||(inside=!1)}}),inside&&idx.push(i)}),idx},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{strokeWidth:1,strokeColor:{r:1,g:.8431372549,b:0},strokeStyle:"solid",strokeOpacity:1,line:function(d){return d},position:function(d){return d}},void 0===arg.style?{}:arg.style);void 0!==arg.line&&(defaultStyle.line=arg.line),void 0!==arg.position&&(defaultStyle.position=arg.position),m_this.style(defaultStyle),m_this.dataTime().modified()},this._init(arg),this},geo.lineFeature.create=function(layer,spec){"use strict";return spec.type="line",geo.feature.create(layer,spec)},inherit(geo.lineFeature,geo.feature),geo.pathFeature=function(arg){"use strict";if(!(this instanceof geo.pathFeature))return new geo.pathFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,m_position=void 0===arg.position?[]:arg.position,s_init=this._init;return this.position=function(val){return void 0===val?m_position:(m_position=val,m_this.dataTime().modified(),m_this.modified(),m_this)},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{strokeWidth:function(){return 1},strokeColor:function(){return{r:1,g:1,b:1}}},void 0===arg.style?{}:arg.style);m_this.style(defaultStyle),m_position&&m_this.dataTime().modified()},this._init(arg),this},inherit(geo.pathFeature,geo.feature),geo.polygonFeature=function(arg){"use strict";function getCoordinates(){var posFunc=m_this.position(),polyFunc=m_this.polygon();m_coordinates=m_this.data().map(function(d,i){var outer,inner,poly=polyFunc(d);return outer=(poly.outer||[]).map(function(d0,j){return posFunc.call(m_this,d0,j,d,i)}),inner=(poly.inner||[]).map(function(hole){return(hole||[]).map(function(d0,k){return posFunc.call(m_this,d0,k,d,i)})}),{outer:outer,inner:inner}})}if(!(this instanceof geo.polygonFeature))return new geo.polygonFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_position,m_polygon,m_this=this,s_init=this._init,s_data=this.data,m_coordinates={outer:[],inner:[]};return m_polygon=void 0===arg.line?function(d){return d}:arg.polygon,m_position=void 0===arg.position?function(d){return d}:arg.position,this.data=function(arg){var ret=s_data(arg);return void 0!==arg&&getCoordinates(),ret},this.polygon=function(val){return void 0===val?m_polygon:(m_polygon=val,m_this.dataTime().modified(),m_this.modified(),getCoordinates(),m_this)},this.position=function(val){return void 0===val?m_position:(m_position=val,m_this.dataTime().modified(),m_this.modified(),getCoordinates(),m_this)},this.pointSearch=function(coordinate){var found=[],indices=[],data=m_this.data();return m_coordinates.forEach(function(coord,i){var inside=geo.util.pointInPolygon(coordinate,coord.outer,coord.inner);inside&&(indices.push(i),found.push(data[i]))}),{index:indices,found:found}},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{fillColor:{r:0,g:.5,b:.5},fillOpacity:1},void 0===arg.style?{}:arg.style);m_this.style(defaultStyle),m_position&&m_this.dataTime().modified()},this._init(arg),this},inherit(geo.polygonFeature,geo.feature),geo.planeFeature=function(arg){"use strict";if(!(this instanceof geo.planeFeature))return new geo.planeFeature(arg);arg=arg||{},arg.ul=void 0===arg.ul?[0,1,0]:arg.ul,arg.lr=void 0===arg.lr?[1,0,0]:arg.lr,arg.depth=void 0===arg.depth?0:arg.depth,geo.polygonFeature.call(this,arg);var m_this=this,m_origin=[arg.ul.x,arg.lr.y,arg.depth],m_upperLeft=[arg.ul.x,arg.ul.y,arg.depth],m_lowerRight=[arg.lr.x,arg.lr.y,arg.depth],m_defaultDepth=arg.depth,m_drawOnAsyncResourceLoad=void 0===arg.drawOnAsyncResourceLoad?!0:!1,s_init=this._init;return this.origin=function(val){if(void 0===val)return m_origin;if(val instanceof Array){if(val.length>3||val.length<2)throw"Upper left point requires point in 2 or 3 dimension";m_origin=val.slice(0),2===m_origin.length&&(m_origin[2]=m_defaultDepth)}else val instanceof geo.latlng&&(m_origin=[val.x(),val.y(),m_defaultDepth]);return m_this.dataTime().modified(),m_this.modified(),m_this},this.upperLeft=function(val){if(void 0===val)return m_upperLeft;if(val instanceof Array){if(val.length>3||val.length<2)throw"Upper left point requires point in 2 or 3 dimension";m_upperLeft=val.slice(0),2===m_upperLeft.length&&(m_upperLeft[2]=m_defaultDepth)}else val instanceof geo.latlng&&(m_upperLeft=[val.x(),val.y(),m_defaultDepth]);return m_this.dataTime().modified(),m_this.modified(),m_this},this.lowerRight=function(val){if(void 0===val)return m_lowerRight;if(val instanceof Array){if(val.length>3||val.length<2)throw"Upper left point requires point in 2 or 3 dimension";m_lowerRight=val.slice(0),2===m_lowerRight.length&&(m_lowerRight[2]=m_defaultDepth),m_this.dataTime().modified()}else val instanceof geo.latlng&&(m_lowerRight=[val.x(),val.y(),m_defaultDepth]);return m_this.dataTime().modified(),m_this.modified(),m_this},this.drawOnAsyncResourceLoad=function(val){return void 0===val?m_drawOnAsyncResourceLoad:(m_drawOnAsyncResourceLoad=val,m_this)},this._init=function(arg){var style=null;s_init.call(m_this,arg),style=m_this.style(),void 0===style.image&&(style.image=null),m_this.style(style)},this._init(arg),this},inherit(geo.planeFeature,geo.polygonFeature),geo.vectorFeature=function(arg){"use strict";if(!(this instanceof geo.vectorFeature))return new geo.vectorFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,s_init=this._init,s_style=this.style;this.origin=function(val){return void 0===val?s_style("origin"):(s_style("origin",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this.delta=function(val){return void 0===val?s_style("delta"):(s_style("delta",val),m_this.dataTime().modified(),m_this.modified(),m_this)},this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend({},{strokeColor:"black",strokeWidth:2,strokeOpacity:1,origin:{x:0,y:0,z:0},delta:function(d){return d},scale:null},void 0===arg.style?{}:arg.style);void 0!==arg.origin&&(defaultStyle.origin=arg.origin),m_this.style(defaultStyle),m_this.dataTime().modified()}},inherit(geo.vectorFeature,geo.feature),geo.geomFeature=function(arg){"use strict";return this instanceof geo.geomFeature?(arg=arg||{},geo.feature.call(this,arg),arg.style=void 0===arg.style?$.extend({},{color:[1,1,1],point_sprites:!1,point_sprites_image:null},arg.style):arg.style,this.style(arg.style),this):new geo.geomFeature(arg)},inherit(geo.geomFeature,geo.feature),geo.graphFeature=function(arg){"use strict";if(!(this instanceof geo.graphFeature))return new geo.graphFeature(arg);arg=arg||{},geo.feature.call(this,arg);var m_this=this,s_draw=this.draw,s_style=this.style,m_nodes=null,m_points=null,m_children=function(d){return d.children},m_links=[],s_init=this._init,s_exit=this._exit;return this._init=function(arg){s_init.call(m_this,arg);var defaultStyle=$.extend(!0,{},{nodes:{radius:5,fill:!0,fillColor:{r:1,g:0,b:0},strokeColor:{r:0,g:0,b:0}},links:{strokeColor:{r:0,g:0,b:0}},linkType:"path"},void 0===arg.style?{}:arg.style);m_this.style(defaultStyle),m_this.nodes(function(d){return d})},this._build=function(){m_this.children().forEach(function(child){child._build()})},this._update=function(){m_this.children().forEach(function(child){child._update()})},this._exit=function(){return m_this.data([]),m_links.forEach(function(link){link._exit(),m_this.removeChild(link)}),m_links=[],m_points._exit(),m_this.removeChild(m_points),s_exit(),m_this},this.style=function(arg,arg2){var out=s_style.call(m_this,arg,arg2);return out!==m_this?out:(m_points.style(arg.nodes),m_links.forEach(function(l){l.style(arg.links)}),m_this)},this.links=function(arg){return void 0===arg?m_children:(m_children=geo.util.ensureFunction(arg),m_this)},this.nodes=function(val){return void 0===val?m_nodes:(m_nodes=val,m_this.modified(),m_this)},this.nodeFeature=function(){return m_points},this.linkFeatures=function(){return m_links},this.draw=function(){var style,layer=m_this.layer(),data=m_this.data(),nLinks=0;return style=m_this.style(),m_points.data(data),m_points.style(style.nodes),data.forEach(function(source){(source.children||[]).forEach(function(target){var link;nLinks+=1,m_links.length0&&inPos[0]instanceof geo.latlng?(noOfComponents=2,pointOffset=1):(noOfComponents=count%2===0?2:count%3===0?3:null,pointOffset=noOfComponents),2!==noOfComponents&&3!==noOfComponents)throw"Transform points require points in 2D or 3D";for(outPos=inplace?inPos:inPos.slice(0),i=0;count>i;i+=pointOffset)yCoord=inPos[i]instanceof geo.latlng?inPos[i].lat():inPos[i+1],yCoord>85.0511&&(yCoord=85.0511),-85.0511>yCoord&&(yCoord=-85.0511),inPos[i]instanceof geo.latlng?outPos[i]=geo.latlng(geo.mercator.lat2y(yCoord),outPos[i].lng()):outPos[i+1]=geo.mercator.lat2y(yCoord);return inplace&&(feature.positions(outPos),feature.gcs(destGcs)),outPos}return null}},geo.transform.transformFeature=function(destGcs,feature,inplace){"use strict";if(!feature)throw"Invalid (null) feature";if(!(feature instanceof geo.pointFeature||feature instanceof geo.lineFeature))throw"Supports only point or line feature";if(feature.gcs()===destGcs)return feature.positions();if("EPSG:3857"===destGcs)return geo.transform.osmTransformFeature(destGcs,feature,inplace);var i,noOfComponents=null,pointOffset=0,count=null,inPos=null,outPos=null,projPoint=null,srcGcs=feature.gcs(),projSrcGcs=new proj4.Proj(srcGcs),projDestGcs=new proj4.Proj(destGcs);if(inplace=!!inplace,feature instanceof geo.pointFeature||feature instanceof geo.lineFeature){if(inPos=feature.positions(),count=inPos.length,!(inPos instanceof Array))throw"Supports Array of 2D and 3D points";if(inPos.length>0&&inPos[0]instanceof geo.latlng?(noOfComponents=2,pointOffset=1):(noOfComponents=count%2===0?2:count%3===0?3:null,pointOffset=noOfComponents),2!==noOfComponents&&3!==noOfComponents)throw"Transform points require points in 2D or 3D";for(inplace?outPos=inPos:(outPos=[],outPos.length=inPos.length),i=0;count>i;i+=pointOffset)projPoint=2===noOfComponents?new proj4.Point(inPos[i],inPos[i+1],0):new proj4.Point(inPos[i],inPos[i+1],inPos[i+2]),proj4.transform(projSrcGcs,projDestGcs,projPoint),2===noOfComponents?(outPos[i]=projPoint.x,outPos[i+1]=projPoint.y):(outPos[i]=projPoint.x,outPos[i+1]=projPoint.y,outPos[i+2]=projPoint.z);return inplace&&(feature.positions(outPos),feature.gcs(destGcs)),outPos}return null},geo.transform.transformLayer=function(destGcs,layer,baseLayer){"use strict";var features,count,i;if(!layer)throw"Requires valid layer for tranformation";if(!baseLayer)throw"Requires baseLayer used by the map";if(layer!==baseLayer){if(!(layer instanceof geo.featureLayer))throw"Only feature layer transformation is supported";for(features=layer.features(),count=features.length,i=0,i=0;count>i;i+=1)"EPSG:3857"===destGcs&&baseLayer instanceof geo.osmLayer?geo.transform.osmTransformFeature(destGcs,features[i],!0):geo.transform.transformFeature(destGcs,features[i],!0);layer.gcs(destGcs)}},geo.transform.transformCoordinates=function(srcGcs,destGcs,coordinates,numberOfComponents){"use strict";function handleLatLngCoordinates(){coordinates[0]&&coordinates[0]instanceof geo.latlng?(xAcc=function(index){return coordinates[index].x()},yAcc=function(index){return coordinates[index].y()},writer=function(index,x,y){output[index]=geo.latlng(y,x)}):(xAcc=function(){return coordinates.x()},yAcc=function(){return coordinates.y()},writer=function(index,x,y){output=geo.latlng(y,x)})}function handleArrayCoordinates(){if(coordinates[0]instanceof Array)if(2===coordinates[0].length)xAcc=function(index){return coordinates[index][0]},yAcc=function(index){return coordinates[index][1]},writer=function(index,x,y){output[index]=[x,y]};else{if(3!==coordinates[0].length)throw"Invalid coordinates. Requires two or three components per array";xAcc=function(index){return coordinates[index][0]},yAcc=function(index){return coordinates[index][1]},zAcc=function(index){return coordinates[index][2]},writer=function(index,x,y,z){output[index]=[x,y,z]}}else if(2===coordinates.length)offset=2,xAcc=function(index){return coordinates[index*offset]},yAcc=function(index){return coordinates[index*offset+1]},writer=function(index,x,y){output[index]=x,output[index+1]=y};else if(3===coordinates.length)offset=3,xAcc=function(index){return coordinates[index*offset]},yAcc=function(index){return coordinates[index*offset+1]},zAcc=function(index){return coordinates[index*offset+2]},writer=function(index,x,y,z){output[index]=x,output[index+1]=y,output[index+2]=z};else{if(!numberOfComponents)throw"Invalid coordinates";offset=numberOfComponents,xAcc=function(index){return coordinates[index]},yAcc=function(index){return coordinates[index+1]},2===numberOfComponents?writer=function(index,x,y){output[index]=x,output[index+1]=y}:(zAcc=function(index){return coordinates[index+2]},writer=function(index,x,y,z){output[index]=x,output[index+1]=y,output[index+2]=z})}}function handleObjectCoordinates(){if(coordinates[0]&&"x"in coordinates[0]&&"y"in coordinates[0])xAcc=function(index){return coordinates[index].x},yAcc=function(index){return coordinates[index].y},"z"in coordinates[0]?(zAcc=function(index){return coordinates[index].z},writer=function(index,x,y,z){output[i]={x:x,y:y,z:z}}):writer=function(index,x,y){output[index]={x:x,y:y}};else{if(!(coordinates&&"x"in coordinates&&"y"in coordinates))throw"Invalid coordinates";xAcc=function(){return coordinates.x},yAcc=function(){return coordinates.y},"z"in coordinates?(zAcc=function(){return coordinates.z},writer=function(index,x,y,z){output={x:x,y:y,z:z}}):writer=function(index,x,y){output={x:x,y:y}}}}var i,count,offset,xCoord,yCoord,zCoord,xAcc,yAcc,zAcc,writer,output,projPoint,projSrcGcs=new proj4.Proj(srcGcs),projDestGcs=new proj4.Proj(destGcs);if(zAcc=function(){return 0},destGcs===srcGcs)return coordinates;if(!destGcs||!srcGcs)throw"Invalid source or destination GCS";if(coordinates instanceof Array)output=[],output.length=coordinates.length,count=coordinates.length,coordinates[0]instanceof Array||coordinates[0]instanceof geo.latlng||coordinates[0]instanceof Object?(offset=1,coordinates[0]instanceof Array?handleArrayCoordinates():coordinates[0]instanceof geo.latlng?handleLatLngCoordinates():coordinates[0]instanceof Object&&handleObjectCoordinates()):handleArrayCoordinates();else if(coordinates&&coordinates instanceof Object)if(count=1,offset=1,coordinates instanceof geo.latlng)handleLatLngCoordinates();else{if(!(coordinates&&"x"in coordinates&&"y"in coordinates))throw"Coordinates are not valid";handleObjectCoordinates()}if("EPSG:3857"===destGcs&&"EPSG:4326"===srcGcs){for(i=0;count>i;i+=offset)xCoord=xAcc(i),yCoord=yAcc(i),zCoord=zAcc(i),yCoord>85.0511&&(yCoord=85.0511),-85.0511>yCoord&&(yCoord=-85.0511),writer(i,xCoord,geo.mercator.lat2y(yCoord),zCoord);return output}for(i=0;count>i;i+=offset)return projPoint=new proj4.Point(xAcc(i),yAcc(i),zAcc(i)),proj4.transform(projSrcGcs,projDestGcs,projPoint),writer(i,projPoint.x,projPoint.y,projPoint.z),output},geo.renderer=function(arg){"use strict";if(!(this instanceof geo.renderer))return new geo.renderer(arg);geo.object.call(this),arg=arg||{};var m_this=this,m_layer=void 0===arg.layer?null:arg.layer,m_canvas=void 0===arg.canvas?null:arg.canvas,m_initialized=!1;return this.layer=function(){return m_layer},this.canvas=function(val){return void 0===val?m_canvas:(m_canvas=val,void m_this.modified())},this.map=function(){return m_layer?m_layer.map():null},this.baseLayer=function(){return m_this.map()?m_this.map().baseLayer():void 0},this.initialized=function(val){return void 0===val?m_initialized:(m_initialized=val,m_this)},this.api=function(){throw"Should be implemented by derivied classes"},this.reset=function(){return!0},this.worldToGcs=function(){throw"Should be implemented by derivied classes"},this.displayToGcs=function(){throw"Should be implemented by derivied classes"},this.gcsToDisplay=function(){throw"Should be implemented by derivied classes"},this.worldToDisplay=function(){throw"Should be implemented by derivied classes"},this.displayToWorld=function(){throw"Should be implemented by derivied classes"},this.relMouseCoords=function(event){var totalOffsetX=0,totalOffsetY=0,canvasX=0,canvasY=0,currentElement=m_this.canvas();do totalOffsetX+=currentElement.offsetLeft-currentElement.scrollLeft,totalOffsetY+=currentElement.offsetTop-currentElement.scrollTop,currentElement=currentElement.offsetParent;while(currentElement);return canvasX=event.pageX-totalOffsetX,canvasY=event.pageY-totalOffsetY,{x:canvasX,y:canvasY}},this._init=function(){},this._resize=function(){},this._render=function(){},this},inherit(geo.renderer,geo.object),geo.osmLayer=function(arg){"use strict";function isTileVisible(tile){return tile.zoom in m_visibleTilesRange&&tile.index_x>=m_visibleTilesRange[tile.zoom].startX&&tile.index_x<=m_visibleTilesRange[tile.zoom].endX&&tile.index_y>=m_visibleTilesRange[tile.zoom].startY&&tile.index_y<=m_visibleTilesRange[tile.zoom].endY?!0:!1}function drawTiles(){m_this._removeTiles(),m_this.draw(),delete m_pendingNewTilesStat[m_updateTimerId]}function updateOSMTiles(request){void 0===request&&(request={}),m_zoom||(m_zoom=m_this.map().zoom()),m_lastVisibleZoom||(m_lastVisibleZoom=m_zoom),m_this._addTiles(request),m_lastVisibleZoom!==m_zoom&&(m_lastVisibleZoom=m_zoom),m_this.updateTime().modified()}if(!(this instanceof geo.osmLayer))return new geo.osmLayer(arg);geo.featureLayer.call(this,arg);var m_tileUrl,m_tileUrlFromTemplate,m_this=this,s_exit=this._exit,m_tiles={},m_hiddenBinNumber=-1,m_lastVisibleBinNumber=-1,m_visibleBinNumber=1e3,m_pendingNewTiles=[],m_pendingInactiveTiles=[],m_numberOfCachedTiles=0,m_tileCacheSize=100,m_baseUrl="http://tile.openstreetmap.org/",m_mapOpacity=1,m_imageFormat="png",m_updateTimerId=null,m_lastVisibleZoom=null,m_visibleTilesRange={},s_init=this._init,m_pendingNewTilesStat={},s_update=this._update,m_updateDefer=null,m_zoom=null;return arg&&void 0!==arg.baseUrl&&(m_baseUrl=arg.baseUrl),"/"!==m_baseUrl.charAt(m_baseUrl.length-1)&&(m_baseUrl+="/"),arg&&void 0!==arg.mapOpacity&&(m_mapOpacity=arg.mapOpacity),arg&&void 0!==arg.imageFormat&&(m_imageFormat=arg.imageFormat),arg&&void 0!==arg.displayLast&&arg.displayLast&&(m_lastVisibleBinNumber=999),m_tileUrl=function(zoom,x,y){return m_baseUrl+zoom+"/"+x+"/"+y+"."+m_imageFormat},m_tileUrlFromTemplate=function(base){return function(zoom,x,y){return base.replace("",zoom).replace("",x).replace("",y)}},this.tileCacheSize=function(val){return void 0===val?m_tileCacheSize:(m_tileCacheSize=val,void m_this.modified())},this.tileUrl=function(val){return void 0===val?m_tileUrl:(m_tileUrl="string"==typeof val?m_tileUrlFromTemplate(val):val,m_this.modified(),m_this)},this.toLocal=function(input){var i,output,delta;if(input instanceof Array&&input.length>0)if(output=[],output.length=input.length,input[0]instanceof geo.latlng)for(i=0;i=2&&(output=input.slice(0),output[1]=geo.mercator.lat2y(input[1]));else input instanceof geo.latlng?(output={},output.x=input.x(),output.y=geo.mercator.lat2y(input.y())):(output={},output.x=input.x,output.y=geo.mercator.lat2y(input.y));return output},this.fromLocal=function(input){var i,output;if(input instanceof Array&&input.length>0)if(output=[],output.length=input.length,input[0]instanceof Object)for(i=0;im_tileCacheSize&&i=m_pendingNewTilesStat[m_updateTimerId].total&&drawTiles(),defer.resolve())}}var feature,lastStartX,lastStartY,lastEndX,lastEndY,currStartX,currStartY,currEndX,currEndY,distWorldDeltaPerTile,ren=m_this.renderer(),llx=0,lly=m_this.height(),urx=m_this.width(),ury=0,temp=null,tile=null,tile1x=null,tile1y=null,tile2x=null,tile2y=null,invJ=null,i=0,j=0,worldPt1=ren.displayToWorld([llx,lly]),worldPt2=ren.displayToWorld([urx,ury]),worldDeltaY=null,displayDeltaY=null,worldDelta=null,displayDelta=null,noOfTilesRequired=null,worldDeltaPerTile=null,minDistWorldDeltaPerTile=null;for(worldPt1[0]=Math.max(worldPt1[0],-180),worldPt1[0]=Math.min(worldPt1[0],180),worldPt1[1]=Math.max(worldPt1[1],-180),worldPt1[1]=Math.min(worldPt1[1],180),worldPt2[0]=Math.max(worldPt2[0],-180),worldPt2[0]=Math.min(worldPt2[0],180),worldPt2[1]=Math.max(worldPt2[1],-180),worldPt2[1]=Math.min(worldPt2[1],180),worldDelta=Math.abs(worldPt2[0]-worldPt1[0]),worldDeltaY=Math.abs(worldPt2[1]-worldPt1[1]),displayDelta=urx-llx,displayDeltaY=lly-ury,displayDeltaY>displayDelta&&(displayDelta=displayDeltaY,worldDelta=worldDeltaY),noOfTilesRequired=Math.round(displayDelta/256),worldDeltaPerTile=worldDelta/noOfTilesRequired,minDistWorldDeltaPerTile=Number.POSITIVE_INFINITY,i=20;i>=2;i-=1)distWorldDeltaPerTile=Math.abs(360/Math.pow(2,i)-worldDeltaPerTile),minDistWorldDeltaPerTile>distWorldDeltaPerTile&&(minDistWorldDeltaPerTile=distWorldDeltaPerTile,m_zoom=i);for(tile1x=geo.mercator.long2tilex(worldPt1[0],m_zoom),tile1y=geo.mercator.lat2tiley(worldPt1[1],m_zoom),tile2x=geo.mercator.long2tilex(worldPt2[0],m_zoom),tile2y=geo.mercator.lat2tiley(worldPt2[1],m_zoom),tile1x=Math.max(tile1x,0),tile1x=Math.min(Math.pow(2,m_zoom)-1,tile1x),tile1y=Math.max(tile1y,0),tile1y=Math.min(Math.pow(2,m_zoom)-1,tile1y),tile2x=Math.max(tile2x,0),tile2x=Math.min(Math.pow(2,m_zoom)-1,tile2x),tile2y=Math.max(tile2y,0),tile2y=Math.min(Math.pow(2,m_zoom)-1,tile2y),tile1x>tile2x&&(temp=tile1x,tile1x=tile2x,tile2x=temp),tile2y>tile1y&&(temp=tile1y,tile1y=tile2y,tile2y=temp),currStartX=tile1x,currEndX=tile2x,currStartY=Math.pow(2,m_zoom)-1-tile1y,currEndY=Math.pow(2,m_zoom)-1-tile2y,currStartY>currEndY&&(temp=currStartY,currStartY=currEndY,currEndY=temp),lastStartX=geo.mercator.long2tilex(worldPt1[0],m_lastVisibleZoom),lastStartY=geo.mercator.lat2tiley(worldPt1[1],m_lastVisibleZoom),lastEndX=geo.mercator.long2tilex(worldPt2[0],m_lastVisibleZoom),lastEndY=geo.mercator.lat2tiley(worldPt2[1],m_lastVisibleZoom),lastStartY=Math.pow(2,m_lastVisibleZoom)-1-lastStartY,lastEndY=Math.pow(2,m_lastVisibleZoom)-1-lastEndY,lastStartY>lastEndY&&(temp=lastStartY,lastStartY=lastEndY,lastEndY=temp),m_visibleTilesRange={},m_visibleTilesRange[m_zoom]={startX:currStartX,endX:currEndX,startY:currStartY,endY:currEndY},m_visibleTilesRange[m_lastVisibleZoom]={startX:lastStartX,endX:lastEndX,startY:lastStartY,endY:lastEndY},m_pendingNewTilesStat[m_updateTimerId]={total:(tile2x-tile1x+1)*(tile1y-tile2y+1),count:0},i=tile1x;tile2x>=i;i+=1)for(j=tile2y;tile1y>=j;j+=1)invJ=Math.pow(2,m_zoom)-1-j,m_this._hasTile(m_zoom,i,invJ)?(tile=m_tiles[m_zoom][i][invJ],tile.feature.bin(m_visibleBinNumber),tile.LOADED&&m_updateTimerId in m_pendingNewTilesStat&&(m_pendingNewTilesStat[m_updateTimerId].count+=1),tile.lastused=new Date,tile.feature._update()):tile=m_this._addTile(request,m_zoom,i,invJ),tile.updateTimerId=m_updateTimerId;for(i=0;i=m_pendingNewTilesStat[m_updateTimerId].total&&drawTiles()},this._updateTiles=function(request){var defer=$.Deferred();return m_this.addDeferred(defer),null!==m_updateTimerId?(clearTimeout(m_updateTimerId),m_updateDefer.resolve(),m_updateDefer=defer,m_updateTimerId in m_pendingNewTilesStat&&delete m_pendingNewTilesStat[m_updateTimerId],m_updateTimerId=setTimeout(function(){updateOSMTiles(request),m_updateDefer.resolve()},100)):(m_updateDefer=defer,
+m_updateTimerId=setTimeout(function(){updateOSMTiles(request),m_updateDefer.resolve()},0)),m_this},this._init=function(){return s_init.call(m_this),m_this.gcs("EPSG:3857"),m_this.map().zoomRange({min:0,max:18}),m_this},this._update=function(request){m_this._updateTiles(request),s_update.call(m_this,request)},this.updateBaseUrl=function(baseUrl){if(baseUrl&&"/"!==baseUrl.charAt(m_baseUrl.length-1)&&(baseUrl+="/"),baseUrl!==m_baseUrl){void 0!==baseUrl&&(m_baseUrl=baseUrl);var tile,x,y,zoom;for(zoom in m_tiles)for(x in m_tiles[zoom])for(y in m_tiles[zoom][x])tile=m_tiles[zoom][x][y],tile.INVALID=!0,m_this.deleteFeature(tile.feature);m_tiles={},m_pendingNewTiles=[],m_pendingInactiveTiles=[],m_numberOfCachedTiles=0,m_visibleTilesRange={},m_pendingNewTilesStat={},null!==m_updateTimerId&&(clearTimeout(m_updateTimerId),m_updateTimerId=null),this._update()}},this.mapOpacity=function(val){if(void 0===val)return m_mapOpacity;if(val!==m_mapOpacity){m_mapOpacity=val;var zoom,x,y,tile;for(zoom in m_tiles)for(x in m_tiles[zoom])for(y in m_tiles[zoom][x])tile=m_tiles[zoom][x][y],tile.feature.style().opacity=val,tile.feature._update();m_this.modified()}return m_this},this._exit=function(){m_tiles={},m_pendingNewTiles=[],m_pendingInactiveTiles=[],m_numberOfCachedTiles=0,m_visibleTilesRange={},m_pendingNewTilesStat={},s_exit()},arg&&void 0!==arg.tileUrl&&this.tileUrl(arg.tileUrl),this},inherit(geo.osmLayer,geo.featureLayer),geo.registerLayer("osm",geo.osmLayer),geo.gl={},geo.gl.renderer=function(arg){"use strict";return this instanceof geo.gl.renderer?(geo.renderer.call(this,arg),this.contextRenderer=function(){throw"Should be implemented by derived classes"},this):new geo.gl.renderer(arg)},inherit(geo.gl.renderer,geo.renderer),geo.gl.lineFeature=function(arg){"use strict";function createVertexShader(){var vertexShaderSource=["#ifdef GL_ES"," precision highp float;","#endif","attribute vec3 pos;","attribute vec3 prev;","attribute vec3 next;","attribute float offset;","attribute vec3 strokeColor;","attribute float strokeOpacity;","attribute float strokeWidth;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float pixelWidth;","uniform float aspect;","varying vec3 strokeColorVar;","varying float strokeWidthVar;","varying float strokeOpacityVar;","void main(void)","{"," if (strokeOpacity < 0.0) {"," gl_Position = vec4(2, 2, 0, 1);"," return;"," }"," const float PI = 3.14159265358979323846264;"," vec4 worldPos = projectionMatrix * modelViewMatrix * vec4(pos.xyz, 1);"," if (worldPos.w != 0.0) {"," worldPos = worldPos/worldPos.w;"," }"," vec4 worldNext = projectionMatrix * modelViewMatrix * vec4(next.xyz, 1);"," if (worldNext.w != 0.0) {"," worldNext = worldNext/worldNext.w;"," }"," vec4 worldPrev = projectionMatrix* modelViewMatrix * vec4(prev.xyz, 1);"," if (worldPrev.w != 0.0) {"," worldPrev = worldPrev/worldPrev.w;"," }"," strokeColorVar = strokeColor;"," strokeWidthVar = strokeWidth;"," strokeOpacityVar = strokeOpacity;"," vec2 deltaNext = worldNext.xy - worldPos.xy;"," vec2 deltaPrev = worldPos.xy - worldPrev.xy;"," float angleNext = 0.0, anglePrev = 0.0;"," if (deltaNext.xy != vec2(0.0, 0.0))"," angleNext = atan(deltaNext.y / aspect, deltaNext.x);"," if (deltaPrev.xy == vec2(0.0, 0.0)) anglePrev = angleNext;"," else anglePrev = atan(deltaPrev.y / aspect, deltaPrev.x);"," if (deltaNext.xy == vec2(0.0, 0.0)) angleNext = anglePrev;"," float angle = (anglePrev + angleNext) / 2.0;"," float cosAngle = cos(anglePrev - angle);"," if (cosAngle < 0.1) { cosAngle = sign(cosAngle) * 1.0; angle = 0.0; }"," float distance = (offset * strokeWidth * pixelWidth) /"," cosAngle;"," worldPos.x += distance * sin(angle);"," worldPos.y -= distance * cos(angle) * aspect;"," gl_Position = worldPos;","}"].join("\n"),shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader}function createFragmentShader(){var fragmentShaderSource=["#ifdef GL_ES"," precision highp float;","#endif","varying vec3 strokeColorVar;","varying float strokeWidthVar;","varying float strokeOpacityVar;","void main () {"," gl_FragColor = vec4 (strokeColorVar, strokeOpacityVar);","}"].join("\n"),shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader}function createGLLines(){var i,j,k,v,len,lineItem,lineItemData,vertTemp,pos,posIdx3,posBuf,nextBuf,prevBuf,offsetBuf,indicesBuf,strokeWidthBuf,strokeColorBuf,strokeOpacityBuf,dest,dest3,data=m_this.data(),numSegments=0,vert=[{},{}],position=[],posFunc=m_this.position(),strkWidthFunc=m_this.style.get("strokeWidth"),strkColorFunc=m_this.style.get("strokeColor"),strkOpacityFunc=m_this.style.get("strokeOpacity"),order=m_this.featureVertices(),geom=m_mapper.geometryData();for(i=0;i=m_this.buildTime().getMTime()||m_this.updateTime().getMTime()<=m_this.getMTime())&&m_this._build(),m_pixelWidthUnif.set(1/m_this.renderer().width()),m_aspectUniform.set(m_this.renderer().width()/m_this.renderer().height()),m_actor.setVisible(m_this.visible()),m_actor.material().setBinNumber(m_this.bin()),m_this.updateTime().modified()},this._exit=function(){m_this.renderer().contextRenderer().removeActor(m_actor),s_exit()},this._init(arg),this},inherit(geo.gl.lineFeature,geo.lineFeature),geo.registerFeature("vgl","line",geo.gl.lineFeature),geo.gl.pointFeature=function(arg){"use strict";function createVertexShader(){var shader=new vgl.shader(gl.VERTEX_SHADER);return shader.setShaderSource(vertexShaderSource),shader}function createFragmentShader(){var shader=new vgl.shader(gl.FRAGMENT_SHADER);return shader.setShaderSource(fragmentShaderSource),shader}function pointPolygon(x,y,w,h){var verts;switch(m_primitiveShape){case"triangle":verts=[x,y-2*h,x-w*Math.sqrt(3),y+h,x+w*Math.sqrt(3),y+h];break;case"sprite":verts=[x,y];break;default:verts=[x-w,y+h,x-w,y-h,x+w,y+h,x-w,y-h,x+w,y-h,x+w,y+h]}return verts}function createGLPoints(){var i,j,posBuf,posVal,posFunc,unitBuf,indices,radius,radiusVal,radFunc,stroke,strokeVal,strokeFunc,strokeWidth,strokeWidthVal,strokeWidthFunc,strokeOpacity,strokeOpacityVal,strokeOpactityFunc,strokeColor,strokeColorVal,strokeColorFunc,fill,fillVal,fillFunc,fillOpacity,fillOpacityVal,fillOpacityFunc,fillColor,fillColorVal,fillColorFunc,item,ivpf,ivpf3,iunit,i3,numPts=m_this.data().length,unit=pointPolygon(0,0,1,1),position=new Array(3*numPts),vpf=m_this.verticesPerFeature(),data=m_this.data(),geom=m_mapper.geometryData();for(posFunc=m_this.position(),radFunc=m_this.style.get("radius"),strokeFunc=m_this.style.get("stroke"),strokeWidthFunc=m_this.style.get("strokeWidth"),strokeOpactityFunc=m_this.style.get("strokeOpacity"),strokeColorFunc=m_this.style.get("strokeColor"),fillFunc=m_this.style.get("fill"),fillOpacityFunc=m_this.style.get("fillOpacity"),fillColorFunc=m_this.style.get("fillColor"),i=i3=0;numPts>i;i+=1,i3+=3)posVal=posFunc(data[i]),position[i3]=posVal.x,position[i3+1]=posVal.y,position[i3+2]=posVal.z||0;for(position=geo.transform.transformCoordinates(m_this.gcs(),m_this.layer().map().gcs(),position,3),posBuf=getBuffer(geom,"pos",vpf*numPts*3),"sprite"!==m_primitiveShape&&(unitBuf=getBuffer(geom,"unit",vpf*numPts*2)),radius=getBuffer(geom,"rad",vpf*numPts*1),stroke=getBuffer(geom,"stroke",vpf*numPts*1),strokeWidth=getBuffer(geom,"strokeWidth",vpf*numPts*1),strokeOpacity=getBuffer(geom,"strokeOpacity",vpf*numPts*1),strokeColor=getBuffer(geom,"strokeColor",vpf*numPts*3),fill=getBuffer(geom,"fill",vpf*numPts*1),fillOpacity=getBuffer(geom,"fillOpacity",vpf*numPts*1),fillColor=getBuffer(geom,"fillColor",vpf*numPts*3),indices=geom.primitive(0).indices(),indices instanceof Uint16Array&&indices.length===vpf*numPts||(indices=new Uint16Array(vpf*numPts),geom.primitive(0).setIndices(indices)),i=ivpf=ivpf3=iunit=i3=0;numPts>i;i+=1,i3+=3){if(item=data[i],"sprite"!==m_primitiveShape)for(j=0;jj;j+=1,ivpf+=1,ivpf3+=3)posBuf[ivpf3]=position[i3],posBuf[ivpf3+1]=position[i3+1],posBuf[ivpf3+2]=position[i3+2],radius[ivpf]=radiusVal,stroke[ivpf]=strokeVal,strokeWidth[ivpf]=strokeWidthVal,strokeOpacity[ivpf]=strokeOpacityVal,strokeColor[ivpf3]=strokeColorVal.r,strokeColor[ivpf3+1]=strokeColorVal.g,strokeColor[ivpf3+2]=strokeColorVal.b,fill[ivpf]=fillVal,fillOpacity[ivpf]=fillOpacityVal,fillColor[ivpf3]=fillColorVal.r,fillColor[ivpf3+1]=fillColorVal.g,fillColor[ivpf3+2]=fillColorVal.b}geom.boundsDirty(!0),m_mapper.modified(),m_mapper.boundsDirtyTimestamp().modified()}function getBuffer(geom,srcName,len){var data,src=geom.sourceByName(srcName);return data=src.data(),data instanceof Float32Array&&data.length===len?data:(data=new Float32Array(len),src.setData(data),data)}if(!(this instanceof geo.gl.pointFeature))return new geo.gl.pointFeature(arg);arg=arg||{},geo.pointFeature.call(this,arg);var m_this=this,s_exit=this._exit,m_actor=null,m_mapper=null,m_pixelWidthUniform=null,m_aspectUniform=null,m_dynamicDraw=void 0===arg.dynamicDraw?!1:arg.dynamicDraw,m_primitiveShape="sprite",s_init=this._init,s_update=this._update,vertexShaderSource=null,fragmentShaderSource=null;return("triangle"===arg.primitiveShape||"square"===arg.primitiveShape||"sprite"===arg.primitiveShape)&&(m_primitiveShape=arg.primitiveShape),vertexShaderSource=["#ifdef GL_ES"," precision highp float;","#endif","attribute vec3 pos;","attribute float rad;","attribute vec3 fillColor;","attribute vec3 strokeColor;","attribute float fillOpacity;","attribute float strokeWidth;","attribute float strokeOpacity;","attribute float fill;","attribute float stroke;","uniform float pixelWidth;","uniform float aspect;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","varying vec4 fillColorVar;","varying vec4 strokeColorVar;","varying float radiusVar;","varying float strokeWidthVar;","varying float fillVar;","varying float strokeVar;"],"sprite"!==m_primitiveShape&&(vertexShaderSource=vertexShaderSource.concat(["attribute vec2 unit;","varying vec3 unitVar;"])),vertexShaderSource.push.apply(vertexShaderSource,["void main(void)","{"," strokeWidthVar = strokeWidth;"," // No stroke or fill implies nothing to draw"," if (stroke < 1.0 || strokeWidth <= 0.0 || strokeOpacity <= 0.0) {"," strokeVar = 0.0;"," strokeWidthVar = 0.0;"," }"," else"," strokeVar = 1.0;"," if (fill < 1.0 || rad <= 0.0 || fillOpacity <= 0.0)"," fillVar = 0.0;"," else"," fillVar = 1.0;"," if (fillVar == 0.0 && strokeVar == 0.0) {"," gl_Position = vec4(2, 2, 0, 1);"," return;"," }"," fillColorVar = vec4 (fillColor, fillOpacity);"," strokeColorVar = vec4 (strokeColor, strokeOpacity);"," radiusVar = rad;"]),"sprite"===m_primitiveShape?vertexShaderSource.push.apply(vertexShaderSource,[" gl_Position = (projectionMatrix * modelViewMatrix * vec4(pos, 1.0)).xyzw;"," gl_PointSize = 2.0 * (rad + strokeWidthVar); ","}"]):vertexShaderSource.push.apply(vertexShaderSource,[" unitVar = vec3 (unit, 1.0);"," vec4 p = (projectionMatrix * modelViewMatrix * vec4(pos, 1.0)).xyzw;"," if (p.w != 0.0) {"," p = p / p.w;"," }"," p += (rad + strokeWidthVar) * "," vec4 (unit.x * pixelWidth, unit.y * pixelWidth * aspect, 0.0, 1.0);"," gl_Position = vec4(p.xyz, 1.0);","}"]),vertexShaderSource=vertexShaderSource.join("\n"),fragmentShaderSource=["#ifdef GL_ES"," precision highp float;","#endif","uniform float aspect;","varying vec4 fillColorVar;","varying vec4 strokeColorVar;","varying float radiusVar;","varying float strokeWidthVar;","varying float fillVar;","varying float strokeVar;"],"sprite"!==m_primitiveShape&&fragmentShaderSource.push("varying vec3 unitVar;"),fragmentShaderSource.push.apply(fragmentShaderSource,["void main () {"," vec4 strokeColor, fillColor;"," float endStep;"," // No stroke or fill implies nothing to draw"," if (fillVar == 0.0 && strokeVar == 0.0)"," discard;"]),fragmentShaderSource.push("sprite"===m_primitiveShape?" float rad = 2.0 * length (gl_PointCoord - vec2(0.5));":" float rad = length (unitVar.xy);"),fragmentShaderSource.push.apply(fragmentShaderSource,[" if (rad > 1.0)"," discard;"," // If there is no stroke, the fill region should transition to nothing"," if (strokeVar == 0.0) {"," strokeColor = vec4 (fillColorVar.rgb, 0.0);"," endStep = 1.0;"," } else {"," strokeColor = strokeColorVar;"," endStep = radiusVar / (radiusVar + strokeWidthVar);"," }"," // Likewise, if there is no fill, the stroke should transition to nothing"," if (fillVar == 0.0)"," fillColor = vec4 (strokeColor.rgb, 0.0);"," else"," fillColor = fillColorVar;"," // Distance to antialias over"," float antialiasDist = 3.0 / (2.0 * radiusVar);"," if (rad < endStep) {"," float step = smoothstep (endStep - antialiasDist, endStep, rad);"," gl_FragColor = mix (fillColor, strokeColor, step);"," } else {"," float step = smoothstep (1.0 - antialiasDist, 1.0, rad);"," gl_FragColor = mix (strokeColor, vec4 (strokeColor.rgb, 0.0), step);"," }","}"]),fragmentShaderSource=fragmentShaderSource.join("\n"),this.actors=function(){return m_actor?[m_actor]:[]},this.verticesPerFeature=function(){var unit=pointPolygon(0,0,1,1);return unit.length/2},this._init=function(){var prog=vgl.shaderProgram(),vertexShader=createVertexShader(),fragmentShader=createFragmentShader(),posAttr=vgl.vertexAttribute("pos"),unitAttr=vgl.vertexAttribute("unit"),radAttr=vgl.vertexAttribute("rad"),strokeWidthAttr=vgl.vertexAttribute("strokeWidth"),fillColorAttr=vgl.vertexAttribute("fillColor"),fillAttr=vgl.vertexAttribute("fill"),strokeColorAttr=vgl.vertexAttribute("strokeColor"),strokeAttr=vgl.vertexAttribute("stroke"),fillOpacityAttr=vgl.vertexAttribute("fillOpacity"),strokeOpacityAttr=vgl.vertexAttribute("strokeOpacity"),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix"),mat=vgl.material(),blend=vgl.blend(),geom=vgl.geometryData(),sourcePositions=vgl.sourceDataP3fv({name:"pos"}),sourceUnits=vgl.sourceDataAnyfv(2,vgl.vertexAttributeKeysIndexed.One,{name:"unit"}),sourceRadius=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Two,{name:"rad"}),sourceStrokeWidth=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Three,{name:"strokeWidth"}),sourceFillColor=vgl.sourceDataAnyfv(3,vgl.vertexAttributeKeysIndexed.Four,{name:"fillColor"}),sourceFill=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Five,{name:"fill"}),sourceStrokeColor=vgl.sourceDataAnyfv(3,vgl.vertexAttributeKeysIndexed.Six,{name:"strokeColor"}),sourceStroke=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Seven,{name:"stroke"}),sourceAlpha=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Eight,{name:"fillOpacity"}),sourceStrokeOpacity=vgl.sourceDataAnyfv(1,vgl.vertexAttributeKeysIndexed.Nine,{name:"strokeOpacity"}),primitive=new vgl.triangles;"sprite"===m_primitiveShape&&(primitive=new vgl.points),m_pixelWidthUniform=new vgl.floatUniform("pixelWidth",2/m_this.renderer().width()),m_aspectUniform=new vgl.floatUniform("aspect",m_this.renderer().width()/m_this.renderer().height()),s_init.call(m_this,arg),m_mapper=vgl.mapper({dynamicDraw:m_dynamicDraw}),prog.addVertexAttribute(posAttr,vgl.vertexAttributeKeys.Position),"sprite"!==m_primitiveShape&&prog.addVertexAttribute(unitAttr,vgl.vertexAttributeKeysIndexed.One),prog.addVertexAttribute(radAttr,vgl.vertexAttributeKeysIndexed.Two),prog.addVertexAttribute(strokeWidthAttr,vgl.vertexAttributeKeysIndexed.Three),prog.addVertexAttribute(fillColorAttr,vgl.vertexAttributeKeysIndexed.Four),prog.addVertexAttribute(fillAttr,vgl.vertexAttributeKeysIndexed.Five),prog.addVertexAttribute(strokeColorAttr,vgl.vertexAttributeKeysIndexed.Six),prog.addVertexAttribute(strokeAttr,vgl.vertexAttributeKeysIndexed.Seven),prog.addVertexAttribute(fillOpacityAttr,vgl.vertexAttributeKeysIndexed.Eight),prog.addVertexAttribute(strokeOpacityAttr,vgl.vertexAttributeKeysIndexed.Nine),prog.addUniform(m_pixelWidthUniform),prog.addUniform(m_aspectUniform),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),mat.addAttribute(prog),mat.addAttribute(blend),m_actor=vgl.actor(),m_actor.setMaterial(mat),m_actor.setMapper(m_mapper),geom.addSource(sourcePositions),geom.addSource(sourceUnits),geom.addSource(sourceRadius),geom.addSource(sourceStrokeWidth),geom.addSource(sourceFillColor),geom.addSource(sourceFill),geom.addSource(sourceStrokeColor),geom.addSource(sourceStroke),geom.addSource(sourceAlpha),geom.addSource(sourceStrokeOpacity),geom.addPrimitive(primitive),m_mapper.setGeometryData(geom)},this._build=function(){m_actor&&m_this.renderer().contextRenderer().removeActor(m_actor),createGLPoints(),m_this.renderer().contextRenderer().addActor(m_actor),m_this.renderer().contextRenderer().render(),m_this.buildTime().modified()},this._update=function(){s_update.call(m_this),(m_this.dataTime().getMTime()>=m_this.buildTime().getMTime()||m_this.updateTime().getMTime()i;i+=1)buffers.write("pos",position[i],start+i,1),buffers.write("indices",[i],start+i,1),buffers.write("fillColor",fillColorNew[i],start+i,1),buffers.write("fillOpacity",[fillOpacityNew[i]],start+i,1);sourcePositions.pushBack(buffers.get("pos")),geom.addSource(sourcePositions),sourceFillColor.pushBack(buffers.get("fillColor")),geom.addSource(sourceFillColor),sourceFillOpacity.pushBack(buffers.get("fillOpacity")),geom.addSource(sourceFillOpacity),trianglePrimitive.setIndices(buffers.get("indices")),
+geom.addPrimitive(trianglePrimitive),m_mapper.setGeometryData(geom)}if(!(this instanceof geo.gl.polygonFeature))return new geo.gl.polygonFeature(arg);arg=arg||{},geo.polygonFeature.call(this,arg);var m_this=this,s_exit=this._exit,m_actor=vgl.actor(),m_mapper=vgl.mapper(),m_material=vgl.material(),s_init=this._init,s_update=this._update;return this._init=function(arg){var blend=vgl.blend(),prog=vgl.shaderProgram(),posAttr=vgl.vertexAttribute("pos"),fillColorAttr=vgl.vertexAttribute("fillColor"),fillOpacityAttr=vgl.vertexAttribute("fillOpacity"),modelViewUniform=new vgl.modelViewUniform("modelViewMatrix"),projectionUniform=new vgl.projectionUniform("projectionMatrix"),vertexShader=createVertexShader(),fragmentShader=createFragmentShader();s_init.call(m_this,arg),prog.addVertexAttribute(posAttr,vgl.vertexAttributeKeys.Position),prog.addVertexAttribute(fillColorAttr,vgl.vertexAttributeKeysIndexed.Two),prog.addVertexAttribute(fillOpacityAttr,vgl.vertexAttributeKeysIndexed.Three),prog.addUniform(modelViewUniform),prog.addUniform(projectionUniform),prog.addShader(fragmentShader),prog.addShader(vertexShader),m_material.addAttribute(prog),m_material.addAttribute(blend),m_actor.setMapper(m_mapper),m_actor.setMaterial(m_material)},this._build=function(){m_actor&&m_this.renderer().contextRenderer().removeActor(m_actor),createGLPolygons(),m_this.renderer().contextRenderer().addActor(m_actor),m_this.buildTime().modified()},this._update=function(){s_update.call(m_this),(m_this.dataTime().getMTime()>=m_this.buildTime().getMTime()||m_this.updateTime().getMTime()<=m_this.getMTime())&&m_this._build(),m_actor.setVisible(m_this.visible()),m_actor.material().setBinNumber(m_this.bin()),m_this.updateTime().modified()},this._exit=function(){m_this.renderer().contextRenderer().removeActor(m_actor),s_exit()},this._init(arg),this},inherit(geo.gl.polygonFeature,geo.polygonFeature),geo.registerFeature("vgl","polygon",geo.gl.polygonFeature),geo.gl._vglViewerInstances={viewers:[],maps:[]},geo.gl.vglViewerInstance=function(map){"use strict";function makeViewer(){canvas=$(document.createElement("canvas")),canvas.attr("class","webgl-canvas");var viewer=vgl.viewer(canvas.get(0));return viewer.renderWindow().removeRenderer(viewer.renderWindow().activeRenderer()),viewer.init(),viewer}var mapIdx,canvas,maps=geo.gl._vglViewerInstances.maps,viewers=geo.gl._vglViewerInstances.viewers;for(mapIdx=0;mapIdx0)if(output=[],input[0]instanceof Object)for(delta=1,i=0;i0)if(output=[],input[0]instanceof Object)for(delta=1,i=0;i0&&(m_contextRenderer.setLayer(m_viewer.renderWindow().renderers().length),m_contextRenderer.setResetScene(!1)),m_viewer.renderWindow().addRenderer(m_contextRenderer),m_this.layer().node().append(m_this.canvas()),m_this)},this._resize=function(x,y,w,h){return m_width=w,m_height=h,m_this.canvas().attr("width",w),m_this.canvas().attr("height",h),m_viewer.renderWindow().positionAndResize(x,y,w,h),m_this._render(),m_this},this._render=function(){return m_viewer.render(),m_this},this._exit=function(){geo.gl.vglViewerInstance.deleteCache(m_viewer),s_exit()},this._updateRendererCamera=function(){var pos,fp,cr,vglRenderer=m_this.contextRenderer(),renderWindow=m_viewer.renderWindow(),camera=vglRenderer.camera();vglRenderer.resetCameraClippingRange(),pos=camera.position(),fp=camera.focalPoint(),cr=camera.clippingRange(),renderWindow.renderers().forEach(function(renderer){var cam=renderer.camera();cam!==camera&&(cam.setPosition(pos[0],pos[1],pos[2]),cam.setFocalPoint(fp[0],fp[1],fp[2]),cam.setClippingRange(cr[0],cr[1]),renderer.render())})},this.geoOn(geo.event.pan,function(evt){var camera,focusPoint,centerDisplay,centerGeo,newCenterDisplay,newCenterGeo,renderWindow,vglRenderer=m_this.contextRenderer(),layer=m_this.layer();layer.map().baseLayer()===layer&&(vglRenderer&&vglRenderer.camera()||console.log("Pan event triggered on unconnected vgl renderer."),renderWindow=m_viewer.renderWindow(),camera=vglRenderer.camera(),focusPoint=renderWindow.focusDisplayPoint(),centerDisplay=[m_width/2,m_height/2,0],centerGeo=renderWindow.displayToWorld(centerDisplay[0],centerDisplay[1],focusPoint,vglRenderer),newCenterDisplay=[centerDisplay[0]+evt.screenDelta.x,centerDisplay[1]+evt.screenDelta.y],newCenterGeo=renderWindow.displayToWorld(newCenterDisplay[0],newCenterDisplay[1],focusPoint,vglRenderer),camera.pan(centerGeo[0]-newCenterGeo[0],centerGeo[1]-newCenterGeo[1],centerGeo[2]-newCenterGeo[2]),evt.center={x:newCenterGeo[0],y:newCenterGeo[1],z:newCenterGeo[2]},m_this._updateRendererCamera())}),this.geoOn(geo.event.zoom,function(evt){var camera,renderWindow,center,dir,focusPoint,position,newZ,vglRenderer=m_this.contextRenderer(),layer=m_this.layer();layer.map().baseLayer()===layer&&(vglRenderer&&vglRenderer.camera()||console.log("Zoom event triggered on unconnected vgl renderer."),renderWindow=m_viewer.renderWindow(),camera=vglRenderer.camera(),focusPoint=camera.focalPoint(),position=camera.position(),newZ=360*Math.pow(2,-evt.zoomLevel),evt.pan=null,evt.screenPosition&&(center=renderWindow.displayToWorld(evt.screenPosition.x,evt.screenPosition.y,focusPoint,vglRenderer),dir=[center[0]-position[0],center[1]-position[1],center[2]-position[2]],evt.center=layer.fromLocal({x:position[0]+dir[0]*(1-newZ/position[2]),y:position[1]+dir[1]*(1-newZ/position[2])})),camera.setPosition(position[0],position[1],360*Math.pow(2,-evt.zoomLevel)),m_this._updateRendererCamera())}),this},inherit(geo.gl.vglRenderer,geo.gl.renderer),geo.registerRenderer("vgl",geo.gl.vglRenderer),geo.d3={},function(){"use strict";var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",strLength=8;geo.d3.uniqueID=function(){var i,strArray=[];for(strArray.length=strLength,i=0;strLength>i;i+=1)strArray[i]=chars.charAt(Math.floor(Math.random()*chars.length));return strArray.join("")},geo.event.d3Rescale="geo_d3_rescale"}(),geo.d3.object=function(arg){"use strict";if(!(this instanceof geo.object))return new geo.d3.object(arg);geo.sceneObject.call(this);var m_id="d3-"+geo.d3.uniqueID(),s_exit=this._exit,m_this=this,s_draw=this.draw;return this._d3id=function(){return m_id},this.select=function(){return m_this.renderer().select(m_this._d3id())},this.draw=function(){return m_this._update(),s_draw(),m_this},this._exit=function(){m_this.renderer()._removeFeature(m_this._d3id()),s_exit()},this},inherit(geo.d3.object,geo.sceneObject),geo.d3.pointFeature=function(arg){"use strict";if(!(this instanceof geo.d3.pointFeature))return new geo.d3.pointFeature(arg);arg=arg||{},geo.pointFeature.call(this,arg),geo.d3.object.call(this);var m_sticky,m_this=this,s_init=this._init,s_update=this._update,m_buildTime=geo.timestamp(),m_style={};return this._init=function(arg){return s_init.call(m_this,arg),m_sticky=m_this.layer().sticky(),m_this},this._build=function(){var data=m_this.data(),s_style=m_this.style.get(),m_renderer=m_this.renderer(),pos_func=m_this.position();return s_update.call(m_this),data||(data=[]),m_style.id=m_this._d3id(),m_style.data=data,m_style.append="circle",m_style.attributes={r:m_renderer._convertScale(s_style.radius),cx:function(d){return m_renderer.worldToDisplay(pos_func(d)).x},cy:function(d){return m_renderer.worldToDisplay(pos_func(d)).y}},m_style.style=s_style,m_style.classes=["d3PointFeature"],m_this.renderer()._drawFeatures(m_style),m_buildTime.modified(),m_this.updateTime().modified(),m_this},this._update=function(){return s_update.call(m_this),m_this.getMTime()>=m_buildTime.getMTime()&&m_this._build(),m_this},this._init(arg),this},inherit(geo.d3.pointFeature,geo.pointFeature),geo.registerFeature("d3","point",geo.d3.pointFeature),geo.d3.lineFeature=function(arg){"use strict";if(!(this instanceof geo.d3.lineFeature))return new geo.d3.lineFeature(arg);arg=arg||{},geo.lineFeature.call(this,arg),geo.d3.object.call(this);var m_this=this,s_init=this._init,m_buildTime=geo.timestamp(),s_update=this._update;return this._init=function(arg){return s_init.call(m_this,arg),m_this},this._build=function(){var data=m_this.data()||[],s_style=m_this.style(),m_renderer=m_this.renderer(),pos_func=m_this.position(),line=d3.svg.line().x(function(d){return m_renderer.worldToDisplay(d).x}).y(function(d){return m_renderer.worldToDisplay(d).y});return s_update.call(m_this),s_style.fill=function(){return!1},data.forEach(function(item,idx){function wrapStyle(func){return geo.util.isFunction(func)?function(){return func(ln[0],0,item,idx)}:func}var m_style,key,ln=m_this.line()(item,idx),style={};for(key in s_style)s_style.hasOwnProperty(key)&&(style[key]=wrapStyle(s_style[key]));m_style={data:[ln.map(function(d,i){return pos_func(d,i,item,idx)})],append:"path",attributes:{d:line},id:m_this._d3id()+idx,classes:["d3LineFeature","d3SubLine-"+idx],style:style},m_renderer._drawFeatures(m_style)}),m_buildTime.modified(),m_this.updateTime().modified(),m_this},this._update=function(){return s_update.call(m_this),m_this.getMTime()>=m_buildTime.getMTime()&&m_this._build(),m_this},this._init(arg),this},inherit(geo.d3.lineFeature,geo.lineFeature),geo.registerFeature("d3","line",geo.d3.lineFeature),geo.d3.pathFeature=function(arg){"use strict";if(!(this instanceof geo.d3.pathFeature))return new geo.d3.pathFeature(arg);arg=arg||{},geo.pathFeature.call(this,arg),geo.d3.object.call(this);var m_this=this,s_init=this._init,m_buildTime=geo.timestamp(),s_update=this._update,m_style={};return m_style.style={},this._init=function(arg){return s_init.call(m_this,arg),m_this},this._build=function(){var tmp,diag,data=m_this.data()||[],s_style=m_this.style(),m_renderer=m_this.renderer();return s_update.call(m_this),diag=function(d){var p={source:d.source,target:d.target};return d3.svg.diagonal()(p)},tmp=[],data.forEach(function(d,i){var src,trg;i=m_buildTime.getMTime()&&m_this._build(),m_this},this._init(arg),this},inherit(geo.d3.pathFeature,geo.pathFeature),geo.registerFeature("d3","path",geo.d3.pathFeature),geo.d3.graphFeature=function(arg){"use strict";var m_this=this;return this instanceof geo.d3.graphFeature?(geo.graphFeature.call(this,arg),this.select=function(){var renderer=m_this.renderer(),selection={},node=m_this.nodeFeature(),links=m_this.linkFeatures();return selection.nodes=renderer.select(node._d3id()),selection.links=links.map(function(link){return renderer.select(link._d3id())}),selection},this):new geo.d3.graphFeature(arg)},inherit(geo.d3.graphFeature,geo.graphFeature),geo.registerFeature("d3","graph",geo.d3.graphFeature),geo.d3.planeFeature=function(arg){"use strict";function normalize(pt){return Array.isArray(pt)?{x:pt[0],y:pt[1]}:pt instanceof geo.latlng?{x:pt.x(),y:pt.y()}:pt}if(!(this instanceof geo.d3.planeFeature))return new geo.d3.planeFeature(arg);geo.planeFeature.call(this,arg),geo.d3.object.call(this);var m_this=this,m_style={},s_update=this._update,s_init=this._init,m_buildTime=geo.timestamp();return this._build=function(){var origin=normalize(m_this.origin()),ul=normalize(m_this.upperLeft()),lr=normalize(m_this.lowerRight()),renderer=m_this.renderer(),s=m_this.style();return delete s.fill_color,delete s.color,delete s.opacity,s.screenCoordinates||(origin=renderer.worldToDisplay(origin),ul=renderer.worldToDisplay(ul),lr=renderer.worldToDisplay(lr)),m_style.id=m_this._d3id(),m_style.style=s,m_style.attributes={x:ul.x,y:ul.y,width:lr.x-origin.x,height:origin.y-ul.y},m_style.append="rect",m_style.data=[0],m_style.classes=["d3PlaneFeature"],renderer._drawFeatures(m_style),m_buildTime.modified(),m_this},this._update=function(){return s_update.call(m_this),m_this.dataTime().getMTime()>=m_buildTime.getMTime()&&m_this._build(),m_this},this._init=function(arg){return s_init.call(m_this,arg||{}),m_this.style({stroke:function(){return!1},fill:function(){return!0},fillColor:function(){return{r:.3,g:.3,b:.3}},fillOpacity:function(){return.5}}),m_this},this._init(),this},inherit(geo.d3.planeFeature,geo.planeFeature),geo.registerFeature("d3","plane",geo.d3.planeFeature),geo.d3.vectorFeature=function(arg){"use strict";function markerID(d,i){return m_this._d3id()+"_marker_"+i}function updateMarkers(data,stroke,opacity){var renderer=m_this.renderer(),sel=m_this.renderer()._definitions().selectAll("marker.geo-vector").data(data);sel.enter().append("marker").attr("id",markerID).attr("class","geo-vector").attr("viewBox","0 0 10 10").attr("refX","1").attr("refY","5").attr("markerWidth","5").attr("markerHeight","5").attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z"),sel.exit().remove(),sel.style("stroke",renderer._convertColor(stroke)).style("fill",renderer._convertColor(stroke)).style("opacity",opacity)}if(!(this instanceof geo.d3.vectorFeature))return new geo.d3.vectorFeature(arg);arg=arg||{},geo.vectorFeature.call(this,arg),geo.d3.object.call(this);var m_sticky,m_this=this,s_init=this._init,s_exit=this._exit,s_update=this._update,m_buildTime=geo.timestamp(),m_style={};return this._init=function(arg){return s_init.call(m_this,arg),m_sticky=m_this.layer().sticky(),m_this},this._build=function(){function getScale(){return scale/m_renderer.scaleFactor()}var data=m_this.data(),s_style=m_this.style.get(),m_renderer=m_this.renderer(),orig_func=m_this.origin(),size_func=m_this.delta(),cache=[],scale=m_this.style("scale"),max=Number.NEGATIVE_INFINITY;return s_update.call(m_this),data||(data=[]),cache=data.map(function(d,i){var origin=m_renderer.worldToDisplay(orig_func(d,i)),delta=size_func(d,i);return max=Math.max(max,delta.x*delta.x+delta.y*delta.y),{x1:origin.x,y1:origin.y,dx:delta.x,dy:-delta.y}}),max=Math.sqrt(max),scale||(scale=75/max),m_style.id=m_this._d3id(),m_style.data=data,m_style.append="line",m_style.attributes={x1:function(d,i){return cache[i].x1},y1:function(d,i){return cache[i].y1},x2:function(d,i){return cache[i].x1+getScale()*cache[i].dx},y2:function(d,i){return cache[i].y1+getScale()*cache[i].dy},"marker-end":function(d,i){return"url(#"+markerID(d,i)+")"}},m_style.style={stroke:function(){return!0},strokeColor:s_style.strokeColor,strokeWidth:s_style.strokeWidth,strokeOpacity:s_style.strokeOpacity},m_style.classes=["d3VectorFeature"],updateMarkers(data,s_style.strokeColor,s_style.strokeOpacity),m_this.renderer()._drawFeatures(m_style),m_buildTime.modified(),m_this.updateTime().modified(),m_this},this._update=function(){return s_update.call(m_this),m_this.getMTime()>=m_buildTime.getMTime()?m_this._build():updateMarkers(m_style.data,m_style.style.strokeColor,m_style.style.strokeOpacity),m_this},this._exit=function(){s_exit.call(m_this),m_style={},updateMarkers([],null,null)},this._init(arg),this},inherit(geo.d3.vectorFeature,geo.vectorFeature),geo.registerFeature("d3","vector",geo.d3.vectorFeature),geo.d3.d3Renderer=function(arg){"use strict";function setAttrs(select,attrs){var key;for(key in attrs)attrs.hasOwnProperty(key)&&select.attr(key,attrs[key])}function setStyles(select,styles){function fillFunc(){return styles.fill.apply(this,arguments)?null:"none"}function strokeFunc(){return styles.stroke.apply(this,arguments)?null:"none"}var key,k,f;for(key in styles)styles.hasOwnProperty(key)&&(f=null,k=null,"strokeColor"===key?(k="stroke",f=m_this._convertColor(styles[key],styles.stroke)):"stroke"===key&&styles[key]?(k="stroke",f=strokeFunc):"strokeWidth"===key?(k="stroke-width",f=m_this._convertScale(styles[key])):"strokeOpacity"===key?(k="stroke-opacity",f=styles[key]):"fillColor"===key?(k="fill",f=m_this._convertColor(styles[key],styles.fill)):"fill"!==key||styles.hasOwnProperty("fillColor")?"fillOpacity"===key&&(k="fill-opacity",f=styles[key]):(k="fill",f=fillFunc),k&&select.style(k,f))}function getMap(){var layer=m_this.layer();return layer?layer.map():null}function getGroup(){return m_svg.select(".group-"+m_this._d3id())}function initCorners(){var layer=m_this.layer(),map=layer.map(),width=m_this.layer().width(),height=m_this.layer().height();if(m_width=width,m_height=height,!m_width||!m_height)throw"Map layer has size 0";m_corners={upperLeft:map.displayToGcs({x:0,y:0}),lowerRight:map.displayToGcs({x:width,y:height})}}function setTransform(){if(m_corners||initCorners(),m_sticky){var dx,dy,scale,layer=m_this.layer(),map=layer.map(),upperLeft=map.gcsToDisplay(m_corners.upperLeft),lowerRight=map.gcsToDisplay(m_corners.lowerRight),group=getGroup();dx=upperLeft.x,dy=upperLeft.y,scale=(lowerRight.y-upperLeft.y)/m_height,group.attr("transform","matrix("+[scale,0,0,scale,dx,dy].join()+")"),m_scale=scale,m_dx=dx,m_dy=dy}}function baseToLocal(pt){return{x:(pt.x-m_dx)/m_scale,y:(pt.y-m_dy)/m_scale}}function localToBase(pt){return{x:pt.x*m_scale+m_dx,y:pt.y*m_scale+m_dy}}if(!(this instanceof geo.d3.d3Renderer))return new geo.d3.d3Renderer(arg);geo.renderer.call(this,arg);var s_exit=this._exit;geo.d3.object.call(this,arg),arg=arg||{};var m_this=this,m_sticky=null,m_features={},m_corners=null,m_width=null,m_height=null,m_scale=1,m_dx=0,m_dy=0,m_svg=null,m_defs=null;return this._convertColor=function(f,g){return f=geo.util.ensureFunction(f),g=g||function(){return!0},function(){var c="none";return g.apply(this,arguments)&&(c=f.apply(this,arguments),c.hasOwnProperty("r")&&c.hasOwnProperty("g")&&c.hasOwnProperty("b")&&(c=d3.rgb(255*c.r,255*c.g,255*c.b))),c}},this._convertPosition=function(f){return f=geo.util.ensureFunction(f),function(){return m_this.worldToDisplay(f.apply(this,arguments))}},this._convertScale=function(f){return f=geo.util.ensureFunction(f),function(){return f.apply(this,arguments)/m_scale}},this._init=function(){if(!m_this.canvas()){var canvas;m_svg=d3.select(m_this.layer().node().get(0)).append("svg"),m_defs=m_svg.append("defs");var shadow=m_defs.append("filter").attr("id","geo-highlight").attr("x","-100%").attr("y","-100%").attr("width","300%").attr("height","300%");shadow.append("feMorphology").attr("operator","dilate").attr("radius",2).attr("in","SourceAlpha").attr("result","dilateOut"),shadow.append("feGaussianBlur").attr("stdDeviation",5).attr("in","dilateOut").attr("result","blurOut"),shadow.append("feColorMatrix").attr("type","matrix").attr("values","-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0").attr("in","blurOut").attr("result","invertOut"),shadow.append("feBlend").attr("in","SourceGraphic").attr("in2","invertOut").attr("mode","normal"),canvas=m_svg.append("g"),shadow=m_defs.append("filter").attr("id","geo-blur").attr("x","-100%").attr("y","-100%").attr("width","300%").attr("height","300%"),shadow.append("feGaussianBlur").attr("stdDeviation",20).attr("in","SourceGraphic"),m_sticky=m_this.layer().sticky(),m_svg.attr("class",m_this._d3id()),m_svg.attr("width",m_this.layer().node().width()),m_svg.attr("height",m_this.layer().node().height()),canvas.attr("class","group-"+m_this._d3id()),m_this.canvas(canvas)}},this.displayToWorld=function(pt){var map=getMap();if(!map)throw"Cannot project until this layer is connected to a map.";return pt=Array.isArray(pt)?pt.map(function(x){return map.displayToGcs(localToBase(x))}):map.displayToGcs(localToBase(pt))},this.worldToDisplay=function(pt){var map=getMap();if(!map)throw"Cannot project until this layer is connected to a map.";var v;return v=Array.isArray(pt)?pt.map(function(x){return baseToLocal(map.gcsToDisplay(x))}):baseToLocal(map.gcsToDisplay(pt))},this.api=function(){return"d3"},this.scaleFactor=function(){return m_scale},this._resize=function(x,y,w,h){m_corners||initCorners(),m_svg.attr("width",w),m_svg.attr("height",h),setTransform(),m_this.layer().geoTrigger(geo.event.d3Rescale,{scale:m_scale},!0)},this._update=function(){},this._exit=function(){m_features={},m_this.canvas().remove(),s_exit()},this._definitions=function(){return m_defs},this._drawFeatures=function(arg){return m_features[arg.id]={data:arg.data,index:arg.dataIndex,style:arg.style,attributes:arg.attributes,classes:arg.classes,append:arg.append},m_this.__render(arg.id)},this.__render=function(id){var key;if(void 0===id){for(key in m_features)m_features.hasOwnProperty(key)&&m_this.__render(key);return m_this}var data=m_features[id].data,index=m_features[id].index,style=m_features[id].style,attributes=m_features[id].attributes,classes=m_features[id].classes,append=m_features[id].append,selection=m_this.select(id).data(data,index);return selection.enter().append(append),selection.exit().remove(),setAttrs(selection,attributes),selection.attr("class",classes.concat([id]).join(" ")),setStyles(selection,style),m_this},this.select=function(id){return getGroup().selectAll("."+id)},this._removeFeature=function(id){return m_this.select(id).remove(),delete m_features[id],m_this},this.draw=function(){},this.layer().geoOn(geo.event.pan,setTransform),this.layer().geoOn(geo.event.zoom,function(){setTransform(),m_this.__render(),m_this.layer().geoTrigger(geo.event.d3Rescale,{scale:m_scale},!0)}),this.layer().geoOn(geo.event.resize,function(event){m_this._resize(event.x,event.y,event.width,event.height)}),this._init(arg),this},inherit(geo.d3.d3Renderer,geo.renderer),geo.registerRenderer("d3",geo.d3.d3Renderer),geo.gui={},geo.gui.uiLayer=function(arg){"use strict";if(arg.renderer="d3",arg.sticky=!1,!(this instanceof geo.gui.uiLayer))return new geo.gui.uiLayer(arg);geo.layer.call(this,arg);var m_this=this,s_exit=this._exit;this.createWidget=function(widgetName,arg){var newWidget=geo.createWidget(widgetName,m_this,m_this.renderer(),arg);return m_this.addChild(newWidget),newWidget._init(),m_this.modified(),newWidget},this.deleteWidget=function(widget){return widget._exit(),m_this.removeChild(widget),m_this.modified(),m_this},this._exit=function(){m_this.children().forEach(function(child){m_this.deleteWidget(child)}),s_exit()}},inherit(geo.gui.uiLayer,geo.layer),geo.registerLayer("ui",geo.gui.uiLayer),geo.gui.widget=function(arg){"use strict";if(!(this instanceof geo.gui.widget))return new geo.gui.widget(arg);geo.sceneObject.call(this,arg);var m_this=this,s_exit=this._exit,m_layer=arg.layer;this._init=function(){m_this.modified()},this._exit=function(){m_this.children().forEach(function(child){m_this._deleteFeature(child)}),s_exit()},this._createFeature=function(featureName,arg){var newFeature=geo.createFeature(featureName,m_this,m_this.renderer(),arg);return m_this.addChild(newFeature),m_this.modified(),newFeature},this._deleteFeature=function(feature){return m_this.removeChild(feature),feature._exit(),m_this},this.layer=function(){return m_layer}},inherit(geo.gui.widget,geo.sceneObject),geo.gui.sliderWidget=function(arg){"use strict";function put_icon(icon,base,cx,cy,size){var g=base.append("g"),s=size/1024;return g.append("g").append("g").attr("transform","translate("+cx+","+cy+") scale("+s+") translate(-512,-512)").append("path").attr("d",icon).attr("class","geo-glyphicon"),g}if(!(this instanceof geo.gui.sliderWidget))return new geo.gui.sliderWidget(arg);geo.gui.widget.call(this,arg);var m_xscale,m_yscale,m_plus,m_minus,m_track,m_nub,m_plusIcon,m_minusIcon,m_group,m_lowContrast,m_this=this,s_exit=this._exit,m_width=20,m_height=100,m_nubSize=10,m_highlightDur=100;m_plusIcon="M512 81.92c-237.568 0-430.080 192.614-430.080 430.080 0 237.568 192.563 430.080 430.080 430.080s430.080-192.563 430.080-430.080c0-237.517-192.563-430.080-430.080-430.080zM564.326 564.326v206.182h-104.653v-206.182h-206.234v-104.653h206.182v-206.234h104.704v206.182h206.182v104.704h-206.182z",m_minusIcon="M512 81.92c-237.568 0-430.080 192.614-430.080 430.080 0 237.568 192.563 430.080 430.080 430.080s430.080-192.563 430.080-430.080c0-237.517-192.563-430.080-430.080-430.080zM770.56 459.674v104.704h-517.12v-104.704h517.12z",m_lowContrast={white:"#f4f4f4",black:"#505050"},this._init=function(){function respond(evt,trans){var z=m_yscale.invert(d3.mouse(m_this.layer().node()[0])[1]),zrange=map.zoomRange();z=(1-z)*(zrange.max-zrange.min)+zrange.min,trans?map.transition({zoom:z,ease:d3.ease("cubic-in-out"),duration:500,done:m_this._update()}):(map.zoom(z),m_this._update()),evt.stopPropagation()}var svg=m_this.layer().renderer().canvas(),x0=40,y0=40+m_width,map=m_this.layer().map();m_xscale=d3.scale.linear().domain([-4,4]).range([x0,x0+m_width]),m_yscale=d3.scale.linear().domain([0,1]).range([y0,y0+m_height]),svg=svg.append("g").classed("geo-ui-slider",!0),m_group=svg,m_plus=svg.append("g"),m_plus.append("circle").datum({fill:"white",stroke:null}).classed("geo-zoom-in",!0).attr("cx",m_xscale(0)).attr("cy",m_yscale(0)-m_width+2).attr("r",m_width/2).style({cursor:"pointer"}).on("click",function(){var z=map.zoom();map.transition({zoom:z+1,ease:d3.ease("cubic-in-out"),duration:500})}).on("mousedown",function(){d3.event.stopPropagation()}),put_icon(m_plusIcon,m_plus,m_xscale(0),m_yscale(0)-m_width+2,m_width+5).style("cursor","pointer").style("pointer-events","none").select("path").datum({fill:"black",stroke:null}),m_minus=svg.append("g"),m_minus.append("circle").datum({fill:"white",stroke:null}).classed("geo-zoom-out",!0).attr("cx",m_xscale(0)).attr("cy",m_yscale(1)+m_width-2).attr("r",m_width/2).style({cursor:"pointer"}).on("click",function(){var z=map.zoom();map.transition({zoom:z-1,ease:d3.ease("cubic-in-out"),duration:500})}).on("mousedown",function(){d3.event.stopPropagation()}),put_icon(m_minusIcon,m_minus,m_xscale(0),m_yscale(1)+m_width-2,m_width+5).style("cursor","pointer").style("pointer-events","none").select("path").datum({fill:"black",stroke:null}),m_track=svg.append("rect").datum({fill:"white",stroke:"black"}).classed("geo-zoom-track",!0).attr("x",m_xscale(0)-m_width/6).attr("y",m_yscale(0)).attr("rx",m_width/10).attr("ry",m_width/10).attr("width",m_width/3).attr("height",m_height).style({cursor:"pointer"}).on("click",function(){respond(d3.event,!0)}),m_nub=svg.append("rect").datum({fill:"black",stroke:null}).classed("geo-zoom-nub",!0).attr("x",m_xscale(-4)).attr("y",m_yscale(.5)-m_nubSize/2).attr("rx",3).attr("ry",3).attr("width",m_width).attr("height",m_nubSize).style({cursor:"pointer"}).on("mousedown",function(){d3.select(document).on("mousemove.geo.slider",function(){respond(d3.event)}),d3.select(document).on("mouseup.geo.slider",function(){respond(d3.event),d3.select(document).on(".geo.slider",null)}),d3.event.stopPropagation()});var mouseOver=function(){d3.select(this).attr("filter","url(#geo-highlight)"),m_group.selectAll("rect,path,circle").transition().duration(m_highlightDur).style("fill",function(d){return d.fill||null}).style("stroke",function(d){return d.stroke||null})},mouseOut=function(){d3.select(this).attr("filter",null),m_group.selectAll("circle,rect,path").transition().duration(m_highlightDur).style("fill",function(d){return m_lowContrast[d.fill]||null}).style("stroke",function(d){return m_lowContrast[d.stroke]||null})};m_group.selectAll("*").on("mouseover",mouseOver).on("mouseout",mouseOut),m_this.layer().geoOn(geo.event.zoom,function(){m_this._update()}),mouseOut(),m_this._update()},this._exit=function(){m_group.remove(),m_this.layer().geoOff(geo.event.zoom),s_exit()},this._update=function(obj){var map=m_this.layer().map(),zoomRange=map.zoomRange(),zoom=map.zoom(),zoomScale=d3.scale.linear();obj=obj||{},zoom=obj.value||zoom,zoomScale.domain([zoomRange.min,zoomRange.max]).range([1,0]).clamp(!0),m_nub.attr("y",m_yscale(zoomScale(zoom))-m_nubSize/2)}},inherit(geo.gui.sliderWidget,geo.gui.widget),geo.registerWidget("d3","slider",geo.gui.sliderWidget),geo.gui.legendWidget=function(arg){"use strict";if(!(this instanceof geo.gui.legendWidget))return new geo.gui.legendWidget(arg);geo.gui.widget.call(this,arg);var m_this=this,m_categories=[],m_top=null,m_group=null,m_border=null,m_spacing=20,m_padding=12;this.categories=function(arg){return void 0===arg?m_categories.slice():(m_categories=arg.slice().map(function(d){return"line"===d.type&&(d.style.fill=!1,d.style.stroke=!0),d}),m_this.draw(),m_this)},this.size=function(){var height,width=1,test=m_this.layer().renderer().canvas().append("text").style("opacity",1e-6);return m_categories.forEach(function(d){test.text(d.name),
+width=Math.max(width,test.node().getBBox().width)}),test.remove(),height=m_spacing*(m_categories.length+1),{width:width+50,height:height}},this.draw=function(){function applyColor(selection){selection.style("fill",function(d){return d.style.fill||void 0===d.style.fill?d.style.fillColor:"none"}).style("fill-opacity",function(d){return void 0===d.style.fillOpacity?1:d.style.fillOpacity}).style("stroke",function(d){return d.style.stroke||void 0===d.style.stroke?d.style.strokeColor:"none"}).style("stroke-opacity",function(d){return void 0===d.style.strokeOpacity?1:d.style.strokeOpacity}).style("stroke-width",function(d){return void 0===d.style.strokeWidth?1.5:d.style.strokeWidth})}m_this._init(),m_border.attr("height",m_this.size().height+2*m_padding).style("display",null);var scale=m_this._scale(),labels=m_group.selectAll("g.geo-label").data(m_categories,function(d){return d.name}),g=labels.enter().append("g").attr("class","geo-label").attr("transform",function(d,i){return"translate(0,"+scale.y(i)+")"});return applyColor(g.filter(function(d){return"point"!==d.type&&"line"!==d.type}).append("rect").attr("x",0).attr("y",-6).attr("rx",5).attr("ry",5).attr("width",40).attr("height",12)),applyColor(g.filter(function(d){return"point"===d.type}).append("circle").attr("cx",20).attr("cy",0).attr("r",6)),applyColor(g.filter(function(d){return"line"===d.type}).append("line").attr("x1",0).attr("y1",0).attr("x2",40).attr("y2",0)),g.append("text").attr("x","50px").attr("y",0).attr("dy","0.3em").text(function(d){return d.name}),m_this},this._scale=function(){return{x:d3.scale.linear().domain([0,1]).range([0,m_this.size().width]),y:d3.scale.linear().domain([0,m_categories.length-1]).range([m_padding/2,m_this.size().height-m_padding/2])}},this._init=function(){var w=m_this.size().width+2*m_padding,h=m_this.size().height+2*m_padding,nw=m_this.layer().map().node().width(),margin=20;m_top&&m_top.remove(),m_top=m_this.layer().renderer().canvas().append("g").attr("transform","translate("+(nw-w-margin)+","+margin+")"),m_group=m_top.append("g").attr("transform","translate("+[m_padding-1.5,m_padding]+")"),m_border=m_group.append("rect").attr("x",-m_padding).attr("y",-m_padding).attr("width",w).attr("height",h).attr("rx",3).attr("ry",3).style({stroke:"black","stroke-width":"1.5px",fill:"white","fill-opacity":.75,display:"none"}),m_group.on("mousedown",function(){d3.event.stopPropagation()}),m_group.on("mouseover",function(){m_border.transition().duration(250).style("fill-opacity",1)}),m_group.on("mouseout",function(){m_border.transition().duration(250).style("fill-opacity",.75)})},this.geoOn(geo.event.resize,function(){this.draw()})},inherit(geo.gui.legendWidget,geo.gui.widget),geo.registerWidget("d3","legend",geo.gui.legendWidget),function($,geo,d3){"use strict";var load=function(){function isColorKey(key){return"color"===key.slice(key.length-5,key.length).toLowerCase()}function makeColorScale(data,acc){function wrap(func){return geo.util.isFunction(func)?function(){return func(acc.apply(this,arguments))}:func(acc)}if(!d3)return console.warn("d3 is unavailable, cannot apply color scales."),acc;var domain,cannotHandle=!1,doNotHandle=!0,categorical=!1,min=Number.POSITIVE_INFINITY,max=Number.NEGATIVE_INFINITY;return domain=geo.util.isFunction(acc)?d3.set(data.map(acc)).values():[acc],domain.forEach(function(v){("string"!=typeof v||"object"!=typeof geo.util.convertColor(v))&&(doNotHandle=!1),"string"==typeof v?categorical=!0:isFinite(v)?+v>max?max=+v:min>+v&&(min=+v):cannotHandle=!0}),cannotHandle?acc:doNotHandle?acc:wrap(categorical?domain.length<=10?d3.scale.category10().domain(domain):domain.length<=20?d3.scale.category20().domain(domain):d3.scale.category20().domain(domain):d3.scale.linear().range(["rgb(252,141,89)","rgb(255,255,191)","rgb(145,191,219)"]).domain([min,(min+max)/2,max]))}return $.widget?void $.widget("geojs.geojsMap",{options:{center:{latitude:0,longitude:0},zoom:0,width:null,height:null,layers:[],data:[],tileUrl:"http://tile.openstreetmap.org///.png",baseLayer:"osm",baseRenderer:"vgl"},_create:function(){!this._map&&this.element.length&&(this._map=geo.map({width:this.options.width,height:this.options.height,zoom:this.options.zoom,center:this.options.center,node:this.element.get(0)}),this._baseLayer=this._map.createLayer(this.options.baseLayer,{renderer:this.options.baseRenderer,tileUrl:this.options.tileUrl}),this._resize({width:800,height:600}),this._layers=[],this.update())},update:function(layers){var m_this=this;return this.options.layers=layers||this.options.layers||[],this._layers.forEach(function(layer){layer.clear(),m_this._map.deleteLayer(layer)}),this._layers=this.options.layers.map(function(layer){return layer.data=layer.data||m_this.options.data,(layer.features||[]).forEach(function(feature){var scl,data=feature.data||layer.data||[];"point"===feature.type&&(feature.size?feature._size=geo.util.ensureFunction(feature.size):null===feature.size&&delete feature._size,data.length&&feature._size&&(scl=d3.scale.linear().domain(d3.extent(data,feature._size)).range([5,20]),feature.radius=function(){return scl(feature._size.apply(this,arguments))}),delete feature.size);var key;for(key in feature)feature.hasOwnProperty(key)&&isColorKey(key)&&(feature[key]=makeColorScale(data,feature[key]))}),geo.layer.create(m_this._map,layer)}),this.redraw(),this},map:function(){return this._map},tileUrl:function(url){return this._baseLayer.tileUrl(url),this._baseLayer.updateBaseUrl(),this},_resize:function(size){var width=this.options.width,height=this.options.height;size&&(width=size.width,height=size.height),width||(width=this.element.width()),height||(height=this.element.height()),this._map.resize(0,0,width,height)},redraw:function(){return this._resize(),this}}):void($.fn.geojsMap=function(){throw new Error("The geojs jquery plugin requires jquery ui to be available.")})};$(load)}($||window.$,geo||window.geo,d3||window.d3);
\ No newline at end of file