text: (function(){})();(function(factory){if(typeof define==="function"&&define.amd){define(["jquery"],factory)}else if(typeof exports==="object"){module.exports=factory}else{factory(jQuery)}})(function($){var toFix=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],toBind="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],slice=Array.prototype.slice,nullLowestDeltaTimeout,lowestDelta;if($.event.fixHooks){for(var i=toFix.length;i;){$.event.fixHooks[toFix[--i]]=$.event.mouseHooks}}var special=$.event.special.mousewheel={version:"3.1.11",setup:function(){if(this.addEventListener){for(var i=toBind.length;i;){this.addEventListener(toBind[--i],handler,false)}}else{this.onmousewheel=handler}$.data(this,"mousewheel-line-height",special.getLineHeight(this));$.data(this,"mousewheel-page-height",special.getPageHeight(this))},teardown:function(){if(this.removeEventListener){for(var i=toBind.length;i;){this.removeEventListener(toBind[--i],handler,false)}}else{this.onmousewheel=null}$.removeData(this,"mousewheel-line-height");$.removeData(this,"mousewheel-page-height")},getLineHeight:function(elem){var $parent=$(elem)["offsetParent"in $.fn?"offsetParent":"parent"]();if(!$parent.length){$parent=$("body")}return parseInt($parent.css("fontSize"),10)},getPageHeight:function(elem){return $(elem).height()},settings:{adjustOldDeltas:true,normalizeOffset:true}};$.fn.extend({mousewheel:function(fn){return fn?this.bind("mousewheel",fn):this.trigger("mousewheel")},unmousewheel:function(fn){return this.unbind("mousewheel",fn)}});function handler(event){var orgEvent=event||window.event,args=slice.call(arguments,1),delta=0,deltaX=0,deltaY=0,absDelta=0,offsetX=0,offsetY=0;event=$.event.fix(orgEvent);event.type="mousewheel";if("detail"in orgEvent){deltaY=orgEvent.detail*-1}if("wheelDelta"in orgEvent){deltaY=orgEvent.wheelDelta}if("wheelDeltaY"in orgEvent){deltaY=orgEvent.wheelDeltaY}if("wheelDeltaX"in orgEvent){deltaX=orgEvent.wheelDeltaX*-1}if("axis"in orgEvent&&orgEvent.axis===orgEvent.HORIZONTAL_AXIS){deltaX=deltaY*-1;deltaY=0}delta=deltaY===0?deltaX:deltaY;if("deltaY"in orgEvent){deltaY=orgEvent.deltaY*-1;delta=deltaY}if("deltaX"in orgEvent){deltaX=orgEvent.deltaX;if(deltaY===0){delta=deltaX*-1}}if(deltaY===0&&deltaX===0){return}if(orgEvent.deltaMode===1){var lineHeight=$.data(this,"mousewheel-line-height");delta*=lineHeight;deltaY*=lineHeight;deltaX*=lineHeight}else if(orgEvent.deltaMode===2){var pageHeight=$.data(this,"mousewheel-page-height");delta*=pageHeight;deltaY*=pageHeight;deltaX*=pageHeight}absDelta=Math.max(Math.abs(deltaY),Math.abs(deltaX));if(!lowestDelta||absDelta<lowestDelta){lowestDelta=absDelta;if(shouldAdjustOldDeltas(orgEvent,absDelta)){lowestDelta/=40}}if(shouldAdjustOldDeltas(orgEvent,absDelta)){delta/=40;deltaX/=40;deltaY/=40}delta=Math[delta>=1?"floor":"ceil"](delta/lowestDelta);deltaX=Math[deltaX>=1?"floor":"ceil"](deltaX/lowestDelta);deltaY=Math[deltaY>=1?"floor":"ceil"](deltaY/lowestDelta);if(special.settings.normalizeOffset&&this.getBoundingClientRect){var boundingRect=this.getBoundingClientRect();offsetX=event.clientX-boundingRect.left;offsetY=event.clientY-boundingRect.top}event.deltaX=deltaX;event.deltaY=deltaY;event.deltaFactor=lowestDelta;event.offsetX=offsetX;event.offsetY=offsetY;event.deltaMode=0;args.unshift(event,delta,deltaX,deltaY);if(nullLowestDeltaTimeout){clearTimeout(nullLowestDeltaTimeout)}nullLowestDeltaTimeout=setTimeout(nullLowestDelta,200);return($.event.dispatch||$.event.handle).apply(this,args)}function nullLowestDelta(){lowestDelta=null}function shouldAdjustOldDeltas(orgEvent,absDelta){return special.settings.adjustOldDeltas&&orgEvent.type==="mousewheel"&&absDelta%120===0}});(function(b){b.color={};b.color.make=function(d,e,g,f){var c={};c.r=d||0;c.g=e||0;c.b=g||0;c.a=f!=null?f:1;c.add=function(h,j){for(var k=0;k<h.length;++k){c[h.charAt(k)]+=j}return c.normalize()};c.scale=function(h,j){for(var k=0;k<h.length;++k){c[h.charAt(k)]*=j}return c.normalize()};c.toString=function(){if(c.a>=1){return"rgb("+[c.r,c.g,c.b].join(",")+")"}else{return"rgba("+[c.r,c.g,c.b,c.a].join(",")+")"}};c.normalize=function(){function h(k,j,l){return j<k?k:j>l?l:j}c.r=h(0,parseInt(c.r),255);c.g=h(0,parseInt(c.g),255);c.b=h(0,parseInt(c.b),255);c.a=h(0,c.a,1);return c};c.clone=function(){return b.color.make(c.r,c.b,c.g,c.a)};return c.normalize()};b.color.extract=function(d,e){var c;do{c=d.css(e).toLowerCase();if(c!=""&&c!="transparent"){break}d=d.parent()}while(!b.nodeName(d.get(0),"body"));if(c=="rgba(0, 0, 0, 0)"){c="transparent"}return b.color.parse(c)};b.color.parse=function(c){var d,f=b.color.make;if(d=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c)){return f(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10))}if(d=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c)){return f(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10),parseFloat(d[4]))}if(d=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c)){return f(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55)}if(d=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c)){return f(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55,parseFloat(d[4]))}if(d=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c)){return f(parseInt(d[1],16),parseInt(d[2],16),parseInt(d[3],16))}if(d=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c)){return f(parseInt(d[1]+d[1],16),parseInt(d[2]+d[2],16),parseInt(d[3]+d[3],16))}var e=b.trim(c).toLowerCase();if(e=="transparent"){return f(255,255,255,0)}else{d=a[e]||[0,0,0];return f(d[0],d[1],d[2])}};var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);(function(c){function b(av,ai,J,af){var Q=[],O={colors:["#edc240","#afd8f8","#cb4b4b","#4da74d","#9440ed"],legend:{show:true,noColumns:1,labelFormatter:null,labelBoxBorderColor:"#ccc",container:null,position:"ne",margin:5,backgroundColor:null,backgroundOpacity:.85},xaxis:{show:null,position:"bottom",mode:null,color:null,tickColor:null,transform:null,inverseTransform:null,min:null,max:null,autoscaleMargin:null,ticks:null,tickFormatter:null,labelWidth:null,labelHeight:null,reserveSpace:null,tickLength:null,alignTicksWithAxis:null,tickDecimals:null,tickSize:null,minTickSize:null,monthNames:null,timeformat:null,twelveHourClock:false},yaxis:{autoscaleMargin:.02,position:"left"},xaxes:[],yaxes:[],series:{points:{show:false,radius:3,lineWidth:2,fill:true,fillColor:"#ffffff",symbol:"circle"},lines:{lineWidth:2,fill:false,fillColor:null,steps:false},bars:{show:false,lineWidth:2,barWidth:1,fill:true,fillColor:null,align:"left",horizontal:false},shadowSize:3},grid:{show:true,aboveData:false,color:"#545454",backgroundColor:null,borderColor:null,tickColor:null,labelMargin:5,axisMargin:8,borderWidth:2,minBorderMargin:null,markings:null,markingsColor:"#f4f4f4",markingsLineWidth:2,clickable:false,hoverable:false,autoHighlight:true,mouseActiveRadius:10},hooks:{}},az=null,ad=null,y=null,H=null,A=null,p=[],aw=[],q={left:0,right:0,top:0,bottom:0},G=0,I=0,h=0,w=0,ak={processOptions:[],processRawData:[],processDatapoints:[],drawSeries:[],draw:[],bindEvents:[],drawOverlay:[],shutdown:[]},aq=this;aq.setData=aj;aq.setupGrid=t;aq.draw=W;aq.getPlaceholder=function(){return av};aq.getCanvas=function(){return az};aq.getPlotOffset=function(){return q};aq.width=function(){return h};aq.height=function(){return w};aq.offset=function(){var aB=y.offset();aB.left+=q.left;aB.top+=q.top;return aB};aq.getData=function(){return Q};aq.getAxes=function(){var aC={},aB;c.each(p.concat(aw),function(aD,aE){if(aE){aC[aE.direction+(aE.n!=1?aE.n:"")+"axis"]=aE}});return aC};aq.getXAxes=function(){return p};aq.getYAxes=function(){return aw};aq.c2p=C;aq.p2c=ar;aq.getOptions=function(){return O};aq.highlight=x;aq.unhighlight=T;aq.triggerRedrawOverlay=f;aq.pointOffset=function(aB){return{left:parseInt(p[aA(aB,"x")-1].p2c(+aB.x)+q.left),top:parseInt(aw[aA(aB,"y")-1].p2c(+aB.y)+q.top)}};aq.shutdown=ag;aq.resize=function(){B();g(az);g(ad)};aq.hooks=ak;F(aq);Z(J);X();aj(ai);t();W();ah();function an(aD,aB){aB=[aq].concat(aB);for(var aC=0;aC<aD.length;++aC){aD[aC].apply(this,aB)}}function F(){for(var aB=0;aB<af.length;++aB){var aC=af[aB];aC.init(aq);if(aC.options){c.extend(true,O,aC.options)}}}function Z(aC){var aB;c.extend(true,O,aC);if(O.xaxis.color==null){O.xaxis.color=O.grid.color}if(O.yaxis.color==null){O.yaxis.color=O.grid.color}if(O.xaxis.tickColor==null){O.xaxis.tickColor=O.grid.tickColor}if(O.yaxis.tickColor==null){O.yaxis.tickColor=O.grid.tickColor}if(O.grid.borderColor==null){O.grid.borderColor=O.grid.color}if(O.grid.tickColor==null){O.grid.tickColor=c.color.parse(O.grid.color).scale("a",.22).toString()}for(aB=0;aB<Math.max(1,O.xaxes.length);++aB){O.xaxes[aB]=c.extend(true,{},O.xaxis,O.xaxes[aB])}for(aB=0;aB<Math.max(1,O.yaxes.length);++aB){O.yaxes[aB]=c.extend(true,{},O.yaxis,O.yaxes[aB])}if(O.xaxis.noTicks&&O.xaxis.ticks==null){O.xaxis.ticks=O.xaxis.noTicks}if(O.yaxis.noTicks&&O.yaxis.ticks==null){O.yaxis.ticks=O.yaxis.noTicks}if(O.x2axis){O.xaxes[1]=c.extend(true,{},O.xaxis,O.x2axis);O.xaxes[1].position="top"}if(O.y2axis){O.yaxes[1]=c.extend(true,{},O.yaxis,O.y2axis);O.yaxes[1].position="right"}if(O.grid.coloredAreas){O.grid.markings=O.grid.coloredAreas}if(O.grid.coloredAreasColor){O.grid.markingsColor=O.grid.coloredAreasColor}if(O.lines){c.extend(true,O.series.lines,O.lines)}if(O.points){c.extend(true,O.series.points,O.points)}if(O.bars){c.extend(true,O.series.bars,O.bars)}if(O.shadowSize!=null){O.series.shadowSize=O.shadowSize}for(aB=0;aB<O.xaxes.length;++aB){V(p,aB+1).options=O.xaxes[aB]}for(aB=0;aB<O.yaxes.length;++aB){V(aw,aB+1).options=O.yaxes[aB]}for(var aD in ak){if(O.hooks[aD]&&O.hooks[aD].length){ak[aD]=ak[aD].concat(O.hooks[aD])}}an(ak.processOptions,[O])}function aj(aB){Q=Y(aB);ax();z()}function Y(aE){var aC=[];for(var aB=0;aB<aE.length;++aB){var aD=c.extend(true,{},O.series);if(aE[aB].data!=null){aD.data=aE[aB].data;delete aE[aB].data;c.extend(true,aD,aE[aB]);aE[aB].data=aD.data}else{aD.data=aE[aB]}aC.push(aD)}return aC}function aA(aC,aD){var aB=aC[aD+"axis"];if(typeof aB=="object"){aB=aB.n}if(typeof aB!="number"){aB=1}return aB}function m(){return c.grep(p.concat(aw),function(aB){return aB})}function C(aE){var aC={},aB,aD;for(aB=0;aB<p.length;++aB){aD=p[aB];if(aD&&aD.used){aC["x"+aD.n]=aD.c2p(aE.left)}}for(aB=0;aB<aw.length;++aB){aD=aw[aB];if(aD&&aD.used){aC["y"+aD.n]=aD.c2p(aE.top)}}if(aC.x1!==undefined){aC.x=aC.x1}if(aC.y1!==undefined){aC.y=aC.y1}return aC}function ar(aF){var aD={},aC,aE,aB;for(aC=0;aC<p.length;++aC){aE=p[aC];if(aE&&aE.used){aB="x"+aE.n;if(aF[aB]==null&&aE.n==1){aB="x"}if(aF[aB]!=null){aD.left=aE.p2c(aF[aB]);break}}}for(aC=0;aC<aw.length;++aC){aE=aw[aC];if(aE&&aE.used){aB="y"+aE.n;if(aF[aB]==null&&aE.n==1){aB="y"}if(aF[aB]!=null){aD.top=aE.p2c(aF[aB]);break}}}return aD}function V(aC,aB){if(!aC[aB-1]){aC[aB-1]={n:aB,direction:aC==p?"x":"y",options:c.extend(true,{},aC==p?O.xaxis:O.yaxis)}}return aC[aB-1]}function ax(){var aG;var aM=Q.length,aB=[],aE=[];for(aG=0;aG<Q.length;++aG){var aJ=Q[aG].color;if(aJ!=null){--aM;if(typeof aJ=="number"){aE.push(aJ)}else{aB.push(c.color.parse(Q[aG].color))}}}for(aG=0;aG<aE.length;++aG){aM=Math.max(aM,aE[aG]+1)}var aC=[],aF=0;aG=0;while(aC.length<aM){var aI;if(O.colors.length==aG){aI=c.color.make(100,100,100)}else{aI=c.color.parse(O.colors[aG])}var aD=aF%2==1?-1:1;aI.scale("rgb",1+aD*Math.ceil(aF/2)*.2);aC.push(aI);++aG;if(aG>=O.colors.length){aG=0;++aF}}var aH=0,aN;for(aG=0;aG<Q.length;++aG){aN=Q[aG];if(aN.color==null){aN.color=aC[aH].toString();++aH}else{if(typeof aN.color=="number"){aN.color=aC[aN.color].toString()}}if(aN.lines.show==null){var aL,aK=true;for(aL in aN){if(aN[aL]&&aN[aL].show){aK=false;break}}if(aK){aN.lines.show=true}}aN.xaxis=V(p,aA(aN,"x"));aN.yaxis=V(aw,aA(aN,"y"))}}function z(){var aO=Number.POSITIVE_INFINITY,aI=Number.NEGATIVE_INFINITY,aB=Number.MAX_VALUE,aU,aS,aR,aN,aD,aJ,aT,aP,aH,aG,aC,a0,aX,aL;function aF(a3,a2,a1){if(a2<a3.datamin&&a2!=-aB){a3.datamin=a2}if(a1>a3.datamax&&a1!=aB){a3.datamax=a1}}c.each(m(),function(a1,a2){a2.datamin=aO;a2.datamax=aI;a2.used=false});for(aU=0;aU<Q.length;++aU){aJ=Q[aU];aJ.datapoints={points:[]};an(ak.processRawData,[aJ,aJ.data,aJ.datapoints])}for(aU=0;aU<Q.length;++aU){aJ=Q[aU];var aZ=aJ.data,aW=aJ.datapoints.format;if(!aW){aW=[];aW.push({x:true,number:true,required:true});aW.push({y:true,number:true,required:true});if(aJ.bars.show||aJ.lines.show&&aJ.lines.fill){aW.push({y:true,number:true,required:false,defaultValue:0});if(aJ.bars.horizontal){delete aW[aW.length-1].y;aW[aW.length-1].x=true}}aJ.datapoints.format=aW}if(aJ.datapoints.pointsize!=null){continue}aJ.datapoints.pointsize=aW.length;aP=aJ.datapoints.pointsize;aT=aJ.datapoints.points;insertSteps=aJ.lines.show&&aJ.lines.steps;aJ.xaxis.used=aJ.yaxis.used=true;for(aS=aR=0;aS<aZ.length;++aS,aR+=aP){aL=aZ[aS];var aE=aL==null;if(!aE){for(aN=0;aN<aP;++aN){a0=aL[aN];aX=aW[aN];if(aX){if(aX.number&&a0!=null){a0=+a0;if(isNaN(a0)){a0=null}else{if(a0==Infinity){a0=aB}else{if(a0==-Infinity){a0=-aB}}}}if(a0==null){if(aX.required){aE=true}if(aX.defaultValue!=null){a0=aX.defaultValue}}}aT[aR+aN]=a0}}if(aE){for(aN=0;aN<aP;++aN){a0=aT[aR+aN];if(a0!=null){aX=aW[aN];if(aX.x){aF(aJ.xaxis,a0,a0)}if(aX.y){aF(aJ.yaxis,a0,a0)}}aT[aR+aN]=null}}else{if(insertSteps&&aR>0&&aT[aR-aP]!=null&&aT[aR-aP]!=aT[aR]&&aT[aR-aP+1]!=aT[aR+1]){for(aN=0;aN<aP;++aN){aT[aR+aP+aN]=aT[aR+aN]}aT[aR+1]=aT[aR-aP+1];aR+=aP}}}}for(aU=0;aU<Q.length;++aU){aJ=Q[aU];an(ak.processDatapoints,[aJ,aJ.datapoints])}for(aU=0;aU<Q.length;++aU){aJ=Q[aU];aT=aJ.datapoints.points,aP=aJ.datapoints.pointsize;var aK=aO,aQ=aO,aM=aI,aV=aI;for(aS=0;aS<aT.length;aS+=aP){if(aT[aS]==null){continue}for(aN=0;aN<aP;++aN){a0=aT[aS+aN];aX=aW[aN];if(!aX||a0==aB||a0==-aB){continue}if(aX.x){if(a0<aK){aK=a0}if(a0>aM){aM=a0}}if(aX.y){if(a0<aQ){aQ=a0}if(a0>aV){aV=a0}}}}if(aJ.bars.show){var aY=aJ.bars.align=="left"?0:-aJ.bars.barWidth/2;if(aJ.bars.horizontal){aQ+=aY;aV+=aY+aJ.bars.barWidth}else{aK+=aY;aM+=aY+aJ.bars.barWidth}}aF(aJ.xaxis,aK,aM);aF(aJ.yaxis,aQ,aV)}c.each(m(),function(a1,a2){if(a2.datamin==aO){a2.datamin=null}if(a2.datamax==aI){a2.datamax=null}})}function j(aB,aC){var aD=document.createElement("canvas");aD.className=aC;aD.width=G;aD.height=I;if(!aB){c(aD).css({position:"absolute",left:0,top:0})}c(aD).appendTo(av);if(!aD.getContext){aD=window.G_vmlCanvasManager.initElement(aD)}aD.getContext("2d").save();return aD}function B(){G=av.width();I=av.height();if(G<=0||I<=0){throw"Invalid dimensions for plot, width = "+G+", height = "+I}}function g(aC){if(aC.width!=G){aC.width=G}if(aC.height!=I){aC.height=I}var aB=aC.getContext("2d");aB.restore();aB.save()}function X(){var aC,aB=av.children("canvas.base"),aD=av.children("canvas.overlay");if(aB.length==0||aD==0){av.html("");av.css({padding:0});if(av.css("position")=="static"){av.css("position","relative")}B();az=j(true,"base");ad=j(false,"overlay");aC=false}else{az=aB.get(0);ad=aD.get(0);aC=true}H=az.getContext("2d");A=ad.getContext("2d");y=c([ad,az]);if(aC){av.data("plot").shutdown();aq.resize();A.clearRect(0,0,G,I);y.unbind();av.children().not([az,ad]).remove()}av.data("plot",aq)}function ah(){if(O.grid.hoverable){y.mousemove(aa);y.mouseleave(l)}if(O.grid.clickable){y.click(R)}an(ak.bindEvents,[y])}function ag(){if(M){clearTimeout(M)}y.unbind("mousemove",aa);y.unbind("mouseleave",l);y.unbind("click",R);an(ak.shutdown,[y])}function r(aG){function aC(aH){return aH}var aF,aB,aD=aG.options.transform||aC,aE=aG.options.inverseTransform;if(aG.direction=="x"){aF=aG.scale=h/Math.abs(aD(aG.max)-aD(aG.min));aB=Math.min(aD(aG.max),aD(aG.min))}else{aF=aG.scale=w/Math.abs(aD(aG.max)-aD(aG.min));aF=-aF;aB=Math.max(aD(aG.max),aD(aG.min))}if(aD==aC){aG.p2c=function(aH){return(aH-aB)*aF}}else{aG.p2c=function(aH){return(aD(aH)-aB)*aF}}if(!aE){aG.c2p=function(aH){return aB+aH/aF}}else{aG.c2p=function(aH){return aE(aB+aH/aF)}}}function L(aD){var aB=aD.options,aF,aJ=aD.ticks||[],aI=[],aE,aK=aB.labelWidth,aG=aB.labelHeight,aC;function aH(aM,aL){return c('<div style="position:absolute;top:-10000px;'+aL+'font-size:smaller"><div class="'+aD.direction+"Axis "+aD.direction+aD.n+'Axis">'+aM.join("")+"</div></div>").appendTo(av)}if(aD.direction=="x"){if(aK==null){aK=Math.floor(G/(aJ.length>0?aJ.length:1))}if(aG==null){aI=[];for(aF=0;aF<aJ.length;++aF){aE=aJ[aF].label;if(aE){aI.push('<div class="tickLabel" style="float:left;width:'+aK+'px">'+aE+"</div>")}}if(aI.length>0){aI.push('<div style="clear:left"></div>');aC=aH(aI,"width:10000px;");aG=aC.height();aC.remove()}}}else{if(aK==null||aG==null){for(aF=0;aF<aJ.length;++aF){aE=aJ[aF].label;if(aE){aI.push('<div class="tickLabel">'+aE+"</div>")}}if(aI.length>0){aC=aH(aI,"");if(aK==null){aK=aC.children().width()}if(aG==null){aG=aC.find("div.tickLabel").height()}aC.remove()}}}if(aK==null){aK=0}if(aG==null){aG=0}aD.labelWidth=aK;aD.labelHeight=aG}function au(aD){var aC=aD.labelWidth,aL=aD.labelHeight,aH=aD.options.position,aF=aD.options.tickLength,aG=O.grid.axisMargin,aJ=O.grid.labelMargin,aK=aD.direction=="x"?p:aw,aE;var aB=c.grep(aK,function(aN){return aN&&aN.options.position==aH&&aN.reserveSpace});if(c.inArray(aD,aB)==aB.length-1){aG=0}if(aF==null){aF="full"}var aI=c.grep(aK,function(aN){return aN&&aN.reserveSpace});var aM=c.inArray(aD,aI)==0;if(!aM&&aF=="full"){aF=5}if(!isNaN(+aF)){aJ+=+aF}if(aD.direction=="x"){aL+=aJ;if(aH=="bottom"){q.bottom+=aL+aG;aD.box={top:I-q.bottom,height:aL}}else{aD.box={top:q.top+aG,height:aL};q.top+=aL+aG}}else{aC+=aJ;if(aH=="left"){aD.box={left:q.left+aG,width:aC};q.left+=aC+aG}else{q.right+=aC+aG;aD.box={left:G-q.right,width:aC}}}aD.position=aH;aD.tickLength=aF;aD.box.padding=aJ;aD.innermost=aM}function U(aB){if(aB.direction=="x"){aB.box.left=q.left;aB.box.width=h}else{aB.box.top=q.top;aB.box.height=w}}function t(){var aC,aE=m();c.each(aE,function(aF,aG){aG.show=aG.options.show;if(aG.show==null){aG.show=aG.used}aG.reserveSpace=aG.show||aG.options.reserveSpace;n(aG)});allocatedAxes=c.grep(aE,function(aF){return aF.reserveSpace});q.left=q.right=q.top=q.bottom=0;if(O.grid.show){c.each(allocatedAxes,function(aF,aG){S(aG);P(aG);ap(aG,aG.ticks);L(aG)});for(aC=allocatedAxes.length-1;aC>=0;--aC){au(allocatedAxes[aC])}var aD=O.grid.minBorderMargin;if(aD==null){aD=0;for(aC=0;aC<Q.length;++aC){aD=Math.max(aD,Q[aC].points.radius+Q[aC].points.lineWidth/2)}}for(var aB in q){q[aB]+=O.grid.borderWidth;q[aB]=Math.max(aD,q[aB])}}h=G-q.left-q.right;w=I-q.bottom-q.top;c.each(aE,function(aF,aG){r(aG)});if(O.grid.show){c.each(allocatedAxes,function(aF,aG){U(aG)});k()}o()}function n(aE){var aF=aE.options,aD=+(aF.min!=null?aF.min:aE.datamin),aB=+(aF.max!=null?aF.max:aE.datamax),aH=aB-aD;if(aH==0){var aC=aB==0?1:.01;if(aF.min==null){aD-=aC}if(aF.max==null||aF.min!=null){aB+=aC}}else{var aG=aF.autoscaleMargin;if(aG!=null){if(aF.min==null){aD-=aH*aG;if(aD<0&&aE.datamin!=null&&aE.datamin>=0){aD=0}}if(aF.max==null){aB+=aH*aG;if(aB>0&&aE.datamax!=null&&aE.datamax<=0){aB=0}}}}aE.min=aD;aE.max=aB}function S(aG){var aM=aG.options;var aH;if(typeof aM.ticks=="number"&&aM.ticks>0){aH=aM.ticks}else{aH=.3*Math.sqrt(aG.direction=="x"?G:I)}var aT=(aG.max-aG.min)/aH,aO,aB,aN,aR,aS,aQ,aI;if(aM.mode=="time"){var aJ={second:1e3,minute:60*1e3,hour:60*60*1e3,day:24*60*60*1e3,month:30*24*60*60*1e3,year:365.2425*24*60*60*1e3};var aK=[[1,"second"],[2,"second"],[5,"second"],[10,"second"],[30,"second"],[1,"minute"],[2,"minute"],[5,"minute"],[10,"minute"],[30,"minute"],[1,"hour"],[2,"hour"],[4,"hour"],[8,"hour"],[12,"hour"],[1,"day"],[2,"day"],[3,"day"],[.25,"month"],[.5,"month"],[1,"month"],[2,"month"],[3,"month"],[6,"month"],[1,"year"]];var aC=0;if(aM.minTickSize!=null){if(typeof aM.tickSize=="number"){aC=aM.tickSize}else{aC=aM.minTickSize[0]*aJ[aM.minTickSize[1]]}}for(var aS=0;aS<aK.length-1;++aS){if(aT<(aK[aS][0]*aJ[aK[aS][1]]+aK[aS+1][0]*aJ[aK[aS+1][1]])/2&&aK[aS][0]*aJ[aK[aS][1]]>=aC){break}}aO=aK[aS][0];aN=aK[aS][1];if(aN=="year"){aQ=Math.pow(10,Math.floor(Math.log(aT/aJ.year)/Math.LN10));aI=aT/aJ.year/aQ;if(aI<1.5){aO=1}else{if(aI<3){aO=2}else{if(aI<7.5){aO=5}else{aO=10}}}aO*=aQ}aG.tickSize=aM.tickSize||[aO,aN];aB=function(aX){var a2=[],a0=aX.tickSize[0],a3=aX.tickSize[1],a1=new Date(aX.min);var aW=a0*aJ[a3];if(a3=="second"){a1.setUTCSeconds(a(a1.getUTCSeconds(),a0))}if(a3=="minute"){a1.setUTCMinutes(a(a1.getUTCMinutes(),a0))}if(a3=="hour"){a1.setUTCHours(a(a1.getUTCHours(),a0))}if(a3=="month"){a1.setUTCMonth(a(a1.getUTCMonth(),a0))}if(a3=="year"){a1.setUTCFullYear(a(a1.getUTCFullYear(),a0))}a1.setUTCMilliseconds(0);if(aW>=aJ.minute){a1.setUTCSeconds(0)}if(aW>=aJ.hour){a1.setUTCMinutes(0)}if(aW>=aJ.day){a1.setUTCHours(0)}if(aW>=aJ.day*4){a1.setUTCDate(1)}if(aW>=aJ.year){a1.setUTCMonth(0)}var a5=0,a4=Number.NaN,aY;do{aY=a4;a4=a1.getTime();a2.push(a4);if(a3=="month"){if(a0<1){a1.setUTCDate(1);var aV=a1.getTime();a1.setUTCMonth(a1.getUTCMonth()+1);var aZ=a1.getTime();a1.setTime(a4+a5*aJ.hour+(aZ-aV)*a0);a5=a1.getUTCHours();a1.setUTCHours(0)}else{a1.setUTCMonth(a1.getUTCMonth()+a0)}}else{if(a3=="year"){a1.setUTCFullYear(a1.getUTCFullYear()+a0)}else{a1.setTime(a4+aW)}}}while(a4<aX.max&&a4!=aY);return a2};aR=function(aV,aY){var a0=new Date(aV);if(aM.timeformat!=null){return c.plot.formatDate(a0,aM.timeformat,aM.monthNames)}var aW=aY.tickSize[0]*aJ[aY.tickSize[1]];var aX=aY.max-aY.min;var aZ=aM.twelveHourClock?" %p":"";if(aW<aJ.minute){fmt="%h:%M:%S"+aZ}else{if(aW<aJ.day){if(aX<2*aJ.day){fmt="%h:%M"+aZ}else{fmt="%b %d %h:%M"+aZ}}else{if(aW<aJ.month){fmt="%b %d"}else{if(aW<aJ.year){if(aX<aJ.year){fmt="%b"}else{fmt="%b %y"}}else{fmt="%y"}}}}return c.plot.formatDate(a0,fmt,aM.monthNames)}}else{var aU=aM.tickDecimals;var aP=-Math.floor(Math.log(aT)/Math.LN10);if(aU!=null&&aP>aU){aP=aU}aQ=Math.pow(10,-aP);aI=aT/aQ;if(aI<1.5){aO=1}else{if(aI<3){aO=2;if(aI>2.25&&(aU==null||aP+1<=aU)){aO=2.5;++aP}}else{if(aI<7.5){aO=5}else{aO=10}}}aO*=aQ;if(aM.minTickSize!=null&&aO<aM.minTickSize){aO=aM.minTickSize}aG.tickDecimals=Math.max(0,aU!=null?aU:aP);aG.tickSize=aM.tickSize||aO;aB=function(aX){var aZ=[];var a0=a(aX.min,aX.tickSize),aW=0,aV=Number.NaN,aY;do{aY=aV;aV=a0+aW*aX.tickSize;aZ.push(aV);++aW}while(aV<aX.max&&aV!=aY);return aZ};aR=function(aV,aW){return aV.toFixed(aW.tickDecimals)}}if(aM.alignTicksWithAxis!=null){var aF=(aG.direction=="x"?p:aw)[aM.alignTicksWithAxis-1];if(aF&&aF.used&&aF!=aG){var aL=aB(aG);if(aL.length>0){if(aM.min==null){aG.min=Math.min(aG.min,aL[0])}if(aM.max==null&&aL.length>1){aG.max=Math.max(aG.max,aL[aL.length-1])}}aB=function(aX){var aY=[],aV,aW;for(aW=0;aW<aF.ticks.length;++aW){aV=(aF.ticks[aW].v-aF.min)/(aF.max-aF.min);aV=aX.min+aV*(aX.max-aX.min);aY.push(aV)}return aY};if(aG.mode!="time"&&aM.tickDecimals==null){var aE=Math.max(0,-Math.floor(Math.log(aT)/Math.LN10)+1),aD=aB(aG);if(!(aD.length>1&&/\..*0$/.test((aD[1]-aD[0]).toFixed(aE)))){aG.tickDecimals=aE}}}}aG.tickGenerator=aB;if(c.isFunction(aM.tickFormatter)){aG.tickFormatter=function(aV,aW){return""+aM.tickFormatter(aV,aW)}}else{aG.tickFormatter=aR}}function P(aF){var aH=aF.options.ticks,aG=[];if(aH==null||typeof aH=="number"&&aH>0){aG=aF.tickGenerator(aF)}else{if(aH){if(c.isFunction(aH)){aG=aH({min:aF.min,max:aF.max})}else{aG=aH}}}var aE,aB;aF.ticks=[];for(aE=0;aE<aG.length;++aE){var aC=null;var aD=aG[aE];if(typeof aD=="object"){aB=+aD[0];if(aD.length>1){aC=aD[1]}}else{aB=+aD}if(aC==null){aC=aF.tickFormatter(aB,aF)}if(!isNaN(aB)){aF.ticks.push({v:aB,label:aC})}}}function ap(aB,aC){if(aB.options.autoscaleMargin&&aC.length>0){if(aB.options.min==null){aB.min=Math.min(aB.min,aC[0].v)}if(aB.options.max==null&&aC.length>1){aB.max=Math.max(aB.max,aC[aC.length-1].v)}}}function W(){H.clearRect(0,0,G,I);var aC=O.grid;if(aC.show&&aC.backgroundColor){N()}if(aC.show&&!aC.aboveData){ac()}for(var aB=0;aB<Q.length;++aB){an(ak.drawSeries,[H,Q[aB]]);d(Q[aB])}an(ak.draw,[H]);if(aC.show&&aC.aboveData){ac()}}function D(aB,aI){var aE,aH,aG,aD,aF=m();for(i=0;i<aF.length;++i){aE=aF[i];if(aE.direction==aI){aD=aI+aE.n+"axis";if(!aB[aD]&&aE.n==1){aD=aI+"axis"}if(aB[aD]){aH=aB[aD].from;aG=aB[aD].to;break}}}if(!aB[aD]){aE=aI=="x"?p[0]:aw[0];aH=aB[aI+"1"];aG=aB[aI+"2"]}if(aH!=null&&aG!=null&&aH>aG){var aC=aH;aH=aG;aG=aC}return{from:aH,to:aG,axis:aE}}function N(){H.save();H.translate(q.left,q.top);H.fillStyle=am(O.grid.backgroundColor,w,0,"rgba(255, 255, 255, 0)");H.fillRect(0,0,h,w);H.restore()}function ac(){var aF;H.save();H.translate(q.left,q.top);var aH=O.grid.markings;if(aH){if(c.isFunction(aH)){var aK=aq.getAxes();aK.xmin=aK.xaxis.min;aK.xmax=aK.xaxis.max;aK.ymin=aK.yaxis.min;aK.ymax=aK.yaxis.max;aH=aH(aK)}for(aF=0;aF<aH.length;++aF){var aD=aH[aF],aC=D(aD,"x"),aI=D(aD,"y");if(aC.from==null){aC.from=aC.axis.min}if(aC.to==null){aC.to=aC.axis.max}if(aI.from==null){aI.from=aI.axis.min}if(aI.to==null){aI.to=aI.axis.max}if(aC.to<aC.axis.min||aC.from>aC.axis.max||aI.to<aI.axis.min||aI.from>aI.axis.max){continue}aC.from=Math.max(aC.from,aC.axis.min);aC.to=Math.min(aC.to,aC.axis.max);aI.from=Math.max(aI.from,aI.axis.min);aI.to=Math.min(aI.to,aI.axis.max);if(aC.from==aC.to&&aI.from==aI.to){continue}aC.from=aC.axis.p2c(aC.from);aC.to=aC.axis.p2c(aC.to);aI.from=aI.axis.p2c(aI.from);aI.to=aI.axis.p2c(aI.to);if(aC.from==aC.to||aI.from==aI.to){H.beginPath();H.strokeStyle=aD.color||O.grid.markingsColor;H.lineWidth=aD.lineWidth||O.grid.markingsLineWidth;H.moveTo(aC.from,aI.from);H.lineTo(aC.to,aI.to);H.stroke()}else{H.fillStyle=aD.color||O.grid.markingsColor;H.fillRect(aC.from,aI.to,aC.to-aC.from,aI.from-aI.to)}}}var aK=m(),aM=O.grid.borderWidth;for(var aE=0;aE<aK.length;++aE){var aB=aK[aE],aG=aB.box,aQ=aB.tickLength,aN,aL,aP,aJ;if(!aB.show||aB.ticks.length==0){continue}H.strokeStyle=aB.options.tickColor||c.color.parse(aB.options.color).scale("a",.22).toString();H.lineWidth=1;if(aB.direction=="x"){aN=0;if(aQ=="full"){aL=aB.position=="top"?0:w}else{aL=aG.top-q.top+(aB.position=="top"?aG.height:0)}}else{aL=0;if(aQ=="full"){aN=aB.position=="left"?0:h}else{aN=aG.left-q.left+(aB.position=="left"?aG.width:0)}}if(!aB.innermost){H.beginPath();aP=aJ=0;if(aB.direction=="x"){aP=h}else{aJ=w}if(H.lineWidth==1){aN=Math.floor(aN)+.5;aL=Math.floor(aL)+.5}H.moveTo(aN,aL);H.lineTo(aN+aP,aL+aJ);H.stroke()}H.beginPath();for(aF=0;aF<aB.ticks.length;++aF){var aO=aB.ticks[aF].v;aP=aJ=0;if(aO<aB.min||aO>aB.max||aQ=="full"&&aM>0&&(aO==aB.min||aO==aB.max)){continue}if(aB.direction=="x"){aN=aB.p2c(aO);aJ=aQ=="full"?-w:aQ;if(aB.position=="top"){aJ=-aJ}}else{aL=aB.p2c(aO);aP=aQ=="full"?-h:aQ;if(aB.position=="left"){aP=-aP}}if(H.lineWidth==1){if(aB.direction=="x"){aN=Math.floor(aN)+.5}else{aL=Math.floor(aL)+.5}}H.moveTo(aN,aL);H.lineTo(aN+aP,aL+aJ)}H.stroke()}if(aM){H.lineWidth=aM;H.strokeStyle=O.grid.borderColor;H.strokeRect(-aM/2,-aM/2,h+aM,w+aM)}H.restore()}function k(){av.find(".tickLabels").remove();var aG=['<div class="tickLabels" style="font-size:smaller">'];var aJ=m();for(var aD=0;aD<aJ.length;++aD){var aC=aJ[aD],aF=aC.box;if(!aC.show){continue}aG.push('<div class="'+aC.direction+"Axis "+aC.direction+aC.n+'Axis" style="color:'+aC.options.color+'">');for(var aE=0;aE<aC.ticks.length;++aE){var aH=aC.ticks[aE];if(!aH.label||aH.v<aC.min||aH.v>aC.max){continue}var aK={},aI;if(aC.direction=="x"){aI="center";aK.left=Math.round(q.left+aC.p2c(aH.v)-aC.labelWidth/2);if(aC.position=="bottom"){aK.top=aF.top+aF.padding}else{aK.bottom=I-(aF.top+aF.height-aF.padding)}}else{aK.top=Math.round(q.top+aC.p2c(aH.v)-aC.labelHeight/2);if(aC.position=="left"){aK.right=G-(aF.left+aF.width-aF.padding);aI="right"}else{aK.left=aF.left+aF.padding;aI="left"}}aK.width=aC.labelWidth;var aB=["position:absolute","text-align:"+aI];for(var aL in aK){aB.push(aL+":"+aK[aL]+"px")}aG.push('<div class="tickLabel" style="'+aB.join(";")+'">'+aH.label+"</div>")}aG.push("</div>")}aG.push("</div>");av.append(aG.join(""))}function d(aB){if(aB.lines.show){at(aB)}if(aB.bars.show){e(aB)}if(aB.points.show){ao(aB)}}function at(aE){function aD(aP,aQ,aI,aU,aT){var aV=aP.points,aJ=aP.pointsize,aN=null,aM=null;H.beginPath();for(var aO=aJ;aO<aV.length;aO+=aJ){var aL=aV[aO-aJ],aS=aV[aO-aJ+1],aK=aV[aO],aR=aV[aO+1];if(aL==null||aK==null){continue}if(aS<=aR&&aS<aT.min){if(aR<aT.min){continue}aL=(aT.min-aS)/(aR-aS)*(aK-aL)+aL;aS=aT.min}else{if(aR<=aS&&aR<aT.min){if(aS<aT.min){continue}aK=(aT.min-aS)/(aR-aS)*(aK-aL)+aL;aR=aT.min}}if(aS>=aR&&aS>aT.max){if(aR>aT.max){continue}aL=(aT.max-aS)/(aR-aS)*(aK-aL)+aL;aS=aT.max}else{if(aR>=aS&&aR>aT.max){if(aS>aT.max){continue}aK=(aT.max-aS)/(aR-aS)*(aK-aL)+aL;aR=aT.max}}if(aL<=aK&&aL<aU.min){if(aK<aU.min){continue}aS=(aU.min-aL)/(aK-aL)*(aR-aS)+aS;aL=aU.min}else{if(aK<=aL&&aK<aU.min){if(aL<aU.min){continue}aR=(aU.min-aL)/(aK-aL)*(aR-aS)+aS;aK=aU.min}}if(aL>=aK&&aL>aU.max){if(aK>aU.max){continue}aS=(aU.max-aL)/(aK-aL)*(aR-aS)+aS;aL=aU.max}else{if(aK>=aL&&aK>aU.max){if(aL>aU.max){continue}aR=(aU.max-aL)/(aK-aL)*(aR-aS)+aS;aK=aU.max}}if(aL!=aN||aS!=aM){H.moveTo(aU.p2c(aL)+aQ,aT.p2c(aS)+aI)}aN=aK;aM=aR;H.lineTo(aU.p2c(aK)+aQ,aT.p2c(aR)+aI)}H.stroke()}function aF(aI,aQ,aP){var aW=aI.points,aV=aI.pointsize,aN=Math.min(Math.max(0,aP.min),aP.max),aX=0,aU,aT=false,aM=1,aL=0,aR=0;while(true){if(aV>0&&aX>aW.length+aV){break}aX+=aV;var aZ=aW[aX-aV],aK=aW[aX-aV+aM],aY=aW[aX],aJ=aW[aX+aM];if(aT){if(aV>0&&aZ!=null&&aY==null){aR=aX;aV=-aV;aM=2;continue}if(aV<0&&aX==aL+aV){H.fill();aT=false;aV=-aV;aM=1;aX=aL=aR+aV;continue}}if(aZ==null||aY==null){continue}if(aZ<=aY&&aZ<aQ.min){if(aY<aQ.min){continue}aK=(aQ.min-aZ)/(aY-aZ)*(aJ-aK)+aK;aZ=aQ.min}else{if(aY<=aZ&&aY<aQ.min){if(aZ<aQ.min){continue}aJ=(aQ.min-aZ)/(aY-aZ)*(aJ-aK)+aK;aY=aQ.min}}if(aZ>=aY&&aZ>aQ.max){if(aY>aQ.max){continue}aK=(aQ.max-aZ)/(aY-aZ)*(aJ-aK)+aK;aZ=aQ.max}else{if(aY>=aZ&&aY>aQ.max){if(aZ>aQ.max){continue}aJ=(aQ.max-aZ)/(aY-aZ)*(aJ-aK)+aK;aY=aQ.max}}if(!aT){H.beginPath();H.moveTo(aQ.p2c(aZ),aP.p2c(aN));aT=true}if(aK>=aP.max&&aJ>=aP.max){H.lineTo(aQ.p2c(aZ),aP.p2c(aP.max));H.lineTo(aQ.p2c(aY),aP.p2c(aP.max));continue}else{if(aK<=aP.min&&aJ<=aP.min){H.lineTo(aQ.p2c(aZ),aP.p2c(aP.min));H.lineTo(aQ.p2c(aY),aP.p2c(aP.min));continue}}var aO=aZ,aS=aY;if(aK<=aJ&&aK<aP.min&&aJ>=aP.min){aZ=(aP.min-aK)/(aJ-aK)*(aY-aZ)+aZ;aK=aP.min}else{if(aJ<=aK&&aJ<aP.min&&aK>=aP.min){aY=(aP.min-aK)/(aJ-aK)*(aY-aZ)+aZ;aJ=aP.min}}if(aK>=aJ&&aK>aP.max&&aJ<=aP.max){aZ=(aP.max-aK)/(aJ-aK)*(aY-aZ)+aZ;aK=aP.max}else{if(aJ>=aK&&aJ>aP.max&&aK<=aP.max){aY=(aP.max-aK)/(aJ-aK)*(aY-aZ)+aZ;aJ=aP.max}}if(aZ!=aO){H.lineTo(aQ.p2c(aO),aP.p2c(aK))}H.lineTo(aQ.p2c(aZ),aP.p2c(aK));H.lineTo(aQ.p2c(aY),aP.p2c(aJ));if(aY!=aS){H.lineTo(aQ.p2c(aY),aP.p2c(aJ));H.lineTo(aQ.p2c(aS),aP.p2c(aJ))}}}H.save();H.translate(q.left,q.top);H.lineJoin="round";var aG=aE.lines.lineWidth,aB=aE.shadowSize;if(aG>0&&aB>0){H.lineWidth=aB;H.strokeStyle="rgba(0,0,0,0.1)";var aH=Math.PI/18;aD(aE.datapoints,Math.sin(aH)*(aG/2+aB/2),Math.cos(aH)*(aG/2+aB/2),aE.xaxis,aE.yaxis);H.lineWidth=aB/2;aD(aE.datapoints,Math.sin(aH)*(aG/2+aB/4),Math.cos(aH)*(aG/2+aB/4),aE.xaxis,aE.yaxis)}H.lineWidth=aG;H.strokeStyle=aE.color;var aC=ae(aE.lines,aE.color,0,w);if(aC){H.fillStyle=aC;aF(aE.datapoints,aE.xaxis,aE.yaxis)}if(aG>0){aD(aE.datapoints,0,0,aE.xaxis,aE.yaxis)}H.restore()}function ao(aE){
  function aH(aN,aM,aU,aK,aS,aT,aQ,aJ){var aR=aN.points,aI=aN.pointsize;for(var aL=0;aL<aR.length;aL+=aI){var aP=aR[aL],aO=aR[aL+1];if(aP==null||aP<aT.min||aP>aT.max||aO<aQ.min||aO>aQ.max){continue}H.beginPath();aP=aT.p2c(aP);aO=aQ.p2c(aO)+aK;if(aJ=="circle"){H.arc(aP,aO,aM,0,aS?Math.PI:Math.PI*2,false)}else{aJ(H,aP,aO,aM,aS)}H.closePath();if(aU){H.fillStyle=aU;H.fill()}H.stroke()}}H.save();H.translate(q.left,q.top);var aG=aE.points.lineWidth,aC=aE.shadowSize,aB=aE.points.radius,aF=aE.points.symbol;if(aG>0&&aC>0){var aD=aC/2;H.lineWidth=aD;H.strokeStyle="rgba(0,0,0,0.1)";aH(aE.datapoints,aB,null,aD+aD/2,true,aE.xaxis,aE.yaxis,aF);H.strokeStyle="rgba(0,0,0,0.2)";aH(aE.datapoints,aB,null,aD/2,true,aE.xaxis,aE.yaxis,aF)}H.lineWidth=aG;H.strokeStyle=aE.color;aH(aE.datapoints,aB,ae(aE.points,aE.color),0,false,aE.xaxis,aE.yaxis,aF);H.restore()}function E(aN,aM,aV,aI,aQ,aF,aD,aL,aK,aU,aR,aC){var aE,aT,aJ,aP,aG,aB,aO,aH,aS;if(aR){aH=aB=aO=true;aG=false;aE=aV;aT=aN;aP=aM+aI;aJ=aM+aQ;if(aT<aE){aS=aT;aT=aE;aE=aS;aG=true;aB=false}}else{aG=aB=aO=true;aH=false;aE=aN+aI;aT=aN+aQ;aJ=aV;aP=aM;if(aP<aJ){aS=aP;aP=aJ;aJ=aS;aH=true;aO=false}}if(aT<aL.min||aE>aL.max||aP<aK.min||aJ>aK.max){return}if(aE<aL.min){aE=aL.min;aG=false}if(aT>aL.max){aT=aL.max;aB=false}if(aJ<aK.min){aJ=aK.min;aH=false}if(aP>aK.max){aP=aK.max;aO=false}aE=aL.p2c(aE);aJ=aK.p2c(aJ);aT=aL.p2c(aT);aP=aK.p2c(aP);if(aD){aU.beginPath();aU.moveTo(aE,aJ);aU.lineTo(aE,aP);aU.lineTo(aT,aP);aU.lineTo(aT,aJ);aU.fillStyle=aD(aJ,aP);aU.fill()}if(aC>0&&(aG||aB||aO||aH)){aU.beginPath();aU.moveTo(aE,aJ+aF);if(aG){aU.lineTo(aE,aP+aF)}else{aU.moveTo(aE,aP+aF)}if(aO){aU.lineTo(aT,aP+aF)}else{aU.moveTo(aT,aP+aF)}if(aB){aU.lineTo(aT,aJ+aF)}else{aU.moveTo(aT,aJ+aF)}if(aH){aU.lineTo(aE,aJ+aF)}else{aU.moveTo(aE,aJ+aF)}aU.stroke()}}function e(aD){function aC(aJ,aI,aL,aG,aK,aN,aM){var aO=aJ.points,aF=aJ.pointsize;for(var aH=0;aH<aO.length;aH+=aF){if(aO[aH]==null){continue}E(aO[aH],aO[aH+1],aO[aH+2],aI,aL,aG,aK,aN,aM,H,aD.bars.horizontal,aD.bars.lineWidth)}}H.save();H.translate(q.left,q.top);H.lineWidth=aD.bars.lineWidth;H.strokeStyle=aD.color;var aB=aD.bars.align=="left"?0:-aD.bars.barWidth/2;var aE=aD.bars.fill?function(aF,aG){return ae(aD.bars,aD.color,aF,aG)}:null;aC(aD.datapoints,aB,aB+aD.bars.barWidth,0,aE,aD.xaxis,aD.yaxis);H.restore()}function ae(aD,aB,aC,aF){var aE=aD.fill;if(!aE){return null}if(aD.fillColor){return am(aD.fillColor,aC,aF,aB)}var aG=c.color.parse(aB);aG.a=typeof aE=="number"?aE:.4;aG.normalize();return aG.toString()}function o(){av.find(".legend").remove();if(!O.legend.show){return}var aH=[],aF=false,aN=O.legend.labelFormatter,aM,aJ;for(var aE=0;aE<Q.length;++aE){aM=Q[aE];aJ=aM.label;if(!aJ){continue}if(aE%O.legend.noColumns==0){if(aF){aH.push("</tr>")}aH.push("<tr>");aF=true}if(aN){aJ=aN(aJ,aM)}aH.push('<td class="legendColorBox"><div style="border:1px solid '+O.legend.labelBoxBorderColor+';padding:1px"><div style="width:4px;height:0;border:5px solid '+aM.color+';overflow:hidden"></div></div></td><td class="legendLabel">'+aJ+"</td>")}if(aF){aH.push("</tr>")}if(aH.length==0){return}var aL='<table style="font-size:smaller;color:'+O.grid.color+'">'+aH.join("")+"</table>";if(O.legend.container!=null){c(O.legend.container).html(aL)}else{var aI="",aC=O.legend.position,aD=O.legend.margin;if(aD[0]==null){aD=[aD,aD]}if(aC.charAt(0)=="n"){aI+="top:"+(aD[1]+q.top)+"px;"}else{if(aC.charAt(0)=="s"){aI+="bottom:"+(aD[1]+q.bottom)+"px;"}}if(aC.charAt(1)=="e"){aI+="right:"+(aD[0]+q.right)+"px;"}else{if(aC.charAt(1)=="w"){aI+="left:"+(aD[0]+q.left)+"px;"}}var aK=c('<div class="legend">'+aL.replace('style="','style="position:absolute;'+aI+";")+"</div>").appendTo(av);if(O.legend.backgroundOpacity!=0){var aG=O.legend.backgroundColor;if(aG==null){aG=O.grid.backgroundColor;if(aG&&typeof aG=="string"){aG=c.color.parse(aG)}else{aG=c.color.extract(aK,"background-color")}aG.a=1;aG=aG.toString()}var aB=aK.children();c('<div style="position:absolute;width:'+aB.width()+"px;height:"+aB.height()+"px;"+aI+"background-color:"+aG+';"> </div>').prependTo(aK).css("opacity",O.legend.backgroundOpacity)}}}var ab=[],M=null;function K(aI,aG,aD){var aO=O.grid.mouseActiveRadius,a0=aO*aO+1,aY=null,aR=false,aW,aU;for(aW=Q.length-1;aW>=0;--aW){if(!aD(Q[aW])){continue}var aP=Q[aW],aH=aP.xaxis,aF=aP.yaxis,aV=aP.datapoints.points,aT=aP.datapoints.pointsize,aQ=aH.c2p(aI),aN=aF.c2p(aG),aC=aO/aH.scale,aB=aO/aF.scale;if(aH.options.inverseTransform){aC=Number.MAX_VALUE}if(aF.options.inverseTransform){aB=Number.MAX_VALUE}if(aP.lines.show||aP.points.show){for(aU=0;aU<aV.length;aU+=aT){var aK=aV[aU],aJ=aV[aU+1];if(aK==null){continue}if(aK-aQ>aC||aK-aQ<-aC||aJ-aN>aB||aJ-aN<-aB){continue}var aM=Math.abs(aH.p2c(aK)-aI),aL=Math.abs(aF.p2c(aJ)-aG),aS=aM*aM+aL*aL;if(aS<a0){a0=aS;aY=[aW,aU/aT]}}}if(aP.bars.show&&!aY){var aE=aP.bars.align=="left"?0:-aP.bars.barWidth/2,aX=aE+aP.bars.barWidth;for(aU=0;aU<aV.length;aU+=aT){var aK=aV[aU],aJ=aV[aU+1],aZ=aV[aU+2];if(aK==null){continue}if(Q[aW].bars.horizontal?aQ<=Math.max(aZ,aK)&&aQ>=Math.min(aZ,aK)&&aN>=aJ+aE&&aN<=aJ+aX:aQ>=aK+aE&&aQ<=aK+aX&&aN>=Math.min(aZ,aJ)&&aN<=Math.max(aZ,aJ)){aY=[aW,aU/aT]}}}}if(aY){aW=aY[0];aU=aY[1];aT=Q[aW].datapoints.pointsize;return{datapoint:Q[aW].datapoints.points.slice(aU*aT,(aU+1)*aT),dataIndex:aU,series:Q[aW],seriesIndex:aW}}return null}function aa(aB){if(O.grid.hoverable){u("plothover",aB,function(aC){return aC.hoverable!=false})}}function l(aB){if(O.grid.hoverable){u("plothover",aB,function(aC){return false})}}function R(aB){u("plotclick",aB,function(aC){return aC.clickable!=false})}function u(aC,aB,aD){var aE=y.offset(),aH=aB.pageX-aE.left-q.left,aF=aB.pageY-aE.top-q.top,aJ=C({left:aH,top:aF});aJ.pageX=aB.pageX;aJ.pageY=aB.pageY;var aK=K(aH,aF,aD);if(aK){aK.pageX=parseInt(aK.series.xaxis.p2c(aK.datapoint[0])+aE.left+q.left);aK.pageY=parseInt(aK.series.yaxis.p2c(aK.datapoint[1])+aE.top+q.top)}if(O.grid.autoHighlight){for(var aG=0;aG<ab.length;++aG){var aI=ab[aG];if(aI.auto==aC&&!(aK&&aI.series==aK.series&&aI.point[0]==aK.datapoint[0]&&aI.point[1]==aK.datapoint[1])){T(aI.series,aI.point)}}if(aK){x(aK.series,aK.datapoint,aC)}}av.trigger(aC,[aJ,aK])}function f(){if(!M){M=setTimeout(s,30)}}function s(){M=null;A.save();A.clearRect(0,0,G,I);A.translate(q.left,q.top);var aC,aB;for(aC=0;aC<ab.length;++aC){aB=ab[aC];if(aB.series.bars.show){v(aB.series,aB.point)}else{ay(aB.series,aB.point)}}A.restore();an(ak.drawOverlay,[A])}function x(aD,aB,aF){if(typeof aD=="number"){aD=Q[aD]}if(typeof aB=="number"){var aE=aD.datapoints.pointsize;aB=aD.datapoints.points.slice(aE*aB,aE*(aB+1))}var aC=al(aD,aB);if(aC==-1){ab.push({series:aD,point:aB,auto:aF});f()}else{if(!aF){ab[aC].auto=false}}}function T(aD,aB){if(aD==null&&aB==null){ab=[];f()}if(typeof aD=="number"){aD=Q[aD]}if(typeof aB=="number"){aB=aD.data[aB]}var aC=al(aD,aB);if(aC!=-1){ab.splice(aC,1);f()}}function al(aD,aE){for(var aB=0;aB<ab.length;++aB){var aC=ab[aB];if(aC.series==aD&&aC.point[0]==aE[0]&&aC.point[1]==aE[1]){return aB}}return-1}function ay(aE,aD){var aC=aD[0],aI=aD[1],aH=aE.xaxis,aG=aE.yaxis;if(aC<aH.min||aC>aH.max||aI<aG.min||aI>aG.max){return}var aF=aE.points.radius+aE.points.lineWidth/2;A.lineWidth=aF;A.strokeStyle=c.color.parse(aE.color).scale("a",.5).toString();var aB=1.5*aF,aC=aH.p2c(aC),aI=aG.p2c(aI);A.beginPath();if(aE.points.symbol=="circle"){A.arc(aC,aI,aB,0,2*Math.PI,false)}else{aE.points.symbol(A,aC,aI,aB,false)}A.closePath();A.stroke()}function v(aE,aB){A.lineWidth=aE.bars.lineWidth;A.strokeStyle=c.color.parse(aE.color).scale("a",.5).toString();var aD=c.color.parse(aE.color).scale("a",.5).toString();var aC=aE.bars.align=="left"?0:-aE.bars.barWidth/2;E(aB[0],aB[1],aB[2]||0,aC,aC+aE.bars.barWidth,0,function(){return aD},aE.xaxis,aE.yaxis,A,aE.bars.horizontal,aE.bars.lineWidth)}function am(aJ,aB,aH,aC){if(typeof aJ=="string"){return aJ}else{var aI=H.createLinearGradient(0,aH,0,aB);for(var aE=0,aD=aJ.colors.length;aE<aD;++aE){var aF=aJ.colors[aE];if(typeof aF!="string"){var aG=c.color.parse(aC);if(aF.brightness!=null){aG=aG.scale("rgb",aF.brightness)}if(aF.opacity!=null){aG.a*=aF.opacity}aF=aG.toString()}aI.addColorStop(aE/(aD-1),aF)}return aI}}}c.plot=function(g,e,d){var f=new b(c(g),e,d,c.plot.plugins);return f};c.plot.version="0.7";c.plot.plugins=[];c.plot.formatDate=function(l,f,h){var o=function(d){d=""+d;return d.length==1?"0"+d:d};var e=[];var p=false,j=false;var n=l.getUTCHours();var k=n<12;if(h==null){h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}if(f.search(/%p|%P/)!=-1){if(n>12){n=n-12}else{if(n==0){n=12}}}for(var g=0;g<f.length;++g){var m=f.charAt(g);if(p){switch(m){case"h":m=""+n;break;case"H":m=o(n);break;case"M":m=o(l.getUTCMinutes());break;case"S":m=o(l.getUTCSeconds());break;case"d":m=""+l.getUTCDate();break;case"m":m=""+(l.getUTCMonth()+1);break;case"y":m=""+l.getUTCFullYear();break;case"b":m=""+h[l.getUTCMonth()];break;case"p":m=k?"am":"pm";break;case"P":m=k?"AM":"PM";break;case"0":m="";j=true;break}if(m&&j){m=o(m);j=false}e.push(m);if(!j){p=false}}else{if(m=="%"){p=true}else{e.push(m)}}}return e.join("")};function a(e,d){return d*Math.floor(e/d)}})(jQuery);(function($){var options={crosshair:{mode:null,color:"rgba(0, 0, 0, 0.5)",lineWidth:1}};function log10(val){return Math.log(val)/Math.LN10}function format_number(val,n){if(n===undefined)n=3;if(val===0)return 0;if(n<=0)throw new Error("Significant figures must be greater than zero.");n=Math.floor(n+.5);var sign=val>=0?"":"-";val=Math.abs(val);var before=Math.floor(log10(val))+1;if(before>n){val=val.toPrecision(n);return sign+val.replace("+","")}else if(before<0){var mantissa=val*pow(10,abs(before)+1);before-=1;return sign+mantissa.toFixed(n-1)+"e"+before}else{return sign+val.toFixed(n-before)}}function init(plot){var crosshair={x:-1,y:-1,locked:false};plot.setCrosshair=function setCrosshair(pos){if(!pos)crosshair.x=-1;else{var o=plot.p2c(pos);crosshair.x=Math.max(0,Math.min(o.left,plot.width()));crosshair.y=Math.max(0,Math.min(o.top,plot.height()))}plot.triggerRedrawOverlay()};plot.clearCrosshair=plot.setCrosshair;plot.lockCrosshair=function lockCrosshair(pos){if(pos)plot.setCrosshair(pos);crosshair.locked=true};plot.unlockCrosshair=function unlockCrosshair(){crosshair.locked=false};function onMouseOut(e){if(crosshair.locked)return;if(crosshair.x!=-1){crosshair.x=-1;plot.triggerRedrawOverlay()}}function onMouseMove(e){if(crosshair.locked)return;if(plot.getSelection&&plot.getSelection()){crosshair.x=-1;return}var offset=plot.offset();crosshair.x=Math.max(0,Math.min(e.pageX-offset.left,plot.width()));crosshair.y=Math.max(0,Math.min(e.pageY-offset.top,plot.height()));plot.triggerRedrawOverlay()}plot.hooks.bindEvents.push(function(plot,eventHolder){if(!plot.getOptions().crosshair.mode)return;eventHolder.mouseout(onMouseOut);eventHolder.mousemove(onMouseMove)});plot.hooks.drawOverlay.push(function(plot,ctx){var c=plot.getOptions().crosshair;if(!c.mode)return;var plotOffset=plot.getPlotOffset();ctx.save();ctx.translate(plotOffset.left,plotOffset.top);if(crosshair.x!=-1){var pos=plot.c2p({left:crosshair.x,top:crosshair.y});text=format_number(pos.x,3)+","+format_number(pos.y,3);var fontheight=13;ctx.fillStyle=c.color;ctx.font=fontheight+"px Verdana";var twidth=ctx.measureText(text).width;var dx=0,dy=0;if(crosshair.y<fontheight+3){twidth+=14;dy=fontheight;if(crosshair.x<=plot.width()-(twidth+5))dx+=14}else{dy=-5}if(crosshair.x>plot.width()-(twidth+5)){ctx.textAlign="right";dx+=-3}else{ctx.textAlign="left";dx+=3}ctx.fillText(text,crosshair.x+dx,crosshair.y+dy);ctx.strokeStyle=c.color;ctx.lineWidth=c.lineWidth;ctx.lineJoin="round";ctx.beginPath();if(c.mode.indexOf("x")!=-1){ctx.moveTo(crosshair.x,0);ctx.lineTo(crosshair.x,plot.height())}if(c.mode.indexOf("y")!=-1){ctx.moveTo(0,crosshair.y);ctx.lineTo(plot.width(),crosshair.y)}ctx.stroke()}ctx.restore()});plot.hooks.shutdown.push(function(plot,eventHolder){eventHolder.unbind("mouseout",onMouseOut);eventHolder.unbind("mousemove",onMouseMove)})}$.plot.plugins.push({init:init,options:options,name:"crosshair_GS",version:"1.0"})})(jQuery);function assert(condition,message){if(!condition){throw new Error(message||"Assert Failed")}}var Node=function(p,t){this.point=p;this.triangle=t||null;this.next=null;this.prev=null;this.value=p.x};var AdvancingFront=function(head,tail){this.head_=head;this.tail_=tail;this.search_node_=head};AdvancingFront.prototype.head=function(){return this.head_};AdvancingFront.prototype.setHead=function(node){this.head_=node};AdvancingFront.prototype.tail=function(){return this.tail_};AdvancingFront.prototype.setTail=function(node){this.tail_=node};AdvancingFront.prototype.search=function(){return this.search_node_};AdvancingFront.prototype.setSearch=function(node){this.search_node_=node};AdvancingFront.prototype.findSearchNode=function(){return this.search_node_};AdvancingFront.prototype.locateNode=function(x){var node=this.search_node_;if(x<node.value){while(node=node.prev){if(x>=node.value){this.search_node_=node;return node}}}else{while(node=node.next){if(x<node.value){this.search_node_=node.prev;return node.prev}}}return null};AdvancingFront.prototype.locatePoint=function(point){var px=point.x;var node=this.findSearchNode(px);var nx=node.point.x;if(px===nx){if(point!==node.point){if(point===node.prev.point){node=node.prev}else if(point===node.next.point){node=node.next}else{throw new Error("poly2tri Invalid AdvancingFront.locatePoint() call")}}}else if(px<nx){while(node=node.prev){if(point===node.point){break}}}else{while(node=node.next){if(point===node.point){break}}}if(node){this.search_node_=node}return node};var Point=function(x,y){this.x=+x||0;this.y=+y||0;this._p2t_edge_list=null};Point.prototype.toJSON=function(){return{x:this.x,y:this.y}};Point.prototype.clone=function(){return new Point(this.x,this.y)};Point.prototype.set_zero=function(){this.x=0;this.y=0;return this};Point.prototype.set=function(x,y){this.x=+x||0;this.y=+y||0;return this};Point.prototype.negate=function(){this.x=-this.x;this.y=-this.y;return this};Point.prototype.add=function(n){this.x+=n.x;this.y+=n.y;return this};Point.prototype.sub=function(n){this.x-=n.x;this.y-=n.y;return this};Point.prototype.mul=function(s){this.x*=s;this.y*=s;return this};Point.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)};Point.prototype.normalize=function(){var len=this.length();this.x/=len;this.y/=len;return len};Point.prototype.equals=function(p){return this.x===p.x&&this.y===p.y};Point.negate=function(p){return new Point(-p.x,-p.y)};Point.add=function(a,b){return new Point(a.x+b.x,a.y+b.y)};Point.sub=function(a,b){return new Point(a.x-b.x,a.y-b.y)};Point.mul=function(s,p){return new Point(s*p.x,s*p.y)};Point.cross=function(a,b){if(typeof a==="number"){if(typeof b==="number"){return a*b}else{return new Point(-a*b.y,a*b.x)}}else{if(typeof b==="number"){return new Point(b*a.y,-b*a.x)}else{return a.x*b.y-a.y*b.x}}};Point.compare=function(a,b){if(a.y===b.y){return a.x-b.x}else{return a.y-b.y}};Point.toString=function(p){var s=p.toString();return s==="[object Object]"?toStringBase(p):s};Point.equals=function(a,b){return a.x===b.x&&a.y===b.y};Point.dot=function(a,b){return a.x*b.x+a.y*b.y};var PointError=function(message,points){this.name="PointError";this.points=points=points||[];this.message=message||"Invalid Points!"};PointError.prototype=new Error;PointError.prototype.constructor=PointError;var EPSILON=1e-12;var Orientation={CW:1,CCW:-1,COLLINEAR:0};function orient2d(pa,pb,pc){var detleft=(pa.x-pc.x)*(pb.y-pc.y);var detright=(pa.y-pc.y)*(pb.x-pc.x);var val=detleft-detright;if(val>-EPSILON&&val<EPSILON){return Orientation.COLLINEAR}else if(val>0){return Orientation.CCW}else{return Orientation.CW}}function inScanArea(pa,pb,pc,pd){var oadb=(pa.x-pb.x)*(pd.y-pb.y)-(pd.x-pb.x)*(pa.y-pb.y);if(oadb>=-EPSILON){return false}var oadc=(pa.x-pc.x)*(pd.y-pc.y)-(pd.x-pc.x)*(pa.y-pc.y);if(oadc<=EPSILON){return false}return true}function isAngleObtuse(pa,pb,pc){var ax=pb.x-pa.x;var ay=pb.y-pa.y;var bx=pc.x-pa.x;var by=pc.y-pa.y;return ax*bx+ay*by<0}function triangulate(tcx){tcx.initTriangulation();tcx.createAdvancingFront();sweepPoints(tcx);finalizationPolygon(tcx)}function sweepPoints(tcx){var i,len=tcx.pointCount();for(i=1;i<len;++i){var point=tcx.getPoint(i);var node=pointEvent(tcx,point);var edges=point._p2t_edge_list;for(var j=0;edges&&j<edges.length;++j){edgeEventByEdge(tcx,edges[j],node)}}}function finalizationPolygon(tcx){var t=tcx.front().head().next.triangle;var p=tcx.front().head().next.point;while(!t.getConstrainedEdgeCW(p)){t=t.neighborCCW(p)}tcx.meshClean(t)}function pointEvent(tcx,point){var node=tcx.locateNode(point);var new_node=newFrontTriangle(tcx,point,node);if(point.x<=node.point.x+EPSILON){fill(tcx,node)}fillAdvancingFront(tcx,new_node);return new_node}function edgeEventByEdge(tcx,edge,node){tcx.edge_event.constrained_edge=edge;tcx.edge_event.right=edge.p.x>edge.q.x;if(isEdgeSideOfTriangle(node.triangle,edge.p,edge.q)){return}fillEdgeEvent(tcx,edge,node);edgeEventByPoints(tcx,edge.p,edge.q,node.triangle,edge.q)}function edgeEventByPoints(tcx,ep,eq,triangle,point){if(isEdgeSideOfTriangle(triangle,ep,eq)){return}var p1=triangle.pointCCW(point);var o1=orient2d(eq,p1,ep);if(o1===Orientation.COLLINEAR){throw new PointError("poly2tri EdgeEvent: Collinear not supported!",[eq,p1,ep])}var p2=triangle.pointCW(point);var o2=orient2d(eq,p2,ep);if(o2===Orientation.COLLINEAR){throw new PointError("poly2tri EdgeEvent: Collinear not supported!",[eq,p2,ep])}if(o1===o2){if(o1===Orientation.CW){triangle=triangle.neighborCCW(point)}else{triangle=triangle.neighborCW(point)}edgeEventByPoints(tcx,ep,eq,triangle,point)}else{flipEdgeEvent(tcx,ep,eq,triangle,point)}}function isEdgeSideOfTriangle(triangle,ep,eq){var index=triangle.edgeIndex(ep,eq);if(index!==-1){triangle.markConstrainedEdgeByIndex(index);var t=triangle.getNeighbor(index);if(t){t.markConstrainedEdgeByPoints(ep,eq)}return true}return false}function newFrontTriangle(tcx,point,node){var triangle=new Triangle(point,node.point,node.next.point);triangle.markNeighbor(node.triangle);tcx.addToMap(triangle);var new_node=new Node(point);new_node.next=node.next;new_node.prev=node;node.next.prev=new_node;node.next=new_node;if(!legalize(tcx,triangle)){tcx.mapTriangleToNodes(triangle)}return new_node}function fill(tcx,node){var triangle=new Triangle(node.prev.point,node.point,node.next.point);triangle.markNeighbor(node.prev.triangle);triangle.markNeighbor(node.triangle);tcx.addToMap(triangle);node.prev.next=node.next;node.next.prev=node.prev;if(!legalize(tcx,triangle)){tcx.mapTriangleToNodes(triangle)}}function fillAdvancingFront(tcx,n){var node=n.next;while(node.next){if(isAngleObtuse(node.point,node.next.point,node.prev.point)){break}fill(tcx,node);node=node.next}node=n.prev;while(node.prev){if(isAngleObtuse(node.point,node.next.point,node.prev.point)){break}fill(tcx,node);node=node.prev}if(n.next&&n.next.next){if(isBasinAngleRight(n)){fillBasin(tcx,n)}}}function isBasinAngleRight(node){var ax=node.point.x-node.next.next.point.x;var ay=node.point.y-node.next.next.point.y;assert(ay>=0,"unordered y");return ax>=0||Math.abs(ax)<ay}function legalize(tcx,t){for(var i=0;i<3;++i){if(t.delaunay_edge[i]){continue}var ot=t.getNeighbor(i);if(ot){var p=t.getPoint(i);var op=ot.oppositePoint(t,p);var oi=ot.index(op);if(ot.constrained_edge[oi]||ot.delaunay_edge[oi]){t.constrained_edge[i]=ot.constrained_edge[oi];continue}var inside=inCircle(p,t.pointCCW(p),t.pointCW(p),op);if(inside){t.delaunay_edge[i]=true;ot.delaunay_edge[oi]=true;rotateTrianglePair(t,p,ot,op);var not_legalized=!legalize(tcx,t);if(not_legalized){tcx.mapTriangleToNodes(t)}not_legalized=!legalize(tcx,ot);if(not_legalized){tcx.mapTriangleToNodes(ot)}t.delaunay_edge[i]=false;ot.delaunay_edge[oi]=false;return true}}}return false}function inCircle(pa,pb,pc,pd){var adx=pa.x-pd.x;var ady=pa.y-pd.y;var bdx=pb.x-pd.x;var bdy=pb.y-pd.y;var adxbdy=adx*bdy;var bdxady=bdx*ady;var oabd=adxbdy-bdxady;if(oabd<=0){return false}var cdx=pc.x-pd.x;var cdy=pc.y-pd.y;var cdxady=cdx*ady;var adxcdy=adx*cdy;var ocad=cdxady-adxcdy;if(ocad<=0){return false}var bdxcdy=bdx*cdy;var cdxbdy=cdx*bdy;var alift=adx*adx+ady*ady;var blift=bdx*bdx+bdy*bdy;var clift=cdx*cdx+cdy*cdy;var det=alift*(bdxcdy-cdxbdy)+blift*ocad+clift*oabd;return det>0}function rotateTrianglePair(t,p,ot,op){var n1,n2,n3,n4;n1=t.neighborCCW(p);n2=t.neighborCW(p);n3=ot.neighborCCW(op);n4=ot.neighborCW(op);var ce1,ce2,ce3,ce4;ce1=t.getConstrainedEdgeCCW(p);ce2=t.getConstrainedEdgeCW(p);ce3=ot.getConstrainedEdgeCCW(op);ce4=ot.getConstrainedEdgeCW(op);var de1,de2,de3,de4;de1=t.getDelaunayEdgeCCW(p);de2=t.getDelaunayEdgeCW(p);de3=ot.getDelaunayEdgeCCW(op);de4=ot.getDelaunayEdgeCW(op);t.legalize(p,op);ot.legalize(op,p);ot.setDelaunayEdgeCCW(p,de1);t.setDelaunayEdgeCW(p,de2);t.setDelaunayEdgeCCW(op,de3);ot.setDelaunayEdgeCW(op,de4);ot.setConstrainedEdgeCCW(p,ce1);t.setConstrainedEdgeCW(p,ce2);t.setConstrainedEdgeCCW(op,ce3);ot.setConstrainedEdgeCW(op,ce4);t.clearNeighbors();ot.clearNeighbors();if(n1){ot.markNeighbor(n1)}if(n2){t.markNeighbor(n2)}if(n3){t.markNeighbor(n3)}if(n4){ot.markNeighbor(n4)}t.markNeighbor(ot)}function fillBasin(tcx,node){if(orient2d(node.point,node.next.point,node.next.next.point)===Orientation.CCW){tcx.basin.left_node=node.next.next}else{tcx.basin.left_node=node.next}tcx.basin.bottom_node=tcx.basin.left_node;while(tcx.basin.bottom_node.next&&tcx.basin.bottom_node.point.y>=tcx.basin.bottom_node.next.point.y){tcx.basin.bottom_node=tcx.basin.bottom_node.next}if(tcx.basin.bottom_node===tcx.basin.left_node){return}tcx.basin.right_node=tcx.basin.bottom_node;while(tcx.basin.right_node.next&&tcx.basin.right_node.point.y<tcx.basin.right_node.next.point.y){tcx.basin.right_node=tcx.basin.right_node.next}if(tcx.basin.right_node===tcx.basin.bottom_node){return}tcx.basin.width=tcx.basin.right_node.point.x-tcx.basin.left_node.point.x;tcx.basin.left_highest=tcx.basin.left_node.point.y>tcx.basin.right_node.point.y;fillBasinReq(tcx,tcx.basin.bottom_node)}function fillBasinReq(tcx,node){if(isShallow(tcx,node)){return}fill(tcx,node);var o;if(node.prev===tcx.basin.left_node&&node.next===tcx.basin.right_node){return}else if(node.prev===tcx.basin.left_node){o=orient2d(node.point,node.next.point,node.next.next.point);if(o===Orientation.CW){return}node=node.next}else if(node.next===tcx.basin.right_node){o=orient2d(node.point,node.prev.point,node.prev.prev.point);if(o===Orientation.CCW){return}node=node.prev}else{if(node.prev.point.y<node.next.point.y){node=node.prev}else{node=node.next}}fillBasinReq(tcx,node)}function isShallow(tcx,node){var height;if(tcx.basin.left_highest){height=tcx.basin.left_node.point.y-node.point.y}else{height=tcx.basin.right_node.point.y-node.point.y}if(tcx.basin.width>height){return true}return false}function fillEdgeEvent(tcx,edge,node){if(tcx.edge_event.right){fillRightAboveEdgeEvent(tcx,edge,node)}else{fillLeftAboveEdgeEvent(tcx,edge,node)}}function fillRightAboveEdgeEvent(tcx,edge,node){while(node.next.point.x<edge.p.x){if(orient2d(edge.q,node.next.point,edge.p)===Orientation.CCW){fillRightBelowEdgeEvent(tcx,edge,node)}else{node=node.next}}}function fillRightBelowEdgeEvent(tcx,edge,node){if(node.point.x<edge.p.x){if(orient2d(node.point,node.next.point,node.next.next.point)===Orientation.CCW){fillRightConcaveEdgeEvent(tcx,edge,node)}else{fillRightConvexEdgeEvent(tcx,edge,node);fillRightBelowEdgeEvent(tcx,edge,node)}}}function fillRightConcaveEdgeEvent(tcx,edge,node){fill(tcx,node.next);if(node.next.point!==edge.p){if(orient2d(edge.q,node.next.point,edge.p)===Orientation.CCW){if(orient2d(node.point,node.next.point,node.next.next.point)===Orientation.CCW){fillRightConcaveEdgeEvent(tcx,edge,node)}else{}}}}function fillRightConvexEdgeEvent(tcx,edge,node){if(orient2d(node.next.point,node.next.next.point,node.next.next.next.point)===Orientation.CCW){fillRightConcaveEdgeEvent(tcx,edge,node.next)}else{if(orient2d(edge.q,node.next.next.point,edge.p)===Orientation.CCW){fillRightConvexEdgeEvent(tcx,edge,node.next)}else{}}}function fillLeftAboveEdgeEvent(tcx,edge,node){while(node.prev.point.x>edge.p.x){if(orient2d(edge.q,node.prev.point,edge.p)===Orientation.CW){fillLeftBelowEdgeEvent(tcx,edge,node)}else{node=node.prev}}}function fillLeftBelowEdgeEvent(tcx,edge,node){if(node.point.x>edge.p.x){if(orient2d(node.point,node.prev.point,node.prev.prev.point)===Orientation.CW){fillLeftConcaveEdgeEvent(tcx,edge,node)}else{fillLeftConvexEdgeEvent(tcx,edge,node);fillLeftBelowEdgeEvent(tcx,edge,node)}}}function fillLeftConvexEdgeEvent(tcx,edge,node){if(orient2d(node.prev.point,node.prev.prev.point,node.prev.prev.prev.point)===Orientation.CW){fillLeftConcaveEdgeEvent(tcx,edge,node.prev)}else{if(orient2d(edge.q,node.prev.prev.point,edge.p)===Orientation.CW){fillLeftConvexEdgeEvent(tcx,edge,node.prev)}else{}}}function fillLeftConcaveEdgeEvent(tcx,edge,node){fill(tcx,node.prev);if(node.prev.point!==edge.p){if(orient2d(edge.q,node.prev.point,edge.p)===Orientation.CW){if(orient2d(node.point,node.prev.point,node.prev.prev.point)===Orientation.CW){fillLeftConcaveEdgeEvent(tcx,edge,node)}else{}}}}function flipEdgeEvent(tcx,ep,eq,t,p){var ot=t.neighborAcross(p);assert(ot,"FLIP failed due to missing triangle!");var op=ot.oppositePoint(t,p);if(t.getConstrainedEdgeAcross(p)){var index=t.index(p);throw new PointError("poly2tri Intersecting Constraints",[p,op,t.getPoint((index+1)%3),t.getPoint((index+2)%3)])}if(inScanArea(p,t.pointCCW(p),t.pointCW(p),op)){rotateTrianglePair(t,p,ot,op);tcx.mapTriangleToNodes(t);tcx.mapTriangleToNodes(ot);if(p===eq&&op===ep){if(eq===tcx.edge_event.constrained_edge.q&&ep===tcx.edge_event.constrained_edge.p){t.markConstrainedEdgeByPoints(ep,eq);ot.markConstrainedEdgeByPoints(ep,eq);legalize(tcx,t);legalize(tcx,ot)}else{}}else{var o=orient2d(eq,op,ep);t=nextFlipTriangle(tcx,o,t,ot,p,op);flipEdgeEvent(tcx,ep,eq,t,p)}}else{var newP=nextFlipPoint(ep,eq,ot,op);flipScanEdgeEvent(tcx,ep,eq,t,ot,newP);edgeEventByPoints(tcx,ep,eq,t,p)}}function nextFlipTriangle(tcx,o,t,ot,p,op){var edge_index;if(o===Orientation.CCW){edge_index=ot.edgeIndex(p,op);ot.delaunay_edge[edge_index]=true;legalize(tcx,ot);ot.clearDelaunayEdges();return t}edge_index=t.edgeIndex(p,op);t.delaunay_edge[edge_index]=true;legalize(tcx,t);t.clearDelaunayEdges();return ot}function nextFlipPoint(ep,eq,ot,op){var o2d=orient2d(eq,op,ep);if(o2d===Orientation.CW){return ot.pointCCW(op)}else if(o2d===Orientation.CCW){return ot.pointCW(op)}else{throw new PointError("poly2tri [Unsupported] nextFlipPoint: opposing point on constrained edge!",[eq,op,ep])}}function flipScanEdgeEvent(tcx,ep,eq,flip_triangle,t,p){var ot=t.neighborAcross(p);assert(ot,"FLIP failed due to missing triangle");var op=ot.oppositePoint(t,p);if(inScanArea(eq,flip_triangle.pointCCW(eq),flip_triangle.pointCW(eq),op)){flipEdgeEvent(tcx,eq,op,ot,op)}else{var newP=nextFlipPoint(ep,eq,ot,op);flipScanEdgeEvent(tcx,ep,eq,flip_triangle,ot,newP)}}var kAlpha=.3;var Edge=function(p1,p2){this.p=p1;this.q=p2;if(p1.y>p2.y){this.q=p1;this.p=p2}else if(p1.y===p2.y){if(p1.x>p2.x){this.q=p1;this.p=p2}else if(p1.x===p2.x){throw new PointError("poly2tri Invalid Edge constructor: repeated points!",[p1])}}if(!this.q._p2t_edge_list){this.q._p2t_edge_list=[]}this.q._p2t_edge_list.push(this)};var Basin=function(){this.left_node=null;this.bottom_node=null;this.right_node=null;this.width=0;this.left_highest=false};Basin.prototype.clear=function(){this.left_node=null;this.bottom_node=null;this.right_node=null;this.width=0;this.left_highest=false};var EdgeEvent=function(){this.constrained_edge=null;this.right=false};var SweepContext=function(contour,options){options=options||{};this.triangles_=[];this.map_=[];this.points_=options.cloneArrays?contour.slice(0):contour;this.edge_list=[];this.pmin_=this.pmax_=null;this.front_=null;this.head_=null;this.tail_=null;this.af_head_=null;this.af_middle_=null;this.af_tail_=null;this.basin=new Basin;this.edge_event=new EdgeEvent;this.initEdges(this.points_)};SweepContext.prototype.addHole=function(polyline){this.initEdges(polyline);var i,len=polyline.length;for(i=0;i<len;i++){this.points_.push(polyline[i])}return this};SweepContext.prototype.AddHole=SweepContext.prototype.addHole;SweepContext.prototype.addHoles=function(holes){var i,len=holes.length;for(i=0;i<len;i++){this.initEdges(holes[i])}this.points_=this.points_.concat.apply(this.points_,holes);return this};SweepContext.prototype.addPoint=function(point){this.points_.push(point);return this};SweepContext.prototype.AddPoint=SweepContext.prototype.addPoint;SweepContext.prototype.addPoints=function(points){this.points_=this.points_.concat(points);return this};SweepContext.prototype.triangulate=function(){triangulate(this);return this};SweepContext.prototype.getBoundingBox=function(){return{min:this.pmin_,max:this.pmax_}};SweepContext.prototype.getTriangles=function(){return this.triangles_};SweepContext.prototype.GetTriangles=SweepContext.prototype.getTriangles;SweepContext.prototype.front=function(){return this.front_};SweepContext.prototype.pointCount=function(){return this.points_.length};SweepContext.prototype.head=function(){return this.head_};SweepContext.prototype.setHead=function(p1){this.head_=p1};SweepContext.prototype.tail=function(){return this.tail_};SweepContext.prototype.setTail=function(p1){this.tail_=p1};SweepContext.prototype.getMap=function(){return this.map_};SweepContext.prototype.initTriangulation=function(){var xmax=this.points_[0].x;var xmin=this.points_[0].x;var ymax=this.points_[0].y;var ymin=this.points_[0].y;var i,len=this.points_.length;for(i=1;i<len;i++){var p=this.points_[i];p.x>xmax&&(xmax=p.x);p.x<xmin&&(xmin=p.x);p.y>ymax&&(ymax=p.y);p.y<ymin&&(ymin=p.y)}this.pmin_=new Point(xmin,ymin);this.pmax_=new Point(xmax,ymax);var dx=kAlpha*(xmax-xmin);var dy=kAlpha*(ymax-ymin);this.head_=new Point(xmax+dx,ymin-dy);this.tail_=new Point(xmin-dx,ymin-dy);this.points_.sort(Point.compare)};SweepContext.prototype.initEdges=function(polyline){var i,len=polyline.length;for(i=0;i<len;++i){this.edge_list.push(new Edge(polyline[i],polyline[(i+1)%len]))}};SweepContext.prototype.getPoint=function(index){return this.points_[index]};SweepContext.prototype.addToMap=function(triangle){this.map_.push(triangle)};SweepContext.prototype.locateNode=function(point){return this.front_.locateNode(point.x)};SweepContext.prototype.createAdvancingFront=function(){var head;var middle;var tail;var triangle=new Triangle(this.points_[0],this.tail_,this.head_);this.map_.push(triangle);head=new Node(triangle.getPoint(1),triangle);middle=new Node(triangle.getPoint(0),triangle);tail=new Node(triangle.getPoint(2));this.front_=new AdvancingFront(head,tail);head.next=middle;middle.next=tail;middle.prev=head;tail.prev=middle};SweepContext.prototype.removeNode=function(node){};SweepContext.prototype.mapTriangleToNodes=function(t){for(var i=0;i<3;++i){if(!t.getNeighbor(i)){var n=this.front_.locatePoint(t.pointCW(t.getPoint(i)));if(n){n.triangle=t}}}};SweepContext.prototype.removeFromMap=function(triangle){var i,map=this.map_,len=map.length;for(i=0;i<len;i++){if(map[i]===triangle){map.splice(i,1);break}}};SweepContext.prototype.meshClean=function(triangle){var triangles=[triangle],t,i;while(t=triangles.pop()){if(!t.isInterior()){t.setInterior(true);this.triangles_.push(t);for(i=0;i<3;i++){if(!t.constrained_edge[i]){triangles.push(t.getNeighbor(i))}}}}};var Triangle=function(a,b,c){this.points_=[a,b,c];this.neighbors_=[null,null,null];this.interior_=false;this.constrained_edge=[false,false,false];this.delaunay_edge=[false,false,false]};Triangle.prototype.getPoint=function(index){return this.points_[index]};Triangle.prototype.GetPoint=Triangle.prototype.getPoint;Triangle.prototype.getPoints=function(){return this.points_};Triangle.prototype.getNeighbor=function(index){return this.neighbors_[index]};Triangle.prototype.containsPoint=function(point){var points=this.points_;return point===points[0]||point===points[1]||point===points[2]};Triangle.prototype.containsEdge=function(edge){return this.containsPoint(edge.p)&&this.containsPoint(edge.q);
  };Triangle.prototype.containsPoints=function(p1,p2){return this.containsPoint(p1)&&this.containsPoint(p2)};Triangle.prototype.isInterior=function(){return this.interior_};Triangle.prototype.setInterior=function(interior){this.interior_=interior;return this};Triangle.prototype.markNeighborPointers=function(p1,p2,t){var points=this.points_;if(p1===points[2]&&p2===points[1]||p1===points[1]&&p2===points[2]){this.neighbors_[0]=t}else if(p1===points[0]&&p2===points[2]||p1===points[2]&&p2===points[0]){this.neighbors_[1]=t}else if(p1===points[0]&&p2===points[1]||p1===points[1]&&p2===points[0]){this.neighbors_[2]=t}else{throw new Error("poly2tri Invalid Triangle.markNeighborPointers() call")}};Triangle.prototype.markNeighbor=function(t){var points=this.points_;if(t.containsPoints(points[1],points[2])){this.neighbors_[0]=t;t.markNeighborPointers(points[1],points[2],this)}else if(t.containsPoints(points[0],points[2])){this.neighbors_[1]=t;t.markNeighborPointers(points[0],points[2],this)}else if(t.containsPoints(points[0],points[1])){this.neighbors_[2]=t;t.markNeighborPointers(points[0],points[1],this)}};Triangle.prototype.clearNeighbors=function(){this.neighbors_[0]=null;this.neighbors_[1]=null;this.neighbors_[2]=null};Triangle.prototype.clearDelaunayEdges=function(){this.delaunay_edge[0]=false;this.delaunay_edge[1]=false;this.delaunay_edge[2]=false};Triangle.prototype.pointCW=function(p){var points=this.points_;if(p===points[0]){return points[2]}else if(p===points[1]){return points[0]}else if(p===points[2]){return points[1]}else{return null}};Triangle.prototype.pointCCW=function(p){var points=this.points_;if(p===points[0]){return points[1]}else if(p===points[1]){return points[2]}else if(p===points[2]){return points[0]}else{return null}};Triangle.prototype.neighborCW=function(p){if(p===this.points_[0]){return this.neighbors_[1]}else if(p===this.points_[1]){return this.neighbors_[2]}else{return this.neighbors_[0]}};Triangle.prototype.neighborCCW=function(p){if(p===this.points_[0]){return this.neighbors_[2]}else if(p===this.points_[1]){return this.neighbors_[0]}else{return this.neighbors_[1]}};Triangle.prototype.getConstrainedEdgeCW=function(p){if(p===this.points_[0]){return this.constrained_edge[1]}else if(p===this.points_[1]){return this.constrained_edge[2]}else{return this.constrained_edge[0]}};Triangle.prototype.getConstrainedEdgeCCW=function(p){if(p===this.points_[0]){return this.constrained_edge[2]}else if(p===this.points_[1]){return this.constrained_edge[0]}else{return this.constrained_edge[1]}};Triangle.prototype.getConstrainedEdgeAcross=function(p){if(p===this.points_[0]){return this.constrained_edge[0]}else if(p===this.points_[1]){return this.constrained_edge[1]}else{return this.constrained_edge[2]}};Triangle.prototype.setConstrainedEdgeCW=function(p,ce){if(p===this.points_[0]){this.constrained_edge[1]=ce}else if(p===this.points_[1]){this.constrained_edge[2]=ce}else{this.constrained_edge[0]=ce}};Triangle.prototype.setConstrainedEdgeCCW=function(p,ce){if(p===this.points_[0]){this.constrained_edge[2]=ce}else if(p===this.points_[1]){this.constrained_edge[0]=ce}else{this.constrained_edge[1]=ce}};Triangle.prototype.getDelaunayEdgeCW=function(p){if(p===this.points_[0]){return this.delaunay_edge[1]}else if(p===this.points_[1]){return this.delaunay_edge[2]}else{return this.delaunay_edge[0]}};Triangle.prototype.getDelaunayEdgeCCW=function(p){if(p===this.points_[0]){return this.delaunay_edge[2]}else if(p===this.points_[1]){return this.delaunay_edge[0]}else{return this.delaunay_edge[1]}};Triangle.prototype.setDelaunayEdgeCW=function(p,e){if(p===this.points_[0]){this.delaunay_edge[1]=e}else if(p===this.points_[1]){this.delaunay_edge[2]=e}else{this.delaunay_edge[0]=e}};Triangle.prototype.setDelaunayEdgeCCW=function(p,e){if(p===this.points_[0]){this.delaunay_edge[2]=e}else if(p===this.points_[1]){this.delaunay_edge[0]=e}else{this.delaunay_edge[1]=e}};Triangle.prototype.neighborAcross=function(p){if(p===this.points_[0]){return this.neighbors_[0]}else if(p===this.points_[1]){return this.neighbors_[1]}else{return this.neighbors_[2]}};Triangle.prototype.oppositePoint=function(t,p){var cw=t.pointCW(p);return this.pointCW(cw)};Triangle.prototype.legalize=function(opoint,npoint){var points=this.points_;if(opoint===points[0]){points[1]=points[0];points[0]=points[2];points[2]=npoint}else if(opoint===points[1]){points[2]=points[1];points[1]=points[0];points[0]=npoint}else if(opoint===points[2]){points[0]=points[2];points[2]=points[1];points[1]=npoint}else{throw new Error("poly2tri Invalid Triangle.legalize() call")}};Triangle.prototype.index=function(p){var points=this.points_;if(p===points[0]){return 0}else if(p===points[1]){return 1}else if(p===points[2]){return 2}else{throw new Error("poly2tri Invalid Triangle.index() call")}};Triangle.prototype.edgeIndex=function(p1,p2){var points=this.points_;if(p1===points[0]){if(p2===points[1]){return 2}else if(p2===points[2]){return 1}}else if(p1===points[1]){if(p2===points[2]){return 0}else if(p2===points[0]){return 2}}else if(p1===points[2]){if(p2===points[0]){return 1}else if(p2===points[1]){return 0}}return-1};Triangle.prototype.markConstrainedEdgeByIndex=function(index){this.constrained_edge[index]=true};Triangle.prototype.markConstrainedEdgeByEdge=function(edge){this.markConstrainedEdgeByPoints(edge.p,edge.q)};Triangle.prototype.markConstrainedEdgeByPoints=function(p,q){var points=this.points_;if(q===points[0]&&p===points[1]||q===points[1]&&p===points[0]){this.constrained_edge[2]=true}else if(q===points[0]&&p===points[2]||q===points[2]&&p===points[0]){this.constrained_edge[1]=true}else if(q===points[1]&&p===points[2]||q===points[2]&&p===points[1]){this.constrained_edge[0]=true}};var TINF_OK=0;var TINF_DATA_ERROR=-3;function Tree(){this.table=new Uint16Array(16);this.trans=new Uint16Array(288)}function Data(source,dest){this.source=source;this.sourceIndex=0;this.tag=0;this.bitcount=0;this.dest=dest;this.destLen=0;this.ltree=new Tree;this.dtree=new Tree}var sltree=new Tree;var sdtree=new Tree;var length_bits=new Uint8Array(30);var length_base=new Uint16Array(30);var dist_bits=new Uint8Array(30);var dist_base=new Uint16Array(30);var clcidx=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);var code_tree=new Tree;var lengths=new Uint8Array(288+32);assert=function(predicate,message){if(!predicate){throw new Error(message)}};function tinf_build_bits_base(bits,base,delta,first){var i,sum;for(i=0;i<delta;++i)bits[i]=0;for(i=0;i<30-delta;++i)bits[i+delta]=i/delta|0;for(sum=first,i=0;i<30;++i){base[i]=sum;sum+=1<<bits[i]}}function tinf_build_fixed_trees(lt,dt){var i;for(i=0;i<7;++i)lt.table[i]=0;lt.table[7]=24;lt.table[8]=152;lt.table[9]=112;for(i=0;i<24;++i)lt.trans[i]=256+i;for(i=0;i<144;++i)lt.trans[24+i]=i;for(i=0;i<8;++i)lt.trans[24+144+i]=280+i;for(i=0;i<112;++i)lt.trans[24+144+8+i]=144+i;for(i=0;i<5;++i)dt.table[i]=0;dt.table[5]=32;for(i=0;i<32;++i)dt.trans[i]=i}var offs=new Uint16Array(16);function tinf_build_tree(t,lengths,off,num){var i,sum;for(i=0;i<16;++i)t.table[i]=0;for(i=0;i<num;++i)t.table[lengths[off+i]]++;t.table[0]=0;for(sum=0,i=0;i<16;++i){offs[i]=sum;sum+=t.table[i]}for(i=0;i<num;++i){if(lengths[off+i])t.trans[offs[lengths[off+i]]++]=i}}function tinf_getbit(d){if(!d.bitcount--){d.tag=d.source[d.sourceIndex++];d.bitcount=7}var bit=d.tag&1;d.tag>>>=1;return bit}function tinf_read_bits(d,num,base){if(!num)return base;while(d.bitcount<24){d.tag|=d.source[d.sourceIndex++]<<d.bitcount;d.bitcount+=8}var val=d.tag&65535>>>16-num;d.tag>>>=num;d.bitcount-=num;return val+base}function tinf_decode_symbol(d,t){while(d.bitcount<24){d.tag|=d.source[d.sourceIndex++]<<d.bitcount;d.bitcount+=8}var sum=0,cur=0,len=0;var tag=d.tag;do{cur=2*cur+(tag&1);tag>>>=1;++len;sum+=t.table[len];cur-=t.table[len]}while(cur>=0);d.tag=tag;d.bitcount-=len;return t.trans[sum+cur]}function tinf_decode_trees(d,lt,dt){var hlit,hdist,hclen;var i,num,length;hlit=tinf_read_bits(d,5,257);hdist=tinf_read_bits(d,5,1);hclen=tinf_read_bits(d,4,4);for(i=0;i<19;++i)lengths[i]=0;for(i=0;i<hclen;++i){var clen=tinf_read_bits(d,3,0);lengths[clcidx[i]]=clen}tinf_build_tree(code_tree,lengths,0,19);for(num=0;num<hlit+hdist;){var sym=tinf_decode_symbol(d,code_tree);switch(sym){case 16:var prev=lengths[num-1];for(length=tinf_read_bits(d,2,3);length;--length){lengths[num++]=prev}break;case 17:for(length=tinf_read_bits(d,3,3);length;--length){lengths[num++]=0}break;case 18:for(length=tinf_read_bits(d,7,11);length;--length){lengths[num++]=0}break;default:lengths[num++]=sym;break}}tinf_build_tree(lt,lengths,0,hlit);tinf_build_tree(dt,lengths,hlit,hdist)}function tinf_inflate_block_data(d,lt,dt){while(1){var sym=tinf_decode_symbol(d,lt);if(sym===256){return TINF_OK}if(sym<256){d.dest[d.destLen++]=sym}else{var length,dist,offs;var i;sym-=257;length=tinf_read_bits(d,length_bits[sym],length_base[sym]);dist=tinf_decode_symbol(d,dt);offs=d.destLen-tinf_read_bits(d,dist_bits[dist],dist_base[dist]);for(i=offs;i<offs+length;++i){d.dest[d.destLen++]=d.dest[i]}}}}function tinf_inflate_uncompressed_block(d){var length,invlength;var i;while(d.bitcount>8){d.sourceIndex--;d.bitcount-=8}length=d.source[d.sourceIndex+1];length=256*length+d.source[d.sourceIndex];invlength=d.source[d.sourceIndex+3];invlength=256*invlength+d.source[d.sourceIndex+2];if(length!==(~invlength&65535))return TINF_DATA_ERROR;d.sourceIndex+=4;for(i=length;i;--i)d.dest[d.destLen++]=d.source[d.sourceIndex++];d.bitcount=0;return TINF_OK}function tinf_uncompress(source,dest){var d=new Data(source,dest);var bfinal,btype,res;do{bfinal=tinf_getbit(d);btype=tinf_read_bits(d,2,0);switch(btype){case 0:res=tinf_inflate_uncompressed_block(d);break;case 1:res=tinf_inflate_block_data(d,sltree,sdtree);break;case 2:tinf_decode_trees(d,d.ltree,d.dtree);res=tinf_inflate_block_data(d,d.ltree,d.dtree);break;default:res=TINF_DATA_ERROR}if(res!==TINF_OK)throw new Error("Data error")}while(!bfinal);if(d.destLen<d.dest.length){if(typeof d.dest.slice==="function")return d.dest.slice(0,d.destLen);else return d.dest.subarray(0,d.destLen)}return d.dest}tinf_build_fixed_trees(sltree,sdtree);tinf_build_bits_base(length_bits,length_base,4,3);tinf_build_bits_base(dist_bits,dist_base,2,1);length_bits[28]=0;length_base[28]=258;function line(ctx,x1,y1,x2,y2){ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);ctx.stroke()}var cffStandardStrings=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","266 ff","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"];var cffStandardEncoding=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls"];var cffExpertEncoding=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"];var standardNames=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function DefaultEncoding(font){this.font=font}DefaultEncoding.prototype.charToGlyphIndex=function(c){var code=c.charCodeAt(0);var glyphs=this.font.glyphs;if(glyphs){for(var i=0;i<glyphs.length;i+=1){var glyph=glyphs.get(i);for(var j=0;j<glyph.unicodes.length;j+=1){if(glyph.unicodes[j]===code){return i}}}}else{return null}};function CmapEncoding(cmap){this.cmap=cmap}CmapEncoding.prototype.charToGlyphIndex=function(c){return this.cmap.glyphIndexMap[c.charCodeAt(0)]||0};function CffEncoding(encoding,charset){this.encoding=encoding;this.charset=charset}CffEncoding.prototype.charToGlyphIndex=function(s){var code=s.charCodeAt(0);var charName=this.encoding[code];return this.charset.indexOf(charName)};function GlyphNames(post){var i;switch(post.version){case 1:this.names=opentype_standardNames.slice();break;case 2:this.names=new Array(post.numberOfGlyphs);for(i=0;i<post.numberOfGlyphs;i++){if(post.glyphNameIndex[i]<opentype_standardNames.length){this.names[i]=opentype_standardNames[post.glyphNameIndex[i]]}else{this.names[i]=post.names[post.glyphNameIndex[i]-opentype_standardNames.length]}}break;case 2.5:this.names=new Array(post.numberOfGlyphs);for(i=0;i<post.numberOfGlyphs;i++){this.names[i]=opentype_standardNames[i+post.glyphNameIndex[i]]}break;case 3:this.names=[];break}}GlyphNames.prototype.nameToGlyphIndex=function(name){return this.names.indexOf(name)};GlyphNames.prototype.glyphIndexToName=function(gid){return this.names[gid]};function addGlyphNames(font){var glyph;var glyphIndexMap=font.tables.cmap.glyphIndexMap;var charCodes=Object.keys(glyphIndexMap);for(var i=0;i<charCodes.length;i+=1){var c=charCodes[i];var glyphIndex=glyphIndexMap[c];glyph=font.glyphs.get(glyphIndex);glyph.addUnicode(parseInt(c))}for(i=0;i<font.glyphs.length;i+=1){glyph=font.glyphs.get(i);if(font.cffEncoding){glyph.name=font.cffEncoding.charset[i]}else{glyph.name=font.glyphNames.glyphIndexToName(i)}}}opentype_cffStandardStrings=cffStandardStrings;opentype_cffStandardEncoding=cffStandardEncoding;opentype_cffExpertEncoding=cffExpertEncoding;opentype_standardNames=standardNames;opentype_DefaultEncoding=DefaultEncoding;opentype_CmapEncoding=CmapEncoding;opentype_CffEncoding=CffEncoding;opentype_GlyphNames=GlyphNames;opentype_addGlyphNames=addGlyphNames;function Font(options){options=options||{};if(!options.empty){util.checkArgument(options.familyName,"When creating a new Font object, familyName is required.");util.checkArgument(options.styleName,"When creating a new Font object, styleName is required.");util.checkArgument(options.unitsPerEm,"When creating a new Font object, unitsPerEm is required.");util.checkArgument(options.ascender,"When creating a new Font object, ascender is required.");util.checkArgument(options.descender,"When creating a new Font object, descender is required.");util.checkArgument(options.descender<0,"Descender should be negative (e.g. -512).");this.names={fontFamily:{en:options.familyName||" "},fontSubfamily:{en:options.styleName||" "},fullName:{en:options.fullName||options.familyName+" "+options.styleName},postScriptName:{en:options.postScriptName||options.familyName+options.styleName},designer:{en:options.designer||" "},designerURL:{en:options.designerURL||" "},manufacturer:{en:options.manufacturer||" "},manufacturerURL:{en:options.manufacturerURL||" "},license:{en:options.license||" "},licenseURL:{en:options.licenseURL||" "},version:{en:options.version||"Version 0.1"},description:{en:options.description||" "},copyright:{en:options.copyright||" "},trademark:{en:options.trademark||" "}};this.unitsPerEm=options.unitsPerEm||1e3;this.ascender=options.ascender;this.descender=options.descender}this.supported=true;this.glyphs=new GlyphSet(this,options.glyphs||[]);this.encoding=new DefaultEncoding(this);this.tables={}}Font.prototype.hasChar=function(c){return this.encoding.charToGlyphIndex(c)!==null};Font.prototype.charToGlyphIndex=function(s){return this.encoding.charToGlyphIndex(s)};Font.prototype.charToGlyph=function(c){var glyphIndex=this.charToGlyphIndex(c);var glyph=this.glyphs.get(glyphIndex);if(!glyph){glyph=this.glyphs.get(0)}return glyph};Font.prototype.stringToGlyphs=function(s){var glyphs=[];for(var i=0;i<s.length;i+=1){var c=s[i];glyphs.push(this.charToGlyph(c))}return glyphs};Font.prototype.nameToGlyphIndex=function(name){return this.glyphNames.nameToGlyphIndex(name)};Font.prototype.nameToGlyph=function(name){var glyphIndex=this.nametoGlyphIndex(name);var glyph=this.glyphs.get(glyphIndex);if(!glyph){glyph=this.glyphs.get(0)}return glyph};Font.prototype.glyphIndexToName=function(gid){if(!this.glyphNames.glyphIndexToName){return""}return this.glyphNames.glyphIndexToName(gid)};Font.prototype.getKerningValue=function(leftGlyph,rightGlyph){leftGlyph=leftGlyph.index||leftGlyph;rightGlyph=rightGlyph.index||rightGlyph;var gposKerning=this.getGposKerningValue;return gposKerning?gposKerning(leftGlyph,rightGlyph):this.kerningPairs[leftGlyph+","+rightGlyph]||0};Font.prototype.forEachGlyph=function(text,x,y,fontSize,options,callback){x=x!==undefined?x:0;y=y!==undefined?y:0;fontSize=fontSize!==undefined?fontSize:72;options=options||{};var kerning=options.kerning===undefined?true:options.kerning;var fontScale=1/this.unitsPerEm*fontSize;var glyphs=this.stringToGlyphs(text);for(var i=0;i<glyphs.length;i+=1){var glyph=glyphs[i];callback(glyph,x,y,fontSize,options);if(glyph.advanceWidth){x+=glyph.advanceWidth*fontScale}if(kerning&&i<glyphs.length-1){var kerningValue=this.getKerningValue(glyph,glyphs[i+1]);x+=kerningValue*fontScale}}};Font.prototype.getPath=function(text,x,y,fontSize,options){var fullPath=new Path;this.forEachGlyph(text,x,y,fontSize,options,function(glyph,gX,gY,gFontSize){var glyphPath=glyph.getPath(gX,gY,gFontSize);fullPath.extend(glyphPath)});return fullPath};Font.prototype.getPaths=function(text,x,y,fontSize,options){var glyphPaths=[];this.forEachGlyph(text,x,y,fontSize,options,function(glyph,gX,gY,gFontSize){var glyphPath=glyph.getPath(gX,gY,gFontSize);glyphPaths.push(glyphPath)});return glyphPaths};Font.prototype.draw=function(ctx,text,x,y,fontSize,options){this.getPath(text,x,y,fontSize,options).draw(ctx)};Font.prototype.drawPoints=function(ctx,text,x,y,fontSize,options){this.forEachGlyph(text,x,y,fontSize,options,function(glyph,gX,gY,gFontSize){glyph.drawPoints(ctx,gX,gY,gFontSize)})};Font.prototype.drawMetrics=function(ctx,text,x,y,fontSize,options){this.forEachGlyph(text,x,y,fontSize,options,function(glyph,gX,gY,gFontSize){glyph.drawMetrics(ctx,gX,gY,gFontSize)})};Font.prototype.getEnglishName=function(name){var translations=this.names[name];if(translations){return translations.en}};Font.prototype.validate=function(){var warnings=[];var _this=this;function assert(predicate,message){if(!predicate){warnings.push(message)}}function assertNamePresent(name){var englishName=_this.getEnglishName(name);assert(englishName&&englishName.trim().length>0,"No English "+name+" specified.")}assertNamePresent("fontFamily");assertNamePresent("weightName");assertNamePresent("manufacturer");assertNamePresent("copyright");assertNamePresent("version");assert(this.unitsPerEm>0,"No unitsPerEm specified.")};Font.prototype.toTables=function(){return sfnt.fontToTable(this)};Font.prototype.toBuffer=function(){console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.");return this.toArrayBuffer()};Font.prototype.toArrayBuffer=function(){var sfntTable=this.toTables();var bytes=sfntTable.encode();var buffer=new ArrayBuffer(bytes.length);var intArray=new Uint8Array(buffer);for(var i=0;i<bytes.length;i++){intArray[i]=bytes[i]}return buffer};Font.prototype.download=function(){var familyName=this.getEnglishName("fontFamily");var styleName=this.getEnglishName("fontSubfamily");var fileName=familyName.replace(/\s/g,"")+"-"+styleName+".otf";var arrayBuffer=this.toArrayBuffer();if(util.isBrowser()){window.requestFileSystem=window.requestFileSystem||window.webkitRequestFileSystem;window.requestFileSystem(window.TEMPORARY,arrayBuffer.byteLength,function(fs){fs.root.getFile(fileName,{create:true},function(fileEntry){fileEntry.createWriter(function(writer){var dataView=new DataView(arrayBuffer);var blob=new Blob([dataView],{type:"font/opentype"});writer.write(blob);writer.addEventListener("writeend",function(){location.href=fileEntry.toURL()},false)})})},function(err){throw err})}else{var fs=require("fs");var buffer=util.arrayBufferToNodeBuffer(arrayBuffer);fs.writeFileSync(fileName,buffer)}};function getPathDefinition(glyph,path){var _path=path||{commands:[]};return{configurable:true,get:function(){if(typeof _path==="function"){_path=_path()}return _path},set:function(p){_path=p}}}function Glyph(options){this.bindConstructorValues(options)}Glyph.prototype.bindConstructorValues=function(options){this.index=options.index||0;this.name=options.name||null;this.unicode=options.unicode||undefined;this.unicodes=options.unicodes||options.unicode!==undefined?[options.unicode]:[];if(options.xMin){this.xMin=options.xMin}if(options.yMin){this.yMin=options.yMin}if(options.xMax){this.xMax=options.xMax}if(options.yMax){this.yMax=options.yMax}if(options.advanceWidth){this.advanceWidth=options.advanceWidth}Object.defineProperty(this,"path",getPathDefinition(this,options.path))};Glyph.prototype.addUnicode=function(unicode){if(this.unicodes.length===0){this.unicode=unicode}this.unicodes.push(unicode)};Glyph.prototype.getPath=function(x,y,fontSize,options){x=x!==undefined?x:0;y=y!==undefined?y:0;options=options!==undefined?options:{xScale:1,yScale:1};fontSize=fontSize!==undefined?fontSize:72;var scale=1/this.path.unitsPerEm*fontSize;var xScale=options.xScale*scale;var yScale=options.yScale*scale;var p=new Path;var commands=this.path.commands;for(var i=0;i<commands.length;i+=1){var cmd=commands[i];if(cmd.type==="M"){p.moveTo(x+cmd.x*xScale,y+-cmd.y*yScale)}else if(cmd.type==="L"){p.lineTo(x+cmd.x*xScale,y+-cmd.y*yScale)}else if(cmd.type==="Q"){p.quadraticCurveTo(x+cmd.x1*xScale,y+-cmd.y1*yScale,x+cmd.x*xScale,y+-cmd.y*yScale)}else if(cmd.type==="C"){p.curveTo(x+cmd.x1*xScale,y+-cmd.y1*yScale,x+cmd.x2*xScale,y+-cmd.y2*yScale,x+cmd.x*xScale,y+-cmd.y*yScale)}else if(cmd.type==="Z"){p.closePath()}}return p};Glyph.prototype.getContours=function(){if(this.points===undefined){return[]}var contours=[];var currentContour=[];for(var i=0;i<this.points.length;i+=1){var pt=this.points[i];currentContour.push(pt);if(pt.lastPointOfContour){contours.push(currentContour);currentContour=[]}}assert(currentContour.length===0,"There are still points left in the current contour.");return contours};Glyph.prototype.getMetrics=function(){var commands=this.path.commands;var xCoords=[];var yCoords=[];for(var i=0;i<commands.length;i+=1){var cmd=commands[i];if(cmd.type!=="Z"){xCoords.push(cmd.x);yCoords.push(cmd.y)}if(cmd.type==="Q"||cmd.type==="C"){xCoords.push(cmd.x1);yCoords.push(cmd.y1)}if(cmd.type==="C"){xCoords.push(cmd.x2);yCoords.push(cmd.y2)}}var metrics={xMin:Math.min.apply(null,xCoords),yMin:Math.min.apply(null,yCoords),xMax:Math.max.apply(null,xCoords),
  yMax:Math.max.apply(null,yCoords),leftSideBearing:this.leftSideBearing};if(!isFinite(metrics.xMin)){metrics.xMin=0}if(!isFinite(metrics.xMax)){metrics.xMax=this.advanceWidth}if(!isFinite(metrics.yMin)){metrics.yMin=0}if(!isFinite(metrics.yMax)){metrics.yMax=0}metrics.rightSideBearing=this.advanceWidth-metrics.leftSideBearing-(metrics.xMax-metrics.xMin);return metrics};Glyph.prototype.draw=function(ctx,x,y,fontSize,options){this.getPath(x,y,fontSize,options).draw(ctx)};Glyph.prototype.drawPoints=function(ctx,x,y,fontSize){function drawCircles(l,x,y,scale){var PI_SQ=Math.PI*2;ctx.beginPath();for(var j=0;j<l.length;j+=1){ctx.moveTo(x+l[j].x*scale,y+l[j].y*scale);ctx.arc(x+l[j].x*scale,y+l[j].y*scale,2,0,PI_SQ,false)}ctx.closePath();ctx.fill()}x=x!==undefined?x:0;y=y!==undefined?y:0;fontSize=fontSize!==undefined?fontSize:24;var scale=1/this.path.unitsPerEm*fontSize;var blueCircles=[];var redCircles=[];var path=this.path;for(var i=0;i<path.commands.length;i+=1){var cmd=path.commands[i];if(cmd.x!==undefined){blueCircles.push({x:cmd.x,y:-cmd.y})}if(cmd.x1!==undefined){redCircles.push({x:cmd.x1,y:-cmd.y1})}if(cmd.x2!==undefined){redCircles.push({x:cmd.x2,y:-cmd.y2})}}ctx.fillStyle="blue";drawCircles(blueCircles,x,y,scale);ctx.fillStyle="red";drawCircles(redCircles,x,y,scale)};Glyph.prototype.drawMetrics=function(ctx,x,y,fontSize){var scale;x=x!==undefined?x:0;y=y!==undefined?y:0;fontSize=fontSize!==undefined?fontSize:24;scale=1/this.path.unitsPerEm*fontSize;ctx.lineWidth=1;ctx.strokeStyle="black";draw.line(ctx,x,-1e4,x,1e4);draw.line(ctx,-1e4,y,1e4,y);var xMin=this.xMin||0;var yMin=this.yMin||0;var xMax=this.xMax||0;var yMax=this.yMax||0;var advanceWidth=this.advanceWidth||0;ctx.strokeStyle="blue";draw.line(ctx,x+xMin*scale,-1e4,x+xMin*scale,1e4);draw.line(ctx,x+xMax*scale,-1e4,x+xMax*scale,1e4);draw.line(ctx,-1e4,y+-yMin*scale,1e4,y+-yMin*scale);draw.line(ctx,-1e4,y+-yMax*scale,1e4,y+-yMax*scale);ctx.strokeStyle="green";draw.line(ctx,x+advanceWidth*scale,-1e4,x+advanceWidth*scale,1e4)};function GlyphSet(font,glyphs){this.font=font;this.glyphs={};if(Array.isArray(glyphs)){for(var i=0;i<glyphs.length;i++){this.glyphs[i]=glyphs[i]}}this.length=glyphs&&glyphs.length||0}GlyphSet.prototype.get=function(index){if(typeof this.glyphs[index]==="function"){this.glyphs[index]=this.glyphs[index]()}return this.glyphs[index]};GlyphSet.prototype.push=function(index,loader){this.glyphs[index]=loader;this.length++};function glyphLoader(font,index){return new Glyph({index:index,font:font})}function ttfGlyphLoader(font,index,parseGlyph,data,position,buildPath){return function(){var glyph=new Glyph({index:index,font:font});glyph.path=function(){parseGlyph(glyph,data,position);var path=buildPath(font.glyphs,glyph);path.unitsPerEm=font.unitsPerEm;return path};return glyph}}function cffGlyphLoader(font,index,parseCFFCharstring,charstring){return function(){var glyph=new Glyph({index:index,font:font});glyph.path=function(){var path=parseCFFCharstring(font,glyph,charstring);path.unitsPerEm=font.unitsPerEm;return path};return glyph}}function loadFromFile(path,callback){var fs=require("fs");fs.readFile(path,function(err,buffer){if(err){return callback(err.message)}callback(null,util.nodeBufferToArrayBuffer(buffer))})}function loadFromUrl(url,callback){var request=new XMLHttpRequest;request.open("get",url,true);request.responseType="arraybuffer";request.onload=function(){if(request.status!==200){return callback("Font could not be loaded: "+request.statusText)}return callback(null,request.response)};request.send()}function parseOpenTypeTableEntries(data,numTables){var tableEntries=[];var p=12;for(var i=0;i<numTables;i+=1){var tag=getTag(data,p);var checksum=getULong(data,p+4);var offset=getULong(data,p+8);var length=getULong(data,p+12);tableEntries.push({tag:tag,checksum:checksum,offset:offset,length:length,compression:false});p+=16}return tableEntries}function parseWOFFTableEntries(data,numTables){var tableEntries=[];var p=44;for(var i=0;i<numTables;i+=1){var tag=getTag(data,p);var offset=getULong(data,p+4);var compLength=getULong(data,p+8);var origLength=getULong(data,p+12);var compression;if(compLength<origLength){compression="WOFF"}else{compression=false}tableEntries.push({tag:tag,offset:offset,compression:compression,compressedLength:compLength,originalLength:origLength});p+=20}return tableEntries}function uncompressTable(data,tableEntry){if(tableEntry.compression==="WOFF"){var inBuffer=new Uint8Array(data.buffer,tableEntry.offset+2,tableEntry.compressedLength-2);var outBuffer=new Uint8Array(tableEntry.originalLength);inflate(inBuffer,outBuffer);if(outBuffer.byteLength!==tableEntry.originalLength){throw new Error("Decompression error: "+tableEntry.tag+" decompressed length doesn't match recorded length")}var view=new DataView(outBuffer.buffer,0);return{data:view,offset:0}}else{return{data:data,offset:tableEntry.offset}}}function parseBuffer(buffer){var indexToLocFormat;var ltagTable;var font=new Font({empty:true});var data=new DataView(buffer,0);var numTables;var tableEntries=[];var signature=getTag(data,0);if(signature===String.fromCharCode(0,1,0,0)){font.outlinesFormat="truetype";numTables=getUShort(data,4);tableEntries=parseOpenTypeTableEntries(data,numTables)}else if(signature==="OTTO"){font.outlinesFormat="cff";numTables=getUShort(data,4);tableEntries=parseOpenTypeTableEntries(data,numTables)}else if(signature==="wOFF"){var flavor=getTag(data,4);if(flavor===String.fromCharCode(0,1,0,0)){font.outlinesFormat="truetype"}else if(flavor==="OTTO"){font.outlinesFormat="cff"}else{throw new Error("Unsupported OpenType flavor "+signature)}numTables=getUShort(data,12);tableEntries=parseWOFFTableEntries(data,numTables)}else{throw new Error("Unsupported OpenType signature "+signature)}var cffTableEntry;var fvarTableEntry;var glyfTableEntry;var gposTableEntry;var hmtxTableEntry;var kernTableEntry;var locaTableEntry;var nameTableEntry;for(var i=0;i<numTables;i+=1){var tableEntry=tableEntries[i];var table;switch(tableEntry.tag){case"cmap":table=uncompressTable(data,tableEntry);font.tables.cmap=parseCmapTable(table.data,table.offset);font.encoding=new CmapEncoding(font.tables.cmap);break;case"fvar":fvarTableEntry=tableEntry;break;case"head":table=uncompressTable(data,tableEntry);font.tables.head=parseHeadTable(table.data,table.offset);font.unitsPerEm=font.tables.head.unitsPerEm;indexToLocFormat=font.tables.head.indexToLocFormat;break;case"hhea":table=uncompressTable(data,tableEntry);font.tables.hhea=parseHheaTable(table.data,table.offset);font.ascender=font.tables.hhea.ascender;font.descender=font.tables.hhea.descender;font.numberOfHMetrics=font.tables.hhea.numberOfHMetrics;break;case"hmtx":hmtxTableEntry=tableEntry;break;case"ltag":table=uncompressTable(data,tableEntry);ltagTable=ltag.parse(table.data,table.offset);break;case"maxp":table=uncompressTable(data,tableEntry);font.tables.maxp=parseMaxpTable(table.data,table.offset);font.numGlyphs=font.tables.maxp.numGlyphs;break;case"name":nameTableEntry=tableEntry;break;case"OS/2":table=uncompressTable(data,tableEntry);font.tables.os2=parseOS2Table(table.data,table.offset);break;case"post":table=uncompressTable(data,tableEntry);font.tables.post=parsePostTable(table.data,table.offset);font.glyphNames=new GlyphNames(font.tables.post);break;case"glyf":glyfTableEntry=tableEntry;break;case"loca":locaTableEntry=tableEntry;break;case"CFF ":cffTableEntry=tableEntry;break;case"kern":kernTableEntry=tableEntry;break;case"GPOS":gposTableEntry=tableEntry;break}}var nameTable=uncompressTable(data,nameTableEntry);font.tables.name=parseNameTable(nameTable.data,nameTable.offset,ltagTable);font.names=font.tables.name;if(glyfTableEntry&&locaTableEntry){var shortVersion=indexToLocFormat===0;var locaTable=uncompressTable(data,locaTableEntry);var locaOffsets=parseLocaTable(locaTable.data,locaTable.offset,font.numGlyphs,shortVersion);var glyfTable=uncompressTable(data,glyfTableEntry);font.glyphs=parseGlyfTable(glyfTable.data,glyfTable.offset,locaOffsets,font)}else if(cffTableEntry){var cffTable=uncompressTable(data,cffTableEntry);parseCFFTable(cffTable.data,cffTable.offset,font)}else{throw new Error("Font doesn't contain TrueType or CFF outlines.")}var hmtxTable=uncompressTable(data,hmtxTableEntry);parseHmtxTable(hmtxTable.data,hmtxTable.offset,font.numberOfHMetrics,font.numGlyphs,font.glyphs);addGlyphNames(font);if(kernTableEntry){var kernTable=uncompressTable(data,kernTableEntry);font.kerningPairs=kern.parse(kernTable.data,kernTable.offset)}else{font.kerningPairs={}}if(gposTableEntry){var gposTable=uncompressTable(data,gposTableEntry);parseGposTable(gposTable.data,gposTable.offset,font)}if(fvarTableEntry){var fvarTable=uncompressTable(data,fvarTableEntry);font.tables.fvar=fvar.parse(fvarTable.data,fvarTable.offset,font.names)}return font}function opentype_load(url,callback){var isNode=typeof window==="undefined";var loadFn=isNode?loadFromFile:loadFromUrl;loadFn(url,function(err,arrayBuffer){if(err){return callback(err)}var font;try{font=parseBuffer(arrayBuffer)}catch(e){return callback(e,null)}return callback(null,font)})}function loadSync(url){var fs=require("fs");var buffer=fs.readFileSync(url);return parseBuffer(util.nodeBufferToArrayBuffer(buffer))}getByte=function getByte(dataView,offset){return dataView.getUint8(offset)};getCard8=getByte;getUShort=function(dataView,offset){return dataView.getUint16(offset,false)};getCard16=getUShort;getShort=function(dataView,offset){return dataView.getInt16(offset,false)};getULong=function(dataView,offset){return dataView.getUint32(offset,false)};getFixed=function(dataView,offset){var decimal=dataView.getInt16(offset,false);var fraction=dataView.getUint16(offset+2,false);return decimal+fraction/65535};getTag=function(dataView,offset){var tag="";for(var i=offset;i<offset+4;i+=1){tag+=String.fromCharCode(dataView.getInt8(i))}return tag};getOffset=function(dataView,offset,offSize){var v=0;for(var i=0;i<offSize;i+=1){v<<=8;v+=dataView.getUint8(offset+i)}return v};getBytes=function(dataView,startOffset,endOffset){var bytes=[];for(var i=startOffset;i<endOffset;i+=1){bytes.push(dataView.getUint8(i))}return bytes};bytesToString=function(bytes){var s="";for(var i=0;i<bytes.length;i+=1){s+=String.fromCharCode(bytes[i])}return s};var typeOffsets={byte:1,uShort:2,short:2,uLong:4,fixed:4,longDateTime:8,tag:4};function Parser(data,offset){this.data=data;this.offset=offset;this.relativeOffset=0}Parser.prototype.parseByte=function(){var v=this.data.getUint8(this.offset+this.relativeOffset);this.relativeOffset+=1;return v};Parser.prototype.parseChar=function(){var v=this.data.getInt8(this.offset+this.relativeOffset);this.relativeOffset+=1;return v};Parser.prototype.parseCard8=Parser.prototype.parseByte;Parser.prototype.parseUShort=function(){var v=this.data.getUint16(this.offset+this.relativeOffset);this.relativeOffset+=2;return v};Parser.prototype.parseCard16=Parser.prototype.parseUShort;Parser.prototype.parseSID=Parser.prototype.parseUShort;Parser.prototype.parseOffset16=Parser.prototype.parseUShort;Parser.prototype.parseShort=function(){var v=this.data.getInt16(this.offset+this.relativeOffset);this.relativeOffset+=2;return v};Parser.prototype.parseF2Dot14=function(){var v=this.data.getInt16(this.offset+this.relativeOffset)/16384;this.relativeOffset+=2;return v};Parser.prototype.parseULong=function(){var v=getULong(this.data,this.offset+this.relativeOffset);this.relativeOffset+=4;return v};Parser.prototype.parseFixed=function(){var v=getFixed(this.data,this.offset+this.relativeOffset);this.relativeOffset+=4;return v};Parser.prototype.parseOffset16List=Parser.prototype.parseUShortList=function(count){var offsets=new Array(count);var dataView=this.data;var offset=this.offset+this.relativeOffset;for(var i=0;i<count;i++){offsets[i]=getUShort(dataView,offset);offset+=2}this.relativeOffset+=count*2;return offsets};Parser.prototype.parseString=function(length){var dataView=this.data;var offset=this.offset+this.relativeOffset;var string="";this.relativeOffset+=length;for(var i=0;i<length;i++){string+=String.fromCharCode(dataView.getUint8(offset+i))}return string};Parser.prototype.parseTag=function(){return this.parseString(4)};Parser.prototype.parseLongDateTime=function(){var v=getULong(this.data,this.offset+this.relativeOffset+4);this.relativeOffset+=8;return v};Parser.prototype.parseFixed=function(){var v=getULong(this.data,this.offset+this.relativeOffset);this.relativeOffset+=4;return v/65536};Parser.prototype.parseVersion=function(){var major=getUShort(this.data,this.offset+this.relativeOffset);var minor=getUShort(this.data,this.offset+this.relativeOffset+2);this.relativeOffset+=4;return major+minor/4096/10};Parser.prototype.skip=function(type,amount){if(amount===undefined){amount=1}this.relativeOffset+=typeOffsets[type]*amount};"use strict";function Path(){this.commands=[];this.fill="black";this.stroke=null;this.strokeWidth=1}Path.prototype.moveTo=function(x,y){this.commands.push({type:"M",x:x,y:y})};Path.prototype.lineTo=function(x,y){this.commands.push({type:"L",x:x,y:y})};Path.prototype.curveTo=Path.prototype.bezierCurveTo=function(x1,y1,x2,y2,x,y){this.commands.push({type:"C",x1:x1,y1:y1,x2:x2,y2:y2,x:x,y:y})};Path.prototype.quadTo=Path.prototype.quadraticCurveTo=function(x1,y1,x,y){this.commands.push({type:"Q",x1:x1,y1:y1,x:x,y:y})};Path.prototype.close=Path.prototype.closePath=function(){this.commands.push({type:"Z"})};Path.prototype.extend=function(pathOrCommands){if(pathOrCommands.commands){pathOrCommands=pathOrCommands.commands}Array.prototype.push.apply(this.commands,pathOrCommands)};Path.prototype.draw=function(ctx){ctx.beginPath();for(var i=0;i<this.commands.length;i+=1){var cmd=this.commands[i];if(cmd.type==="M"){ctx.moveTo(cmd.x,cmd.y)}else if(cmd.type==="L"){ctx.lineTo(cmd.x,cmd.y)}else if(cmd.type==="C"){ctx.bezierCurveTo(cmd.x1,cmd.y1,cmd.x2,cmd.y2,cmd.x,cmd.y)}else if(cmd.type==="Q"){ctx.quadraticCurveTo(cmd.x1,cmd.y1,cmd.x,cmd.y)}else if(cmd.type==="Z"){ctx.closePath()}}if(this.fill){ctx.fillStyle=this.fill;ctx.fill()}if(this.stroke){ctx.strokeStyle=this.stroke;ctx.lineWidth=this.strokeWidth;ctx.stroke()}};Path.prototype.toPathData=function(decimalPlaces){decimalPlaces=decimalPlaces!==undefined?decimalPlaces:2;function floatToString(v){if(Math.round(v)===v){return""+Math.round(v)}else{return v.toFixed(decimalPlaces)}}function packValues(){var s="";for(var i=0;i<arguments.length;i+=1){var v=arguments[i];if(v>=0&&i>0){s+=" "}s+=floatToString(v)}return s}var d="";for(var i=0;i<this.commands.length;i+=1){var cmd=this.commands[i];if(cmd.type==="M"){d+="M"+packValues(cmd.x,cmd.y)}else if(cmd.type==="L"){d+="L"+packValues(cmd.x,cmd.y)}else if(cmd.type==="C"){d+="C"+packValues(cmd.x1,cmd.y1,cmd.x2,cmd.y2,cmd.x,cmd.y)}else if(cmd.type==="Q"){d+="Q"+packValues(cmd.x1,cmd.y1,cmd.x,cmd.y)}else if(cmd.type==="Z"){d+="Z"}}return d};Path.prototype.toSVG=function(decimalPlaces){var svg='<path d="';svg+=this.toPathData(decimalPlaces);svg+='"';if(this.fill&this.fill!=="black"){if(this.fill===null){svg+=' fill="none"'}else{svg+=' fill="'+this.fill+'"'}}if(this.stroke){svg+=' stroke="'+this.stroke+'" stroke-width="'+this.strokeWidth+'"'}svg+="/>";return svg};function Table(tableName,fields,options){var i;for(i=0;i<fields.length;i+=1){var field=fields[i];this[field.name]=field.value}this.tableName=tableName;this.fields=fields;if(options){var optionKeys=Object.keys(options);for(i=0;i<optionKeys.length;i+=1){var k=optionKeys[i];var v=options[k];if(this[k]!==undefined){this[k]=v}}}}Table.prototype.encode=function(){return encode.TABLE(this)};Table.prototype.sizeOf=function(){return sizeOf.TABLE(this)};function equals(a,b){if(a===b){return true}else if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length){return false}for(var i=0;i<a.length;i+=1){if(!equals(a[i],b[i])){return false}}return true}else{return false}}function parseCFFIndex(data,start,conversionFn){var offsets=[];var objects=[];var count=getCard16(data,start);var i;var objectOffset;var endOffset;if(count!==0){var offsetSize=getByte(data,start+2);objectOffset=start+(count+1)*offsetSize+2;var pos=start+3;for(i=0;i<count+1;i+=1){offsets.push(getOffset(data,pos,offsetSize));pos+=offsetSize}endOffset=objectOffset+offsets[count]}else{endOffset=start+2}for(i=0;i<offsets.length-1;i+=1){var value=getBytes(data,objectOffset+offsets[i],objectOffset+offsets[i+1]);if(conversionFn){value=conversionFn(value)}objects.push(value)}return{objects:objects,startOffset:start,endOffset:endOffset}}function parseFloatOperand(parser){var s="";var eof=15;var lookup=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"];while(true){var b=parser.parseByte();var n1=b>>4;var n2=b&15;if(n1===eof){break}s+=lookup[n1];if(n2===eof){break}s+=lookup[n2]}return parseFloat(s)}function parseOperand(parser,b0){var b1;var b2;var b3;var b4;if(b0===28){b1=parser.parseByte();b2=parser.parseByte();return b1<<8|b2}if(b0===29){b1=parser.parseByte();b2=parser.parseByte();b3=parser.parseByte();b4=parser.parseByte();return b1<<24|b2<<16|b3<<8|b4}if(b0===30){return parseFloatOperand(parser)}if(b0>=32&&b0<=246){return b0-139}if(b0>=247&&b0<=250){b1=parser.parseByte();return(b0-247)*256+b1+108}if(b0>=251&&b0<=254){b1=parser.parseByte();return-(b0-251)*256-b1-108}throw new Error("Invalid b0 "+b0)}function entriesToObject(entries){var o={};for(var i=0;i<entries.length;i+=1){var key=entries[i][0];var values=entries[i][1];var value;if(values.length===1){value=values[0]}else{value=values}if(o.hasOwnProperty(key)){throw new Error("Object "+o+" already has key "+key)}o[key]=value}return o}function parseCFFDict(data,start,size){start=start!==undefined?start:0;var parser=new Parser(data,start);var entries=[];var operands=[];size=size!==undefined?size:data.length;while(parser.relativeOffset<size){var op=parser.parseByte();if(op<=21){if(op===12){op=1200+parser.parseByte()}entries.push([op,operands]);operands=[]}else{operands.push(parseOperand(parser,op))}}return entriesToObject(entries)}function getCFFString(strings,index){if(index<=390){index=cffStandardStrings[index]}else{index=strings[index-391]}return index}function interpretDict(dict,meta,strings){var newDict={};for(var i=0;i<meta.length;i+=1){var m=meta[i];var value=dict[m.op];if(value===undefined){value=m.value!==undefined?m.value:null}if(m.type==="SID"){value=getCFFString(strings,value)}newDict[m.name]=value}return newDict}function parseCFFHeader(data,start){var header={};header.formatMajor=getCard8(data,start);header.formatMinor=getCard8(data,start+1);header.size=getCard8(data,start+2);header.offsetSize=getCard8(data,start+3);header.startOffset=start;header.endOffset=start+4;return header}var TOP_DICT_META=[{name:"version",op:0,type:"SID"},{name:"notice",op:1,type:"SID"},{name:"copyright",op:1200,type:"SID"},{name:"fullName",op:2,type:"SID"},{name:"familyName",op:3,type:"SID"},{name:"weight",op:4,type:"SID"},{name:"isFixedPitch",op:1201,type:"number",value:0},{name:"italicAngle",op:1202,type:"number",value:0},{name:"underlinePosition",op:1203,type:"number",value:-100},{name:"underlineThickness",op:1204,type:"number",value:50},{name:"paintType",op:1205,type:"number",value:0},{name:"charstringType",op:1206,type:"number",value:2},{name:"fontMatrix",op:1207,type:["real","real","real","real","real","real"],value:[.001,0,0,.001,0,0]},{name:"uniqueId",op:13,type:"number"},{name:"fontBBox",op:5,type:["number","number","number","number"],value:[0,0,0,0]},{name:"strokeWidth",op:1208,type:"number",value:0},{name:"xuid",op:14,type:[],value:null},{name:"charset",op:15,type:"offset",value:0},{name:"encoding",op:16,type:"offset",value:0},{name:"charStrings",op:17,type:"offset",value:0},{name:"private",op:18,type:["number","offset"],value:[0,0]}];var PRIVATE_DICT_META=[{name:"subrs",op:19,type:"offset",value:0},{name:"defaultWidthX",op:20,type:"number",value:0},{name:"nominalWidthX",op:21,type:"number",value:0}];function parseCFFTopDict(data,strings){var dict=parseCFFDict(data,0,data.byteLength);return interpretDict(dict,TOP_DICT_META,strings)}function parseCFFPrivateDict(data,start,size,strings){var dict=parseCFFDict(data,start,size);return interpretDict(dict,PRIVATE_DICT_META,strings)}function parseCFFCharset(data,start,nGlyphs,strings){var i;var sid;var count;var parser=new Parser(data,start);nGlyphs-=1;var charset=[".notdef"];var format=parser.parseCard8();if(format===0){for(i=0;i<nGlyphs;i+=1){sid=parser.parseSID();charset.push(getCFFString(strings,sid))}}else if(format===1){while(charset.length<=nGlyphs){sid=parser.parseSID();count=parser.parseCard8();for(i=0;i<=count;i+=1){charset.push(getCFFString(strings,sid));sid+=1}}}else if(format===2){while(charset.length<=nGlyphs){sid=parser.parseSID();count=parser.parseCard16();for(i=0;i<=count;i+=1){charset.push(getCFFString(strings,sid));sid+=1}}}else{throw new Error("Unknown charset format "+format)}return charset}function parseCFFEncoding(data,start,charset){var i;var code;var enc={};var parser=new Parser(data,start);var format=parser.parseCard8();if(format===0){var nCodes=parser.parseCard8();for(i=0;i<nCodes;i+=1){code=parser.parseCard8();enc[code]=i}}else if(format===1){var nRanges=parser.parseCard8();code=1;for(i=0;i<nRanges;i+=1){var first=parser.parseCard8();var nLeft=parser.parseCard8();for(var j=first;j<=first+nLeft;j+=1){enc[j]=code;code+=1}}}else{throw new Error("Unknown encoding format "+format)}return new CffEncoding(enc,charset)}function parseCFFCharstring(font,glyph,code){var c1x;var c1y;var c2x;var c2y;var p=new Path;var stack=[];var nStems=0;var haveWidth=false;var width=font.defaultWidthX;var open=false;var x=0;var y=0;function newContour(x,y){if(open){p.closePath()}p.moveTo(x,y);open=true}function parseStems(){var hasWidthArg;hasWidthArg=stack.length%2!==0;if(hasWidthArg&&!haveWidth){width=stack.shift()+font.nominalWidthX}nStems+=stack.length>>1;stack.length=0;haveWidth=true}function parse(code){var b1;var b2;var b3;var b4;var codeIndex;var subrCode;var jpx;var jpy;var c3x;var c3y;var c4x;var c4y;var i=0;while(i<code.length){var v=code[i];i+=1;switch(v){case 1:parseStems();break;case 3:parseStems();break;case 4:if(stack.length>1&&!haveWidth){width=stack.shift()+font.nominalWidthX;haveWidth=true}y+=stack.pop();newContour(x,y);break;case 5:while(stack.length>0){x+=stack.shift();y+=stack.shift();p.lineTo(x,y)}break;case 6:while(stack.length>0){x+=stack.shift();p.lineTo(x,y);if(stack.length===0){break}y+=stack.shift();p.lineTo(x,y)}break;case 7:while(stack.length>0){y+=stack.shift();p.lineTo(x,y);if(stack.length===0){break}x+=stack.shift();p.lineTo(x,y)}break;case 8:while(stack.length>0){c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;case 10:codeIndex=stack.pop()+font.subrsBias;subrCode=font.subrs[codeIndex];if(subrCode){parse(subrCode)}break;case 11:return;case 12:v=code[i];i+=1;switch(v){case 35:c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();jpx=c2x+stack.shift();jpy=c2y+stack.shift();c3x=jpx+stack.shift();c3y=jpy+stack.shift();c4x=c3x+stack.shift();c4y=c3y+stack.shift();x=c4x+stack.shift();y=c4y+stack.shift();stack.shift();p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;case 34:c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();jpx=c2x+stack.shift();jpy=c2y;c3x=jpx+stack.shift();c3y=c2y;c4x=c3x+stack.shift();c4y=y;x=c4x+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;case 36:c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();jpx=c2x+stack.shift();jpy=c2y;c3x=jpx+stack.shift();c3y=c2y;c4x=c3x+stack.shift();c4y=c3y+stack.shift();x=c4x+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;case 37:c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();jpx=c2x+stack.shift();jpy=c2y+stack.shift();c3x=jpx+stack.shift();c3y=jpy+stack.shift();c4x=c3x+stack.shift();c4y=c3y+stack.shift();if(Math.abs(c4x-x)>Math.abs(c4y-y)){x=c4x+stack.shift()}else{y=c4y+stack.shift()}p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;default:console.log("Glyph "+glyph.index+": unknown operator "+1200+v);stack.length=0}break;case 14:if(stack.length>0&&!haveWidth){width=stack.shift()+font.nominalWidthX;haveWidth=true}if(open){p.closePath();open=false}break;case 18:parseStems();break;case 19:case 20:parseStems();i+=nStems+7>>3;break;case 21:if(stack.length>2&&!haveWidth){width=stack.shift()+font.nominalWidthX;haveWidth=true}y+=stack.pop();x+=stack.pop();newContour(x,y);break;case 22:if(stack.length>1&&!haveWidth){width=stack.shift()+font.nominalWidthX;haveWidth=true}x+=stack.pop();newContour(x,y);break;case 23:parseStems();break;case 24:while(stack.length>2){c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y)}x+=stack.shift();y+=stack.shift();p.lineTo(x,y);break;case 25:while(stack.length>6){x+=stack.shift();y+=stack.shift();p.lineTo(x,y)}c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y);break;case 26:if(stack.length%2){x+=stack.shift()}while(stack.length>0){c1x=x;c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x;y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;case 27:if(stack.length%2){y+=stack.shift()}while(stack.length>0){c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y;p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;case 28:b1=code[i];b2=code[i+1];stack.push((b1<<24|b2<<16)>>16);i+=2;break;case 29:codeIndex=stack.pop()+font.gsubrsBias;subrCode=font.gsubrs[codeIndex];if(subrCode){parse(subrCode)}break;case 30:while(stack.length>0){c1x=x;c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y);if(stack.length===0){break}c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();y=c2y+stack.shift();x=c2x+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;case 31:while(stack.length>0){c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();y=c2y+stack.shift();x=c2x+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y);if(stack.length===0){break}c1x=x;c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;default:if(v<32){console.log("Glyph "+glyph.index+": unknown operator "+v)}else if(v<247){stack.push(v-139)}else if(v<251){b1=code[i];i+=1;stack.push((v-247)*256+b1+108)}else if(v<255){b1=code[i];i+=1;stack.push(-(v-251)*256-b1-108)}else{b1=code[i];b2=code[i+1];b3=code[i+2];b4=code[i+3];i+=4;stack.push((b1<<24|b2<<16|b3<<8|b4)/65536)}}}}parse(code);glyph.advanceWidth=width;return p}function calcCFFSubroutineBias(subrs){var bias;if(subrs.length<1240){bias=107}else if(subrs.length<33900){bias=1131}else{bias=32768}return bias}function parseCFFTable(data,start,font){font.tables.cff={};var header=parseCFFHeader(data,start);var nameIndex=parseCFFIndex(data,header.endOffset,bytesToString);var topDictIndex=parseCFFIndex(data,nameIndex.endOffset);var stringIndex=parseCFFIndex(data,topDictIndex.endOffset,bytesToString);var globalSubrIndex=parseCFFIndex(data,stringIndex.endOffset);font.gsubrs=globalSubrIndex.objects;font.gsubrsBias=calcCFFSubroutineBias(font.gsubrs);var topDictData=new DataView(new Uint8Array(topDictIndex.objects[0]).buffer);var topDict=parseCFFTopDict(topDictData,stringIndex.objects);font.tables.cff.topDict=topDict;var privateDictOffset=start+topDict["private"][1];var privateDict=parseCFFPrivateDict(data,privateDictOffset,topDict["private"][0],stringIndex.objects);font.defaultWidthX=privateDict.defaultWidthX;font.nominalWidthX=privateDict.nominalWidthX;if(privateDict.subrs!==0){var subrOffset=privateDictOffset+privateDict.subrs;var subrIndex=parseCFFIndex(data,subrOffset);font.subrs=subrIndex.objects;font.subrsBias=calcCFFSubroutineBias(font.subrs)}else{font.subrs=[];font.subrsBias=0}var charStringsIndex=parseCFFIndex(data,start+topDict.charStrings);font.nGlyphs=charStringsIndex.objects.length;var charset=parseCFFCharset(data,start+topDict.charset,font.nGlyphs,stringIndex.objects);if(topDict.encoding===0){font.cffEncoding=new CffEncoding(cffStandardEncoding,charset)}else if(topDict.encoding===1){font.cffEncoding=new CffEncoding(cffExpertEncoding,charset)}else{font.cffEncoding=parseCFFEncoding(data,start+topDict.encoding,charset)}font.encoding=font.encoding||font.cffEncoding;font.glyphs=new GlyphSet(font);for(var i=0;i<font.nGlyphs;i+=1){var charString=charStringsIndex.objects[i];font.glyphs.push(i,cffGlyphLoader(font,i,parseCFFCharstring,charString))}}function encodeString(s,strings){var sid;var i=cffStandardStrings.indexOf(s);if(i>=0){sid=i}i=strings.indexOf(s);if(i>=0){sid=i+cffStandardStrings.length}else{sid=cffStandardStrings.length+strings.length;strings.push(s)}return sid}function makeHeader(){return new table.Record("Header",[{name:"major",type:"Card8",value:1},{name:"minor",type:"Card8",value:0},{name:"hdrSize",type:"Card8",value:4},{name:"major",type:"Card8",value:1}])}function makeNameIndex(fontNames){var t=new table.Record("Name INDEX",[{name:"names",type:"INDEX",value:[]}]);t.names=[];for(var i=0;i<fontNames.length;i+=1){t.names.push({name:"name_"+i,type:"NAME",value:fontNames[i]})}return t}function makeDict(meta,attrs,strings){var m={};for(var i=0;i<meta.length;i+=1){var entry=meta[i];var value=attrs[entry.name];if(value!==undefined&&!equals(value,entry.value)){if(entry.type==="SID"){value=encodeString(value,strings)}m[entry.op]={name:entry.name,type:entry.type,value:value}}}return m}function makeTopDict(attrs,strings){var t=new table.Record("Top DICT",[{name:"dict",type:"DICT",value:{}}]);t.dict=makeDict(TOP_DICT_META,attrs,strings);return t}function makeTopDictIndex(topDict){var t=new table.Record("Top DICT INDEX",[{name:"topDicts",type:"INDEX",value:[]}]);t.topDicts=[{name:"topDict_0",type:"TABLE",value:topDict}];return t}function makeStringIndex(strings){var t=new table.Record("String INDEX",[{name:"strings",type:"INDEX",value:[]}]);t.strings=[];for(var i=0;i<strings.length;i+=1){t.strings.push({name:"string_"+i,type:"STRING",value:strings[i]})}return t}function makeGlobalSubrIndex(){return new table.Record("Global Subr INDEX",[{name:"subrs",type:"INDEX",value:[]}])}function makeCharsets(glyphNames,strings){var t=new table.Record("Charsets",[{name:"format",type:"Card8",value:0}]);for(var i=0;i<glyphNames.length;i+=1){var glyphName=glyphNames[i];var glyphSID=encodeString(glyphName,strings);t.fields.push({name:"glyph_"+i,type:"SID",value:glyphSID})}return t}function glyphToOps(glyph){var ops=[];var path=glyph.path;ops.push({name:"width",type:"NUMBER",value:glyph.advanceWidth});var x=0;var y=0;for(var i=0;i<path.commands.length;i+=1){var dx;var dy;var cmd=path.commands[i];if(cmd.type==="Q"){var _13=1/3;var _23=2/3;cmd={type:"C",x:cmd.x,y:cmd.y,x1:_13*x+_23*cmd.x1,y1:_13*y+_23*cmd.y1,x2:_13*cmd.x+_23*cmd.x1,y2:_13*cmd.y+_23*cmd.y1}}if(cmd.type==="M"){dx=Math.round(cmd.x-x);dy=Math.round(cmd.y-y);ops.push({name:"dx",type:"NUMBER",value:dx});ops.push({name:"dy",type:"NUMBER",value:dy});ops.push({name:"rmoveto",type:"OP",value:21});x=Math.round(cmd.x);y=Math.round(cmd.y)}else if(cmd.type==="L"){dx=Math.round(cmd.x-x);dy=Math.round(cmd.y-y);ops.push({name:"dx",type:"NUMBER",value:dx});ops.push({name:"dy",type:"NUMBER",value:dy});ops.push({name:"rlineto",type:"OP",value:5});x=Math.round(cmd.x);y=Math.round(cmd.y)}else if(cmd.type==="C"){var dx1=Math.round(cmd.x1-x);var dy1=Math.round(cmd.y1-y);var dx2=Math.round(cmd.x2-cmd.x1);var dy2=Math.round(cmd.y2-cmd.y1);dx=Math.round(cmd.x-cmd.x2);dy=Math.round(cmd.y-cmd.y2);ops.push({name:"dx1",type:"NUMBER",value:dx1});ops.push({name:"dy1",type:"NUMBER",value:dy1
  });ops.push({name:"dx2",type:"NUMBER",value:dx2});ops.push({name:"dy2",type:"NUMBER",value:dy2});ops.push({name:"dx",type:"NUMBER",value:dx});ops.push({name:"dy",type:"NUMBER",value:dy});ops.push({name:"rrcurveto",type:"OP",value:8});x=Math.round(cmd.x);y=Math.round(cmd.y)}}ops.push({name:"endchar",type:"OP",value:14});return ops}function makeCharStringsIndex(glyphs){var t=new table.Record("CharStrings INDEX",[{name:"charStrings",type:"INDEX",value:[]}]);for(var i=0;i<glyphs.length;i+=1){var glyph=glyphs.get(i);var ops=glyphToOps(glyph);t.charStrings.push({name:glyph.name,type:"CHARSTRING",value:ops})}return t}function makePrivateDict(attrs,strings){var t=new table.Record("Private DICT",[{name:"dict",type:"DICT",value:{}}]);t.dict=makeDict(PRIVATE_DICT_META,attrs,strings);return t}function makeCFFTable(glyphs,options){var t=new table.Table("CFF ",[{name:"header",type:"RECORD"},{name:"nameIndex",type:"RECORD"},{name:"topDictIndex",type:"RECORD"},{name:"stringIndex",type:"RECORD"},{name:"globalSubrIndex",type:"RECORD"},{name:"charsets",type:"RECORD"},{name:"charStringsIndex",type:"RECORD"},{name:"privateDict",type:"RECORD"}]);var fontScale=1/options.unitsPerEm;var attrs={version:options.version,fullName:options.fullName,familyName:options.familyName,weight:options.weightName,fontBBox:options.fontBBox||[0,0,0,0],fontMatrix:[fontScale,0,0,fontScale,0,0],charset:999,encoding:0,charStrings:999,private:[0,999]};var privateAttrs={};var glyphNames=[];var glyph;for(var i=1;i<glyphs.length;i+=1){glyph=glyphs.get(i);glyphNames.push(glyph.name)}var strings=[];t.header=makeHeader();t.nameIndex=makeNameIndex([options.postScriptName]);var topDict=makeTopDict(attrs,strings);t.topDictIndex=makeTopDictIndex(topDict);t.globalSubrIndex=makeGlobalSubrIndex();t.charsets=makeCharsets(glyphNames,strings);t.charStringsIndex=makeCharStringsIndex(glyphs);t.privateDict=makePrivateDict(privateAttrs,strings);t.stringIndex=makeStringIndex(strings);var startOffset=t.header.sizeOf()+t.nameIndex.sizeOf()+t.topDictIndex.sizeOf()+t.stringIndex.sizeOf()+t.globalSubrIndex.sizeOf();attrs.charset=startOffset;attrs.encoding=0;attrs.charStrings=attrs.charset+t.charsets.sizeOf();attrs.private[1]=attrs.charStrings+t.charStringsIndex.sizeOf();topDict=makeTopDict(attrs,strings);t.topDictIndex=makeTopDictIndex(topDict);return t}function parseCmapTable(data,start){var i;var cmap={};cmap.version=getUShort(data,start);assert(cmap.version===0,"cmap table version should be 0.");cmap.numTables=getUShort(data,start+2);var offset=-1;for(i=0;i<cmap.numTables;i+=1){var platformId=getUShort(data,start+4+i*8);var encodingId=getUShort(data,start+4+i*8+2);if(platformId===3&&(encodingId===1||encodingId===0)){offset=getULong(data,start+4+i*8+4);break}}if(offset===-1){return null}var p=new Parser(data,start+offset);cmap.format=p.parseUShort();assert(cmap.format===4,"Only format 4 cmap tables are supported.");cmap.length=p.parseUShort();cmap.language=p.parseUShort();var segCount;cmap.segCount=segCount=p.parseUShort()>>1;p.skip("uShort",3);cmap.glyphIndexMap={};var endCountParser=new Parser(data,start+offset+14);var startCountParser=new Parser(data,start+offset+16+segCount*2);var idDeltaParser=new Parser(data,start+offset+16+segCount*4);var idRangeOffsetParser=new Parser(data,start+offset+16+segCount*6);var glyphIndexOffset=start+offset+16+segCount*8;for(i=0;i<segCount-1;i+=1){var glyphIndex;var endCount=endCountParser.parseUShort();var startCount=startCountParser.parseUShort();var idDelta=idDeltaParser.parseShort();var idRangeOffset=idRangeOffsetParser.parseUShort();for(var c=startCount;c<=endCount;c+=1){if(idRangeOffset!==0){glyphIndexOffset=idRangeOffsetParser.offset+idRangeOffsetParser.relativeOffset-2;glyphIndexOffset+=idRangeOffset;glyphIndexOffset+=(c-startCount)*2;glyphIndex=getUShort(data,glyphIndexOffset);if(glyphIndex!==0){glyphIndex=glyphIndex+idDelta&65535}}else{glyphIndex=c+idDelta&65535}cmap.glyphIndexMap[c]=glyphIndex}}return cmap}function addSegment(t,code,glyphIndex){t.segments.push({end:code,start:code,delta:-(code-glyphIndex),offset:0})}function addTerminatorSegment(t){t.segments.push({end:65535,start:65535,delta:1,offset:0})}function makeCmapTable(glyphs){var i;var t=new table.Table("cmap",[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:1},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:12},{name:"format",type:"USHORT",value:4},{name:"length",type:"USHORT",value:0},{name:"language",type:"USHORT",value:0},{name:"segCountX2",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);t.segments=[];for(i=0;i<glyphs.length;i+=1){var glyph=glyphs.get(i);for(var j=0;j<glyph.unicodes.length;j+=1){addSegment(t,glyph.unicodes[j],i)}t.segments=t.segments.sort(function(a,b){return a.start-b.start})}addTerminatorSegment(t);var segCount;segCount=t.segments.length;t.segCountX2=segCount*2;t.searchRange=Math.pow(2,Math.floor(Math.log(segCount)/Math.log(2)))*2;t.entrySelector=Math.log(t.searchRange/2)/Math.log(2);t.rangeShift=t.segCountX2-t.searchRange;var endCounts=[];var startCounts=[];var idDeltas=[];var idRangeOffsets=[];var glyphIds=[];for(i=0;i<segCount;i+=1){var segment=t.segments[i];endCounts=endCounts.concat({name:"end_"+i,type:"USHORT",value:segment.end});startCounts=startCounts.concat({name:"start_"+i,type:"USHORT",value:segment.start});idDeltas=idDeltas.concat({name:"idDelta_"+i,type:"SHORT",value:segment.delta});idRangeOffsets=idRangeOffsets.concat({name:"idRangeOffset_"+i,type:"USHORT",value:segment.offset});if(segment.glyphId!==undefined){glyphIds=glyphIds.concat({name:"glyph_"+i,type:"USHORT",value:segment.glyphId})}}t.fields=t.fields.concat(endCounts);t.fields.push({name:"reservedPad",type:"USHORT",value:0});t.fields=t.fields.concat(startCounts);t.fields=t.fields.concat(idDeltas);t.fields=t.fields.concat(idRangeOffsets);t.fields=t.fields.concat(glyphIds);t.length=14+endCounts.length*2+2+startCounts.length*2+idDeltas.length*2+idRangeOffsets.length*2+glyphIds.length*2;return t}function addName(name,names){var nameString=JSON.stringify(name);var nameID=256;for(var nameKey in names){var n=parseInt(nameKey);if(!n||n<256){continue}if(JSON.stringify(names[nameKey])===nameString){return n}if(nameID<=n){nameID=n+1}}names[nameID]=name;return nameID}function makeFvarAxis(n,axis,names){var nameID=addName(axis.name,names);return[{name:"tag_"+n,type:"TAG",value:axis.tag},{name:"minValue_"+n,type:"FIXED",value:axis.minValue<<16},{name:"defaultValue_"+n,type:"FIXED",value:axis.defaultValue<<16},{name:"maxValue_"+n,type:"FIXED",value:axis.maxValue<<16},{name:"flags_"+n,type:"USHORT",value:0},{name:"nameID_"+n,type:"USHORT",value:nameID}]}function parseFvarAxis(data,start,names){var axis={};var p=new Parser(data,start);axis.tag=p.parseTag();axis.minValue=p.parseFixed();axis.defaultValue=p.parseFixed();axis.maxValue=p.parseFixed();p.skip("uShort",1);axis.name=names[p.parseUShort()]||{};return axis}function makeFvarInstance(n,inst,axes,names){var nameID=addName(inst.name,names);var fields=[{name:"nameID_"+n,type:"USHORT",value:nameID},{name:"flags_"+n,type:"USHORT",value:0}];for(var i=0;i<axes.length;++i){var axisTag=axes[i].tag;fields.push({name:"axis_"+n+" "+axisTag,type:"FIXED",value:inst.coordinates[axisTag]<<16})}return fields}function parseFvarInstance(data,start,axes,names){var inst={};var p=new Parser(data,start);inst.name=names[p.parseUShort()]||{};p.skip("uShort",1);inst.coordinates={};for(var i=0;i<axes.length;++i){inst.coordinates[axes[i].tag]=p.parseFixed()}return inst}function makeFvarTable(fvar,names){var result=new table.Table("fvar",[{name:"version",type:"ULONG",value:65536},{name:"offsetToData",type:"USHORT",value:0},{name:"countSizePairs",type:"USHORT",value:2},{name:"axisCount",type:"USHORT",value:fvar.axes.length},{name:"axisSize",type:"USHORT",value:20},{name:"instanceCount",type:"USHORT",value:fvar.instances.length},{name:"instanceSize",type:"USHORT",value:4+fvar.axes.length*4}]);result.offsetToData=result.sizeOf();for(var i=0;i<fvar.axes.length;i++){result.fields=result.fields.concat(makeFvarAxis(i,fvar.axes[i],names))}for(var j=0;j<fvar.instances.length;j++){result.fields=result.fields.concat(makeFvarInstance(j,fvar.instances[j],fvar.axes,names))}return result}function parseFvarTable(data,start,names){var p=new Parser(data,start);var tableVersion=p.parseULong();assert(tableVersion===65536,"Unsupported fvar table version.");var offsetToData=p.parseOffset16();p.skip("uShort",1);var axisCount=p.parseUShort();var axisSize=p.parseUShort();var instanceCount=p.parseUShort();var instanceSize=p.parseUShort();var axes=[];for(var i=0;i<axisCount;i++){axes.push(parseFvarAxis(data,start+offsetToData+i*axisSize,names))}var instances=[];var instanceStart=start+offsetToData+axisCount*axisSize;for(var j=0;j<instanceCount;j++){instances.push(parseFvarInstance(data,instanceStart+j*instanceSize,axes,names))}return{axes:axes,instances:instances}}function parseGlyphCoordinate(p,flag,previousValue,shortVectorBitMask,sameBitMask){var v;if((flag&shortVectorBitMask)>0){v=p.parseByte();if((flag&sameBitMask)===0){v=-v}v=previousValue+v}else{if((flag&sameBitMask)>0){v=previousValue}else{v=previousValue+p.parseShort()}}return v}function parseGlyph(glyph,data,start){var p=new Parser(data,start);glyph.numberOfContours=p.parseShort();glyph.xMin=p.parseShort();glyph.yMin=p.parseShort();glyph.xMax=p.parseShort();glyph.yMax=p.parseShort();var flags;var flag;if(glyph.numberOfContours>0){var i;var endPointIndices=glyph.endPointIndices=[];for(i=0;i<glyph.numberOfContours;i+=1){endPointIndices.push(p.parseUShort())}glyph.instructionLength=p.parseUShort();glyph.instructions=[];for(i=0;i<glyph.instructionLength;i+=1){glyph.instructions.push(p.parseByte())}var numberOfCoordinates=endPointIndices[endPointIndices.length-1]+1;flags=[];for(i=0;i<numberOfCoordinates;i+=1){flag=p.parseByte();flags.push(flag);if((flag&8)>0){var repeatCount=p.parseByte();for(var j=0;j<repeatCount;j+=1){flags.push(flag);i+=1}}}assert(flags.length===numberOfCoordinates,"Bad flags.");if(endPointIndices.length>0){var points=[];var point;if(numberOfCoordinates>0){for(i=0;i<numberOfCoordinates;i+=1){flag=flags[i];point={};point.onCurve=!!(flag&1);point.lastPointOfContour=endPointIndices.indexOf(i)>=0;points.push(point)}var px=0;for(i=0;i<numberOfCoordinates;i+=1){flag=flags[i];point=points[i];point.x=parseGlyphCoordinate(p,flag,px,2,16);px=point.x}var py=0;for(i=0;i<numberOfCoordinates;i+=1){flag=flags[i];point=points[i];point.y=parseGlyphCoordinate(p,flag,py,4,32);py=point.y}}glyph.points=points}else{glyph.points=[]}}else if(glyph.numberOfContours===0){glyph.points=[]}else{glyph.isComposite=true;glyph.points=[];glyph.components=[];var moreComponents=true;while(moreComponents){flags=p.parseUShort();var component={glyphIndex:p.parseUShort(),xScale:1,scale01:0,scale10:0,yScale:1,dx:0,dy:0};if((flags&1)>0){component.dx=p.parseShort();component.dy=p.parseShort()}else{component.dx=p.parseChar();component.dy=p.parseChar()}if((flags&8)>0){component.xScale=component.yScale=p.parseF2Dot14()}else if((flags&64)>0){component.xScale=p.parseF2Dot14();component.yScale=p.parseF2Dot14()}else if((flags&128)>0){component.xScale=p.parseF2Dot14();component.scale01=p.parseF2Dot14();component.scale10=p.parseF2Dot14();component.yScale=p.parseF2Dot14()}glyph.components.push(component);moreComponents=!!(flags&32)}}}function transformPoints(points,transform){var newPoints=[];for(var i=0;i<points.length;i+=1){var pt=points[i];var newPt={x:transform.xScale*pt.x+transform.scale01*pt.y+transform.dx,y:transform.scale10*pt.x+transform.yScale*pt.y+transform.dy,onCurve:pt.onCurve,lastPointOfContour:pt.lastPointOfContour};newPoints.push(newPt)}return newPoints}function getContours(points){var contours=[];var currentContour=[];for(var i=0;i<points.length;i+=1){var pt=points[i];currentContour.push(pt);if(pt.lastPointOfContour){contours.push(currentContour);currentContour=[]}}assert(currentContour.length===0,"There are still points left in the current contour.");return contours}function getPath(points){var p=new Path;if(!points){return p}var contours=getContours(points);for(var i=0;i<contours.length;i+=1){var contour=contours[i];var firstPt=contour[0];var lastPt=contour[contour.length-1];var curvePt;var realFirstPoint;if(firstPt.onCurve){curvePt=null;realFirstPoint=true}else{if(lastPt.onCurve){firstPt=lastPt}else{firstPt={x:(firstPt.x+lastPt.x)/2,y:(firstPt.y+lastPt.y)/2}}curvePt=firstPt;realFirstPoint=false}p.moveTo(firstPt.x,firstPt.y);for(var j=realFirstPoint?1:0;j<contour.length;j+=1){var pt=contour[j];var prevPt=j===0?firstPt:contour[j-1];if(prevPt.onCurve&&pt.onCurve){p.lineTo(pt.x,pt.y)}else if(prevPt.onCurve&&!pt.onCurve){curvePt=pt}else if(!prevPt.onCurve&&!pt.onCurve){var midPt={x:(prevPt.x+pt.x)/2,y:(prevPt.y+pt.y)/2};p.quadraticCurveTo(prevPt.x,prevPt.y,midPt.x,midPt.y);curvePt=pt}else if(!prevPt.onCurve&&pt.onCurve){p.quadraticCurveTo(curvePt.x,curvePt.y,pt.x,pt.y);curvePt=null}else{throw new Error("Invalid state.")}}if(firstPt!==lastPt){if(curvePt){p.quadraticCurveTo(curvePt.x,curvePt.y,firstPt.x,firstPt.y)}else{p.lineTo(firstPt.x,firstPt.y)}}}p.closePath();return p}function buildPath(glyphs,glyph){if(glyph.isComposite){for(var j=0;j<glyph.components.length;j+=1){var component=glyph.components[j];var componentGlyph=glyphs.get(component.glyphIndex);componentGlyph.getPath();if(componentGlyph.points){var transformedPoints=transformPoints(componentGlyph.points,component);glyph.points=glyph.points.concat(transformedPoints)}}}return getPath(glyph.points)}function parseGlyfTable(data,start,loca,font){var glyphs=new GlyphSet(font);var i;for(i=0;i<loca.length-1;i+=1){var offset=loca[i];var nextOffset=loca[i+1];if(offset!==nextOffset){glyphs.push(i,ttfGlyphLoader(font,i,parseGlyph,data,start+offset,buildPath))}else{glyphs.push(i,glyphLoader(font,i))}}return glyphs}function parseTaggedListTable(data,start){var p=new Parser(data,start);var n=p.parseUShort();var list=[];for(var i=0;i<n;i++){list[p.parseTag()]={offset:p.parseUShort()}}return list}function parseCoverageTable(data,start){var p=new Parser(data,start);var format=p.parseUShort();var count=p.parseUShort();if(format===1){return p.parseUShortList(count)}else if(format===2){var coverage=[];for(;count--;){var begin=p.parseUShort();var end=p.parseUShort();var index=p.parseUShort();for(var i=begin;i<=end;i++){coverage[index++]=i}}return coverage}}function parseClassDefTable(data,start){var p=new Parser(data,start);var format=p.parseUShort();if(format===1){var startGlyph=p.parseUShort();var glyphCount=p.parseUShort();var classes=p.parseUShortList(glyphCount);return function(glyphID){return classes[glyphID-startGlyph]||0}}else if(format===2){var rangeCount=p.parseUShort();var startGlyphs=[];var endGlyphs=[];var classValues=[];for(var i=0;i<rangeCount;i++){startGlyphs[i]=p.parseUShort();endGlyphs[i]=p.parseUShort();classValues[i]=p.parseUShort()}return function(glyphID){var l=0;var r=startGlyphs.length-1;while(l<r){var c=l+r+1>>1;if(glyphID<startGlyphs[c]){r=c-1}else{l=c}}if(startGlyphs[l]<=glyphID&&glyphID<=endGlyphs[l]){return classValues[l]||0}return 0}}}function parsePairPosSubTable(data,start){var p=new Parser(data,start);var format=p.parseUShort();var coverageOffset=p.parseUShort();var coverage=parseCoverageTable(data,start+coverageOffset);var valueFormat1=p.parseUShort();var valueFormat2=p.parseUShort();var value1;var value2;if(valueFormat1!==4||valueFormat2!==0)return;var sharedPairSets={};if(format===1){var pairSetCount=p.parseUShort();var pairSet=[];var pairSetOffsets=p.parseOffset16List(pairSetCount);for(var firstGlyph=0;firstGlyph<pairSetCount;firstGlyph++){var pairSetOffset=pairSetOffsets[firstGlyph];var sharedPairSet=sharedPairSets[pairSetOffset];if(!sharedPairSet){sharedPairSet={};p.relativeOffset=pairSetOffset;var pairValueCount=p.parseUShort();for(;pairValueCount--;){var secondGlyph=p.parseUShort();if(valueFormat1)value1=p.parseShort();if(valueFormat2)value2=p.parseShort();sharedPairSet[secondGlyph]=value1}}pairSet[coverage[firstGlyph]]=sharedPairSet}return function(leftGlyph,rightGlyph){var pairs=pairSet[leftGlyph];if(pairs)return pairs[rightGlyph]}}else if(format===2){var classDef1Offset=p.parseUShort();var classDef2Offset=p.parseUShort();var class1Count=p.parseUShort();var class2Count=p.parseUShort();var getClass1=parseClassDefTable(data,start+classDef1Offset);var getClass2=parseClassDefTable(data,start+classDef2Offset);var kerningMatrix=[];for(var i=0;i<class1Count;i++){var kerningRow=kerningMatrix[i]=[];for(var j=0;j<class2Count;j++){if(valueFormat1)value1=p.parseShort();if(valueFormat2)value2=p.parseShort();kerningRow[j]=value1}}var covered={};for(i=0;i<coverage.length;i++)covered[coverage[i]]=1;return function(leftGlyph,rightGlyph){if(!covered[leftGlyph])return;var class1=getClass1(leftGlyph);var class2=getClass2(rightGlyph);var kerningRow=kerningMatrix[class1];if(kerningRow){return kerningRow[class2]}}}}function parseLookupTable(data,start){var p=new Parser(data,start);var lookupType=p.parseUShort();var lookupFlag=p.parseUShort();var useMarkFilteringSet=lookupFlag&16;var subTableCount=p.parseUShort();var subTableOffsets=p.parseOffset16List(subTableCount);var table={lookupType:lookupType,lookupFlag:lookupFlag,markFilteringSet:useMarkFilteringSet?p.parseUShort():-1};if(lookupType===2){var subtables=[];for(var i=0;i<subTableCount;i++){subtables.push(parsePairPosSubTable(data,start+subTableOffsets[i]))}table.getKerningValue=function(leftGlyph,rightGlyph){for(var i=subtables.length;i--;){var value=subtables[i](leftGlyph,rightGlyph);if(value!==undefined)return value}return 0}}return table}function parseGposTable(data,start,font){var p=new Parser(data,start);var tableVersion=p.parseFixed();assert(tableVersion===1,"Unsupported GPOS table version.");parseTaggedListTable(data,start+p.parseUShort());parseTaggedListTable(data,start+p.parseUShort());var lookupListOffset=p.parseUShort();p.relativeOffset=lookupListOffset;var lookupCount=p.parseUShort();var lookupTableOffsets=p.parseOffset16List(lookupCount);var lookupListAbsoluteOffset=start+lookupListOffset;for(var i=0;i<lookupCount;i++){var table=parseLookupTable(data,lookupListAbsoluteOffset+lookupTableOffsets[i]);if(table.lookupType===2&&!font.getGposKerningValue)font.getGposKerningValue=table.getKerningValue}}function parseHeadTable(data,start){var head={};var p=new Parser(data,start);head.version=p.parseVersion();head.fontRevision=Math.round(p.parseFixed()*1e3)/1e3;head.checkSumAdjustment=p.parseULong();head.magicNumber=p.parseULong();assert(head.magicNumber===1594834165,"Font header has wrong magic number.");head.flags=p.parseUShort();head.unitsPerEm=p.parseUShort();head.created=p.parseLongDateTime();head.modified=p.parseLongDateTime();head.xMin=p.parseShort();head.yMin=p.parseShort();head.xMax=p.parseShort();head.yMax=p.parseShort();head.macStyle=p.parseUShort();head.lowestRecPPEM=p.parseUShort();head.fontDirectionHint=p.parseShort();head.indexToLocFormat=p.parseShort();head.glyphDataFormat=p.parseShort();return head}function makeHeadTable(options){return new table.Table("head",[{name:"version",type:"FIXED",value:65536},{name:"fontRevision",type:"FIXED",value:65536},{name:"checkSumAdjustment",type:"ULONG",value:0},{name:"magicNumber",type:"ULONG",value:1594834165},{name:"flags",type:"USHORT",value:0},{name:"unitsPerEm",type:"USHORT",value:1e3},{name:"created",type:"LONGDATETIME",value:0},{name:"modified",type:"LONGDATETIME",value:0},{name:"xMin",type:"SHORT",value:0},{name:"yMin",type:"SHORT",value:0},{name:"xMax",type:"SHORT",value:0},{name:"yMax",type:"SHORT",value:0},{name:"macStyle",type:"USHORT",value:0},{name:"lowestRecPPEM",type:"USHORT",value:0},{name:"fontDirectionHint",type:"SHORT",value:2},{name:"indexToLocFormat",type:"SHORT",value:0},{name:"glyphDataFormat",type:"SHORT",value:0}],options)}function parseHheaTable(data,start){var hhea={};var p=new Parser(data,start);hhea.version=p.parseVersion();hhea.ascender=p.parseShort();hhea.descender=p.parseShort();hhea.lineGap=p.parseShort();hhea.advanceWidthMax=p.parseUShort();hhea.minLeftSideBearing=p.parseShort();hhea.minRightSideBearing=p.parseShort();hhea.xMaxExtent=p.parseShort();hhea.caretSlopeRise=p.parseShort();hhea.caretSlopeRun=p.parseShort();hhea.caretOffset=p.parseShort();p.relativeOffset+=8;hhea.metricDataFormat=p.parseShort();hhea.numberOfHMetrics=p.parseUShort();return hhea}function makeHheaTable(options){return new table.Table("hhea",[{name:"version",type:"FIXED",value:65536},{name:"ascender",type:"FWORD",value:0},{name:"descender",type:"FWORD",value:0},{name:"lineGap",type:"FWORD",value:0},{name:"advanceWidthMax",type:"UFWORD",value:0},{name:"minLeftSideBearing",type:"FWORD",value:0},{name:"minRightSideBearing",type:"FWORD",value:0},{name:"xMaxExtent",type:"FWORD",value:0},{name:"caretSlopeRise",type:"SHORT",value:1},{name:"caretSlopeRun",type:"SHORT",value:0},{name:"caretOffset",type:"SHORT",value:0},{name:"reserved1",type:"SHORT",value:0},{name:"reserved2",type:"SHORT",value:0},{name:"reserved3",type:"SHORT",value:0},{name:"reserved4",type:"SHORT",value:0},{name:"metricDataFormat",type:"SHORT",value:0},{name:"numberOfHMetrics",type:"USHORT",value:0}],options)}function parseHmtxTable(data,start,numMetrics,numGlyphs,glyphs){var advanceWidth;var leftSideBearing;var p=new Parser(data,start);for(var i=0;i<numGlyphs;i+=1){if(i<numMetrics){advanceWidth=p.parseUShort();leftSideBearing=p.parseShort()}var glyph=glyphs.get(i);glyph.advanceWidth=advanceWidth;glyph.leftSideBearing=leftSideBearing}}function makeHmtxTable(glyphs){var t=new table.Table("hmtx",[]);for(var i=0;i<glyphs.length;i+=1){var glyph=glyphs.get(i);var advanceWidth=glyph.advanceWidth||0;var leftSideBearing=glyph.leftSideBearing||0;t.fields.push({name:"advanceWidth_"+i,type:"USHORT",value:advanceWidth});t.fields.push({name:"leftSideBearing_"+i,type:"SHORT",value:leftSideBearing})}return t}function parseKernTable(data,start){var pairs={};var p=new Parser(data,start);var tableVersion=p.parseUShort();assert(tableVersion===0,"Unsupported kern table version.");p.skip("uShort",1);var subTableVersion=p.parseUShort();assert(subTableVersion===0,"Unsupported kern sub-table version.");p.skip("uShort",2);var nPairs=p.parseUShort();p.skip("uShort",3);for(var i=0;i<nPairs;i+=1){var leftIndex=p.parseUShort();var rightIndex=p.parseUShort();var value=p.parseShort();pairs[leftIndex+","+rightIndex]=value}return pairs}function parseLocaTable(data,start,numGlyphs,shortVersion){var p=new Parser(data,start);var parseFn=shortVersion?p.parseUShort:p.parseULong;var glyphOffsets=[];for(var i=0;i<numGlyphs+1;i+=1){var glyphOffset=parseFn.call(p);if(shortVersion){glyphOffset*=2}glyphOffsets.push(glyphOffset)}return glyphOffsets}function makeLtagTable(tags){var result=new table.Table("ltag",[{name:"version",type:"ULONG",value:1},{name:"flags",type:"ULONG",value:0},{name:"numTags",type:"ULONG",value:tags.length}]);var stringPool="";var stringPoolOffset=12+tags.length*4;for(var i=0;i<tags.length;++i){var pos=stringPool.indexOf(tags[i]);if(pos<0){pos=stringPool.length;stringPool+=tags[i]}result.fields.push({name:"offset "+i,type:"USHORT",value:stringPoolOffset+pos});result.fields.push({name:"length "+i,type:"USHORT",value:tags[i].length})}result.fields.push({name:"stringPool",type:"CHARARRAY",value:stringPool});return result}function parseLtagTable(data,start){var p=new Parser(data,start);var tableVersion=p.parseULong();assert(tableVersion===1,"Unsupported ltag table version.");p.skip("uLong",1);var numTags=p.parseULong();var tags=[];for(var i=0;i<numTags;i++){var tag="";var offset=start+p.parseUShort();var length=p.parseUShort();for(var j=offset;j<offset+length;++j){tag+=String.fromCharCode(data.getInt8(j))}tags.push(tag)}return tags}function parseMaxpTable(data,start){var maxp={};var p=new Parser(data,start);maxp.version=p.parseVersion();maxp.numGlyphs=p.parseUShort();if(maxp.version===1){maxp.maxPoints=p.parseUShort();maxp.maxContours=p.parseUShort();maxp.maxCompositePoints=p.parseUShort();maxp.maxCompositeContours=p.parseUShort();maxp.maxZones=p.parseUShort();maxp.maxTwilightPoints=p.parseUShort();maxp.maxStorage=p.parseUShort();maxp.maxFunctionDefs=p.parseUShort();maxp.maxInstructionDefs=p.parseUShort();maxp.maxStackElements=p.parseUShort();maxp.maxSizeOfInstructions=p.parseUShort();maxp.maxComponentElements=p.parseUShort();maxp.maxComponentDepth=p.parseUShort()}return maxp}function makeMaxpTable(numGlyphs){return new table.Table("maxp",[{name:"version",type:"FIXED",value:20480},{name:"numGlyphs",type:"USHORT",value:numGlyphs}])}var nameTableNames=["copyright","fontFamily","fontSubfamily","uniqueID","fullName","version","postScriptName","trademark","manufacturer","designer","description","manufacturerURL","designerURL","license","licenseURL","reserved","preferredFamily","preferredSubfamily","compatibleFullName","sampleText","postScriptFindFontName","wwsFamily","wwsSubfamily"];var macLanguages={0:"en",1:"fr",2:"de",3:"it",4:"nl",5:"sv",6:"es",7:"da",8:"pt",9:"no",10:"he",11:"ja",12:"ar",13:"fi",14:"el",15:"is",16:"mt",17:"tr",18:"hr",19:"zh-Hant",20:"ur",21:"hi",22:"th",23:"ko",24:"lt",25:"pl",26:"hu",27:"es",28:"lv",29:"se",30:"fo",31:"fa",32:"ru",33:"zh",34:"nl-BE",35:"ga",36:"sq",37:"ro",38:"cz",39:"sk",40:"si",41:"yi",42:"sr",43:"mk",44:"bg",45:"uk",46:"be",47:"uz",48:"kk",49:"az-Cyrl",50:"az-Arab",51:"hy",52:"ka",53:"mo",54:"ky",55:"tg",56:"tk",57:"mn-CN",58:"mn",59:"ps",60:"ks",61:"ku",62:"sd",63:"bo",64:"ne",65:"sa",66:"mr",67:"bn",68:"as",69:"gu",70:"pa",71:"or",72:"ml",73:"kn",74:"ta",75:"te",76:"si",77:"my",78:"km",79:"lo",80:"vi",81:"id",82:"tl",83:"ms",84:"ms-Arab",85:"am",86:"ti",87:"om",88:"so",89:"sw",90:"rw",91:"rn",92:"ny",93:"mg",94:"eo",128:"cy",129:"eu",130:"ca",131:"la",132:"qu",133:"gn",134:"ay",135:"tt",136:"ug",137:"dz",138:"jv",139:"su",140:"gl",141:"af",142:"br",143:"iu",144:"gd",145:"gv",146:"ga",147:"to",148:"el-polyton",149:"kl",150:"az",151:"nn"};var macLanguageToScript={0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:5,11:1,12:4,13:0,14:6,15:0,16:0,17:0,18:0,19:2,20:4,21:9,22:21,23:3,24:29,25:29,26:29,27:29,28:29,29:0,30:0,31:4,32:7,33:25,34:0,35:0,36:0,37:0,38:29,39:29,40:0,41:5,42:7,43:7,44:7,45:7,46:7,47:7,48:7,49:7,50:4,51:24,52:23,53:7,54:7,55:7,56:7,57:27,58:7,59:4,60:4,61:4,62:4,63:26,64:9,65:9,66:9,67:13,68:13,69:11,70:10,71:12,72:17,73:16,74:14,75:15,76:18,77:19,78:20,79:22,80:30,81:0,82:0,83:0,84:4,85:28,86:28,87:28,88:0,89:0,90:0,91:0,92:0,93:0,94:0,128:0,129:0,130:0,131:0,132:0,133:0,134:0,135:7,136:4,137:26,138:0,139:0,140:0,141:0,142:0,143:28,144:0,145:0,146:0,147:0,148:6,149:0,150:0,151:0};var windowsLanguages={1078:"af",1052:"sq",1156:"gsw",1118:"am",5121:"ar-DZ",15361:"ar-BH",3073:"ar",2049:"ar-IQ",11265:"ar-JO",13313:"ar-KW",12289:"ar-LB",4097:"ar-LY",6145:"ary",8193:"ar-OM",16385:"ar-QA",1025:"ar-SA",10241:"ar-SY",7169:"aeb",14337:"ar-AE",9217:"ar-YE",1067:"hy",1101:"as",2092:"az-Cyrl",1068:"az",1133:"ba",1069:"eu",1059:"be",2117:"bn",1093:"bn-IN",8218:"bs-Cyrl",5146:"bs",1150:"br",1026:"bg",1027:"ca",3076:"zh-HK",5124:"zh-MO",2052:"zh",4100:"zh-SG",1028:"zh-TW",1155:"co",1050:"hr",4122:"hr-BA",1029:"cs",1030:"da",1164:"prs",1125:"dv",2067:"nl-BE",1043:"nl",3081:"en-AU",10249:"en-BZ",4105:"en-CA",9225:"en-029",16393:"en-IN",6153:"en-IE",8201:"en-JM",17417:"en-MY",5129:"en-NZ",13321:"en-PH",18441:"en-SG",7177:"en-ZA",11273:"en-TT",2057:"en-GB",1033:"en",12297:"en-ZW",1061:"et",1080:"fo",1124:"fil",1035:"fi",2060:"fr-BE",3084:"fr-CA",1036:"fr",5132:"fr-LU",6156:"fr-MC",4108:"fr-CH",1122:"fy",1110:"gl",1079:"ka",3079:"de-AT",1031:"de",5127:"de-LI",4103:"de-LU",2055:"de-CH",1032:"el",1135:"kl",1095:"gu",1128:"ha",1037:"he",1081:"hi",1038:"hu",1039:"is",1136:"ig",1057:"id",1117:"iu",2141:"iu-Latn",2108:"ga",1076:"xh",1077:"zu",1040:"it",2064:"it-CH",1041:"ja",1099:"kn",1087:"kk",1107:"km",1158:"quc",1159:"rw",1089:"sw",1111:"kok",1042:"ko",1088:"ky",1108:"lo",1062:"lv",1063:"lt",2094:"dsb",1134:"lb",1071:"mk",2110:"ms-BN",1086:"ms",1100:"ml",1082:"mt",1153:"mi",1146:"arn",1102:"mr",1148:"moh",1104:"mn",2128:"mn-CN",1121:"ne",1044:"nb",2068:"nn",1154:"oc",1096:"or",1123:"ps",1045:"pl",1046:"pt",2070:"pt-PT",1094:"pa",1131:"qu-BO",2155:"qu-EC",3179:"qu",1048:"ro",1047:"rm",1049:"ru",9275:"smn",4155:"smj-NO",5179:"smj",3131:"se-FI",1083:"se",2107:"se-SE",8251:"sms",6203:"sma-NO",7227:"sms",1103:"sa",7194:"sr-Cyrl-BA",3098:"sr",6170:"sr-Latn-BA",2074:"sr-Latn",1132:"nso",1074:"tn",1115:"si",1051:"sk",1060:"sl",11274:"es-AR",16394:"es-BO",13322:"es-CL",9226:"es-CO",5130:"es-CR",7178:"es-DO",12298:"es-EC",17418:"es-SV",4106:"es-GT",18442:"es-HN",2058:"es-MX",19466:"es-NI",6154:"es-PA",15370:"es-PY",10250:"es-PE",20490:"es-PR",3082:"es",1034:"es",21514:"es-US",14346:"es-UY",8202:"es-VE",2077:"sv-FI",1053:"sv",1114:"syr",1064:"tg",2143:"tzm",1097:"ta",1092:"tt",1098:"te",1054:"th",1105:"bo",1055:"tr",1090:"tk",1152:"ug",1058:"uk",1070:"hsb",1056:"ur",2115:"uz-Cyrl",1091:"uz",1066:"vi",1106:"cy",1160:"wo",1157:"sah",1144:"ii",1130:"yo"};function getLanguageCode(platformID,languageID,ltag){switch(platformID){case 0:if(languageID===65535){return"und"}else if(ltag){return ltag[languageID]}break;case 1:return macLanguages[languageID];case 3:return windowsLanguages[languageID]}return undefined}var utf16="utf-16";var macScriptEncodings={0:"macintosh",1:"x-mac-japanese",2:"x-mac-chinesetrad",3:"x-mac-korean",6:"x-mac-greek",7:"x-mac-cyrillic",9:"x-mac-devanagai",10:"x-mac-gurmukhi",11:"x-mac-gujarati",12:"x-mac-oriya",13:"x-mac-bengali",14:"x-mac-tamil",15:"x-mac-telugu",16:"x-mac-kannada",17:"x-mac-malayalam",18:"x-mac-sinhalese",19:"x-mac-burmese",20:"x-mac-khmer",21:"x-mac-thai",22:"x-mac-lao",23:"x-mac-georgian",24:"x-mac-armenian",25:"x-mac-chinesesimp",26:"x-mac-tibetan",27:"x-mac-mongolian",28:"x-mac-ethiopic",29:"x-mac-ce",30:"x-mac-vietnamese",31:"x-mac-extarabic"};var macLanguageEncodings={15:"x-mac-icelandic",17:"x-mac-turkish",18:"x-mac-croatian",24:"x-mac-ce",25:"x-mac-ce",26:"x-mac-ce",27:"x-mac-ce",28:"x-mac-ce",30:"x-mac-icelandic",37:"x-mac-romanian",38:"x-mac-ce",39:"x-mac-ce",40:"x-mac-ce",143:"x-mac-inuit",146:"x-mac-gaelic"};function getEncoding(platformID,encodingID,languageID){switch(platformID){case 0:return utf16;case 1:return macLanguageEncodings[languageID]||macScriptEncodings[encodingID];case 3:if(encodingID===1||encodingID===10){return utf16}break}return undefined}function parseNameTable(data,start,ltag){var name={};var p=new Parser(data,start);var format=p.parseUShort();var count=p.parseUShort();var stringOffset=p.offset+p.parseUShort();for(var i=0;i<count;i++){var platformID=p.parseUShort();var encodingID=p.parseUShort();var languageID=p.parseUShort();var nameID=p.parseUShort();var property=nameTableNames[nameID]||nameID;var byteLength=p.parseUShort();var offset=p.parseUShort();var language=getLanguageCode(platformID,languageID,ltag);var encoding=getEncoding(platformID,encodingID,languageID);if(encoding!==undefined&&language!==undefined){var text;if(encoding===utf16){text=opentype_decode.UTF16(data,stringOffset+offset,byteLength)}else{text=opentype_decode.MACSTRING(data,stringOffset+offset,byteLength,encoding)}if(text){var translations=name[property];if(translations===undefined){translations=name[property]={}}translations[language]=text}}}var langTagCount=0;if(format===1){langTagCount=p.parseUShort()}return name}function reverseDict(dict){var result={};for(var key in dict){result[dict[key]]=parseInt(key)}return result}function makeNameRecord(platformID,encodingID,languageID,nameID,length,offset){return new table.Record("NameRecord",[{name:"platformID",type:"USHORT",value:platformID},{name:"encodingID",type:"USHORT",value:encodingID},{name:"languageID",type:"USHORT",value:languageID},{name:"nameID",type:"USHORT",value:nameID},{name:"length",type:"USHORT",value:length},{name:"offset",type:"USHORT",value:offset}])}function findSubArray(needle,haystack){var needleLength=needle.length;
  var limit=haystack.length-needleLength+1;loop:for(var pos=0;pos<limit;pos++){for(;pos<limit;pos++){for(var k=0;k<needleLength;k++){if(haystack[pos+k]!==needle[k]){continue loop}}return pos}}return-1}function addStringToPool(s,pool){var offset=findSubArray(s,pool);if(offset<0){offset=pool.length;for(var i=0,len=s.length;i<len;++i){pool.push(s[i])}}return offset}function makeNameTable(names,ltag){var nameID;var nameIDs=[];var namesWithNumericKeys={};var nameTableIds=reverseDict(nameTableNames);for(var key in names){var id=nameTableIds[key];if(id===undefined){id=key}nameID=parseInt(id);namesWithNumericKeys[nameID]=names[key];nameIDs.push(nameID)}var macLanguageIds=reverseDict(macLanguages);var windowsLanguageIds=reverseDict(windowsLanguages);var nameRecords=[];var stringPool=[];for(var i=0;i<nameIDs.length;i++){nameID=nameIDs[i];var translations=namesWithNumericKeys[nameID];for(var lang in translations){var text=translations[lang];var macPlatform=1;var macLanguage=macLanguageIds[lang];var macScript=macLanguageToScript[macLanguage];var macEncoding=getEncoding(macPlatform,macScript,macLanguage);var macName=encode.MACSTRING(text,macEncoding);if(macName===undefined){macPlatform=0;macLanguage=ltag.indexOf(lang);if(macLanguage<0){macLanguage=ltag.length;ltag.push(lang)}macScript=4;macName=encode.UTF16(text)}var macNameOffset=addStringToPool(macName,stringPool);nameRecords.push(makeNameRecord(macPlatform,macScript,macLanguage,nameID,macName.length,macNameOffset));var winLanguage=windowsLanguageIds[lang];if(winLanguage!==undefined){var winName=encode.UTF16(text);var winNameOffset=addStringToPool(winName,stringPool);nameRecords.push(makeNameRecord(3,1,winLanguage,nameID,winName.length,winNameOffset))}}}nameRecords.sort(function(a,b){return a.platformID-b.platformID||a.encodingID-b.encodingID||a.languageID-b.languageID||a.nameID-b.nameID});var t=new table.Table("name",[{name:"format",type:"USHORT",value:0},{name:"count",type:"USHORT",value:nameRecords.length},{name:"stringOffset",type:"USHORT",value:6+nameRecords.length*12}]);for(var r=0;r<nameRecords.length;r++){t.fields.push({name:"record_"+r,type:"RECORD",value:nameRecords[r]})}t.fields.push({name:"strings",type:"LITERAL",value:stringPool});return t}var unicodeRanges=[{begin:0,end:127},{begin:128,end:255},{begin:256,end:383},{begin:384,end:591},{begin:592,end:687},{begin:688,end:767},{begin:768,end:879},{begin:880,end:1023},{begin:11392,end:11519},{begin:1024,end:1279},{begin:1328,end:1423},{begin:1424,end:1535},{begin:42240,end:42559},{begin:1536,end:1791},{begin:1984,end:2047},{begin:2304,end:2431},{begin:2432,end:2559},{begin:2560,end:2687},{begin:2688,end:2815},{begin:2816,end:2943},{begin:2944,end:3071},{begin:3072,end:3199},{begin:3200,end:3327},{begin:3328,end:3455},{begin:3584,end:3711},{begin:3712,end:3839},{begin:4256,end:4351},{begin:6912,end:7039},{begin:4352,end:4607},{begin:7680,end:7935},{begin:7936,end:8191},{begin:8192,end:8303},{begin:8304,end:8351},{begin:8352,end:8399},{begin:8400,end:8447},{begin:8448,end:8527},{begin:8528,end:8591},{begin:8592,end:8703},{begin:8704,end:8959},{begin:8960,end:9215},{begin:9216,end:9279},{begin:9280,end:9311},{begin:9312,end:9471},{begin:9472,end:9599},{begin:9600,end:9631},{begin:9632,end:9727},{begin:9728,end:9983},{begin:9984,end:10175},{begin:12288,end:12351},{begin:12352,end:12447},{begin:12448,end:12543},{begin:12544,end:12591},{begin:12592,end:12687},{begin:43072,end:43135},{begin:12800,end:13055},{begin:13056,end:13311},{begin:44032,end:55215},{begin:55296,end:57343},{begin:67840,end:67871},{begin:19968,end:40959},{begin:57344,end:63743},{begin:12736,end:12783},{begin:64256,end:64335},{begin:64336,end:65023},{begin:65056,end:65071},{begin:65040,end:65055},{begin:65104,end:65135},{begin:65136,end:65279},{begin:65280,end:65519},{begin:65520,end:65535},{begin:3840,end:4095},{begin:1792,end:1871},{begin:1920,end:1983},{begin:3456,end:3583},{begin:4096,end:4255},{begin:4608,end:4991},{begin:5024,end:5119},{begin:5120,end:5759},{begin:5760,end:5791},{begin:5792,end:5887},{begin:6016,end:6143},{begin:6144,end:6319},{begin:10240,end:10495},{begin:40960,end:42127},{begin:5888,end:5919},{begin:66304,end:66351},{begin:66352,end:66383},{begin:66560,end:66639},{begin:118784,end:119039},{begin:119808,end:120831},{begin:1044480,end:1048573},{begin:65024,end:65039},{begin:917504,end:917631},{begin:6400,end:6479},{begin:6480,end:6527},{begin:6528,end:6623},{begin:6656,end:6687},{begin:11264,end:11359},{begin:11568,end:11647},{begin:19904,end:19967},{begin:43008,end:43055},{begin:65536,end:65663},{begin:65856,end:65935},{begin:66432,end:66463},{begin:66464,end:66527},{begin:66640,end:66687},{begin:66688,end:66735},{begin:67584,end:67647},{begin:68096,end:68191},{begin:119552,end:119647},{begin:73728,end:74751},{begin:119648,end:119679},{begin:7040,end:7103},{begin:7168,end:7247},{begin:7248,end:7295},{begin:43136,end:43231},{begin:43264,end:43311},{begin:43312,end:43359},{begin:43520,end:43615},{begin:65936,end:65999},{begin:66e3,end:66047},{begin:66208,end:66271},{begin:127024,end:127135}];function getUnicodeRange(unicode){for(var i=0;i<unicodeRanges.length;i+=1){var range=unicodeRanges[i];if(unicode>=range.begin&&unicode<range.end){return i}}return-1}var os2={};function parseOS2Table(data,start){var p=new Parser(data,start);os2.version=p.parseUShort();os2.xAvgCharWidth=p.parseShort();os2.usWeightClass=p.parseUShort();os2.usWidthClass=p.parseUShort();os2.fsType=p.parseUShort();os2.ySubscriptXSize=p.parseShort();os2.ySubscriptYSize=p.parseShort();os2.ySubscriptXOffset=p.parseShort();os2.ySubscriptYOffset=p.parseShort();os2.ySuperscriptXSize=p.parseShort();os2.ySuperscriptYSize=p.parseShort();os2.ySuperscriptXOffset=p.parseShort();os2.ySuperscriptYOffset=p.parseShort();os2.yStrikeoutSize=p.parseShort();os2.yStrikeoutPosition=p.parseShort();os2.sFamilyClass=p.parseShort();os2.panose=[];for(var i=0;i<10;i++){os2.panose[i]=p.parseByte()}os2.ulUnicodeRange1=p.parseULong();os2.ulUnicodeRange2=p.parseULong();os2.ulUnicodeRange3=p.parseULong();os2.ulUnicodeRange4=p.parseULong();os2.achVendID=String.fromCharCode(p.parseByte(),p.parseByte(),p.parseByte(),p.parseByte());os2.fsSelection=p.parseUShort();os2.usFirstCharIndex=p.parseUShort();os2.usLastCharIndex=p.parseUShort();os2.sTypoAscender=p.parseShort();os2.sTypoDescender=p.parseShort();os2.sTypoLineGap=p.parseShort();os2.usWinAscent=p.parseUShort();os2.usWinDescent=p.parseUShort();if(os2.version>=1){os2.ulCodePageRange1=p.parseULong();os2.ulCodePageRange2=p.parseULong()}if(os2.version>=2){os2.sxHeight=p.parseShort();os2.sCapHeight=p.parseShort();os2.usDefaultChar=p.parseUShort();os2.usBreakChar=p.parseUShort();os2.usMaxContent=p.parseUShort()}return os2}function makeOS2Table(options){return new table.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],options)}function parsePostTable(data,start){var post={};var p=new Parser(data,start);var i;post.version=p.parseVersion();post.italicAngle=p.parseFixed();post.underlinePosition=p.parseShort();post.underlineThickness=p.parseShort();post.isFixedPitch=p.parseULong();post.minMemType42=p.parseULong();post.maxMemType42=p.parseULong();post.minMemType1=p.parseULong();post.maxMemType1=p.parseULong();switch(post.version){case 1:post.names=standardNames.slice();break;case 2:post.numberOfGlyphs=p.parseUShort();post.glyphNameIndex=new Array(post.numberOfGlyphs);for(i=0;i<post.numberOfGlyphs;i++){post.glyphNameIndex[i]=p.parseUShort()}post.names=[];for(i=0;i<post.numberOfGlyphs;i++){if(post.glyphNameIndex[i]>=standardNames.length){var nameLength=p.parseChar();post.names.push(p.parseString(nameLength))}}break;case 2.5:post.numberOfGlyphs=p.parseUShort();post.offset=new Array(post.numberOfGlyphs);for(i=0;i<post.numberOfGlyphs;i++){post.offset[i]=p.parseChar()}break}return post}function makePostTable(){return new table.Table("post",[{name:"version",type:"FIXED",value:196608},{name:"italicAngle",type:"FIXED",value:0},{name:"underlinePosition",type:"FWORD",value:0},{name:"underlineThickness",type:"FWORD",value:0},{name:"isFixedPitch",type:"ULONG",value:0},{name:"minMemType42",type:"ULONG",value:0},{name:"maxMemType42",type:"ULONG",value:0},{name:"minMemType1",type:"ULONG",value:0},{name:"maxMemType1",type:"ULONG",value:0}])}function log2(v){return Math.log(v)/Math.log(2)|0}function computeCheckSum(bytes){while(bytes.length%4!==0){bytes.push(0)}var sum=0;for(var i=0;i<bytes.length;i+=4){sum+=(bytes[i]<<24)+(bytes[i+1]<<16)+(bytes[i+2]<<8)+bytes[i+3]}sum%=Math.pow(2,32);return sum}function makeTableRecord(tag,checkSum,offset,length){return new table.Record("Table Record",[{name:"tag",type:"TAG",value:tag!==undefined?tag:""},{name:"checkSum",type:"ULONG",value:checkSum!==undefined?checkSum:0},{name:"offset",type:"ULONG",value:offset!==undefined?offset:0},{name:"length",type:"ULONG",value:length!==undefined?length:0}])}function makeSfntTable(tables){var sfnt=new table.Table("sfnt",[{name:"version",type:"TAG",value:"OTTO"},{name:"numTables",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);sfnt.tables=tables;sfnt.numTables=tables.length;var highestPowerOf2=Math.pow(2,log2(sfnt.numTables));sfnt.searchRange=16*highestPowerOf2;sfnt.entrySelector=log2(highestPowerOf2);sfnt.rangeShift=sfnt.numTables*16-sfnt.searchRange;var recordFields=[];var tableFields=[];var offset=sfnt.sizeOf()+makeTableRecord().sizeOf()*sfnt.numTables;while(offset%4!==0){offset+=1;tableFields.push({name:"padding",type:"BYTE",value:0})}for(var i=0;i<tables.length;i+=1){var t=tables[i];assert(t.tableName.length===4,"Table name"+t.tableName+" is invalid.");var tableLength=t.sizeOf();var tableRecord=makeTableRecord(t.tableName,computeCheckSum(t.encode()),offset,tableLength);recordFields.push({name:tableRecord.tag+" Table Record",type:"RECORD",value:tableRecord});tableFields.push({name:t.tableName+" table",type:"RECORD",value:t});offset+=tableLength;assert(!isNaN(offset),"Something went wrong calculating the offset.");while(offset%4!==0){offset+=1;tableFields.push({name:"padding",type:"BYTE",value:0})}}recordFields.sort(function(r1,r2){if(r1.value.tag>r2.value.tag){return 1}else{return-1}});sfnt.fields=sfnt.fields.concat(recordFields);sfnt.fields=sfnt.fields.concat(tableFields);return sfnt}function metricsForChar(font,chars,notFoundMetrics){for(var i=0;i<chars.length;i+=1){var glyphIndex=font.charToGlyphIndex(chars[i]);if(glyphIndex>0){var glyph=font.glyphs.get(glyphIndex);return glyph.getMetrics()}}return notFoundMetrics}function average(vs){var sum=0;for(var i=0;i<vs.length;i+=1){sum+=vs[i]}return sum/vs.length}function fontToSfntTable(font){var xMins=[];var yMins=[];var xMaxs=[];var yMaxs=[];var advanceWidths=[];var leftSideBearings=[];var rightSideBearings=[];var firstCharIndex;var lastCharIndex=0;var ulUnicodeRange1=0;var ulUnicodeRange2=0;var ulUnicodeRange3=0;var ulUnicodeRange4=0;for(var i=0;i<font.glyphs.length;i+=1){var glyph=font.glyphs.get(i);var unicode=glyph.unicode|0;if(typeof glyph.advanceWidth==="undefined"){throw new Error("Glyph "+glyph.name+" ("+i+"): advanceWidth is required.")}if(firstCharIndex>unicode||firstCharIndex===null){firstCharIndex=unicode}if(lastCharIndex<unicode){lastCharIndex=unicode}var position=os2.getUnicodeRange(unicode);if(position<32){ulUnicodeRange1|=1<<position}else if(position<64){ulUnicodeRange2|=1<<position-32}else if(position<96){ulUnicodeRange3|=1<<position-64}else if(position<123){ulUnicodeRange4|=1<<position-96}else{throw new Error("Unicode ranges bits > 123 are reserved for internal usage")}if(glyph.name===".notdef")continue;var metrics=glyph.getMetrics();xMins.push(metrics.xMin);yMins.push(metrics.yMin);xMaxs.push(metrics.xMax);yMaxs.push(metrics.yMax);leftSideBearings.push(metrics.leftSideBearing);rightSideBearings.push(metrics.rightSideBearing);advanceWidths.push(glyph.advanceWidth)}var globals={xMin:Math.min.apply(null,xMins),yMin:Math.min.apply(null,yMins),xMax:Math.max.apply(null,xMaxs),yMax:Math.max.apply(null,yMaxs),advanceWidthMax:Math.max.apply(null,advanceWidths),advanceWidthAvg:average(advanceWidths),minLeftSideBearing:Math.min.apply(null,leftSideBearings),maxLeftSideBearing:Math.max.apply(null,leftSideBearings),minRightSideBearing:Math.min.apply(null,rightSideBearings)};globals.ascender=font.ascender;globals.descender=font.descender;var headTable=head.make({flags:3,unitsPerEm:font.unitsPerEm,xMin:globals.xMin,yMin:globals.yMin,xMax:globals.xMax,yMax:globals.yMax,lowestRecPPEM:3});var hheaTable=hhea.make({ascender:globals.ascender,descender:globals.descender,advanceWidthMax:globals.advanceWidthMax,minLeftSideBearing:globals.minLeftSideBearing,minRightSideBearing:globals.minRightSideBearing,xMaxExtent:globals.maxLeftSideBearing+(globals.xMax-globals.xMin),numberOfHMetrics:font.glyphs.length});var maxpTable=maxp.make(font.glyphs.length);var os2Table=os2.make({xAvgCharWidth:Math.round(globals.advanceWidthAvg),usWeightClass:500,usWidthClass:5,usFirstCharIndex:firstCharIndex,usLastCharIndex:lastCharIndex,ulUnicodeRange1:ulUnicodeRange1,ulUnicodeRange2:ulUnicodeRange2,ulUnicodeRange3:ulUnicodeRange3,ulUnicodeRange4:ulUnicodeRange4,fsSelection:64,sTypoAscender:globals.ascender,sTypoDescender:globals.descender,sTypoLineGap:0,usWinAscent:globals.yMax,usWinDescent:Math.abs(globals.yMin),ulCodePageRange1:1,sxHeight:metricsForChar(font,"xyvw",{yMax:Math.round(globals.ascender/2)}).yMax,sCapHeight:metricsForChar(font,"HIKLEFJMNTZBDPRAGOQSUVWXY",globals).yMax,usDefaultChar:font.hasChar(" ")?32:0,usBreakChar:font.hasChar(" ")?32:0});var hmtxTable=hmtx.make(font.glyphs);var cmapTable=cmap.make(font.glyphs);var englishFamilyName=font.getEnglishName("fontFamily");var englishStyleName=font.getEnglishName("fontSubfamily");var englishFullName=englishFamilyName+" "+englishStyleName;var postScriptName=font.getEnglishName("postScriptName");if(!postScriptName){postScriptName=englishFamilyName.replace(/\s/g,"")+"-"+englishStyleName}var names={};for(var n in font.names){names[n]=font.names[n]}if(!names.uniqueID){names.uniqueID={en:font.getEnglishName("manufacturer")+":"+englishFullName}}if(!names.postScriptName){names.postScriptName={en:postScriptName}}if(!names.preferredFamily){names.preferredFamily=font.names.fontFamily}if(!names.preferredSubfamily){names.preferredSubfamily=font.names.fontSubfamily}var languageTags=[];var nameTable=makeNameTable(names,languageTags);var ltagTable=languageTags.length>0?ltag.make(languageTags):undefined;var postTable=post.make();var cffTable=cff.make(font.glyphs,{version:font.getEnglishName("version"),fullName:englishFullName,familyName:englishFamilyName,weightName:englishStyleName,postScriptName:postScriptName,unitsPerEm:font.unitsPerEm,fontBBox:[0,globals.yMin,globals.ascender,globals.advanceWidthMax]});var tables=[headTable,hheaTable,maxpTable,os2Table,nameTable,cmapTable,postTable,cffTable,hmtxTable];if(ltagTable){tables.push(ltagTable)}var sfntTable=makeSfntTable(tables);var bytes=sfntTable.encode();var checkSum=computeCheckSum(bytes);var tableFields=sfntTable.fields;var checkSumAdjusted=false;for(i=0;i<tableFields.length;i+=1){if(tableFields[i].name==="head table"){tableFields[i].value.checkSumAdjustment=2981146554-checkSum;checkSumAdjusted=true;break}}if(!checkSumAdjusted){throw new Error("Could not find head table with checkSum to adjust.")}return sfntTable}var LIMIT16=32768;var LIMIT32=2147483648;var opentype_decode={};var encode={};var sizeOf={};function constant(v){return function(){return v}}encode.BYTE=function(v){assert(v>=0&&v<=255,"Byte value should be between 0 and 255.");return[v]};sizeOf.BYTE=constant(1);encode.CHAR=function(v){return[v.charCodeAt(0)]};sizeOf.CHAR=constant(1);encode.CHARARRAY=function(v){var b=[];for(var i=0;i<v.length;i+=1){b.push(v.charCodeAt(i))}return b};sizeOf.CHARARRAY=function(v){return v.length};encode.USHORT=function(v){return[v>>8&255,v&255]};sizeOf.USHORT=constant(2);encode.SHORT=function(v){if(v>=LIMIT16){v=-(2*LIMIT16-v)}return[v>>8&255,v&255]};sizeOf.SHORT=constant(2);encode.UINT24=function(v){return[v>>16&255,v>>8&255,v&255]};sizeOf.UINT24=constant(3);encode.ULONG=function(v){return[v>>24&255,v>>16&255,v>>8&255,v&255]};sizeOf.ULONG=constant(4);encode.LONG=function(v){if(v>=LIMIT32){v=-(2*LIMIT32-v)}return[v>>24&255,v>>16&255,v>>8&255,v&255]};sizeOf.LONG=constant(4);encode.FIXED=encode.ULONG;sizeOf.FIXED=sizeOf.ULONG;encode.FWORD=encode.SHORT;sizeOf.FWORD=sizeOf.SHORT;encode.UFWORD=encode.USHORT;sizeOf.UFWORD=sizeOf.USHORT;encode.LONGDATETIME=function(){return[0,0,0,0,0,0,0,0]};sizeOf.LONGDATETIME=constant(8);encode.TAG=function(v){assert(v.length===4,"Tag should be exactly 4 ASCII characters.");return[v.charCodeAt(0),v.charCodeAt(1),v.charCodeAt(2),v.charCodeAt(3)]};sizeOf.TAG=constant(4);encode.Card8=encode.BYTE;sizeOf.Card8=sizeOf.BYTE;encode.Card16=encode.USHORT;sizeOf.Card16=sizeOf.USHORT;encode.OffSize=encode.BYTE;sizeOf.OffSize=sizeOf.BYTE;encode.SID=encode.USHORT;sizeOf.SID=sizeOf.USHORT;encode.NUMBER=function(v){if(v>=-107&&v<=107){return[v+139]}else if(v>=108&&v<=1131){v=v-108;return[(v>>8)+247,v&255]}else if(v>=-1131&&v<=-108){v=-v-108;return[(v>>8)+251,v&255]}else if(v>=-32768&&v<=32767){return encode.NUMBER16(v)}else{return encode.NUMBER32(v)}};sizeOf.NUMBER=function(v){return encode.NUMBER(v).length};encode.NUMBER16=function(v){return[28,v>>8&255,v&255]};sizeOf.NUMBER16=constant(3);encode.NUMBER32=function(v){return[29,v>>24&255,v>>16&255,v>>8&255,v&255]};sizeOf.NUMBER32=constant(5);encode.REAL=function(v){var value=v.toString();var m=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);if(m){var epsilon=parseFloat("1e"+((m[2]?+m[2]:0)+m[1].length));value=(Math.round(v*epsilon)/epsilon).toString()}var nibbles="";var i;var ii;for(i=0,ii=value.length;i<ii;i+=1){var c=value[i];if(c==="e"){nibbles+=value[++i]==="-"?"c":"b"}else if(c==="."){nibbles+="a"}else if(c==="-"){nibbles+="e"}else{nibbles+=c}}nibbles+=nibbles.length&1?"f":"ff";var out=[30];for(i=0,ii=nibbles.length;i<ii;i+=2){out.push(parseInt(nibbles.substr(i,2),16))}return out};sizeOf.REAL=function(v){return encode.REAL(v).length};encode.NAME=encode.CHARARRAY;sizeOf.NAME=sizeOf.CHARARRAY;encode.STRING=encode.CHARARRAY;sizeOf.STRING=sizeOf.CHARARRAY;opentype_decode.UTF16=function(data,offset,numBytes){var codePoints=[];var numChars=numBytes/2;for(var j=0;j<numChars;j++,offset+=2){codePoints[j]=data.getUint16(offset)}return String.fromCharCode.apply(null,codePoints)};encode.UTF16=function(v){var b=[];for(var i=0;i<v.length;i+=1){var codepoint=v.charCodeAt(i);b.push(codepoint>>8&255);b.push(codepoint&255)}return b};sizeOf.UTF16=function(v){return v.length*2};var eightBitMacEncodings={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø"+"¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ"+"јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø"+"ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ä¹²É³ÖÜ΅àâä΄¨çéèêë£™îï•½‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ"+"άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ"+"ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆćéŹźĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ"+"ņŃ¬√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›ﬁﬂ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};opentype_decode.MACSTRING=function(dataView,offset,dataLength,encoding){var table=eightBitMacEncodings[encoding];if(table===undefined){return undefined}var result="";for(var i=0;i<dataLength;i++){var c=dataView.getUint8(offset+i);if(c<=127){result+=String.fromCharCode(c)}else{result+=table[c&127]}}return result};var macEncodingTableCache=typeof WeakMap==="function"&&new WeakMap;var macEncodingCacheKeys;var getMacEncodingTable=function(encoding){if(!macEncodingCacheKeys){macEncodingCacheKeys={};for(var e in eightBitMacEncodings){macEncodingCacheKeys[e]=new String(e)}}var cacheKey=macEncodingCacheKeys[encoding];if(cacheKey===undefined){return undefined}if(macEncodingTableCache){var cachedTable=macEncodingTableCache.get(cacheKey);if(cachedTable!==undefined){return cachedTable}}var decodingTable=eightBitMacEncodings[encoding];if(decodingTable===undefined){return undefined}var encodingTable={};for(var i=0;i<decodingTable.length;i++){encodingTable[decodingTable.charCodeAt(i)]=i+128}if(macEncodingTableCache){macEncodingTableCache.set(cacheKey,encodingTable)}return encodingTable};encode.MACSTRING=function(str,encoding){var table=getMacEncodingTable(encoding);if(table===undefined){return undefined}var result=[];for(var i=0;i<str.length;i++){var c=str.charCodeAt(i);if(c>=128){c=table[c];if(c===undefined){return undefined}}result.push(c)}return result};sizeOf.MACSTRING=function(str,encoding){var b=encode.MACSTRING(str,encoding);if(b!==undefined){return b.length}else{return 0}};encode.INDEX=function(l){var i;var offset=1;var offsets=[offset];var data=[];var dataSize=0;for(i=0;i<l.length;i+=1){var v=encode.OBJECT(l[i]);Array.prototype.push.apply(data,v);dataSize+=v.length;offset+=v.length;offsets.push(offset)}if(data.length===0){return[0,0]}var encodedOffsets=[];var offSize=1+Math.floor(Math.log(dataSize)/Math.log(2))/8|0;var offsetEncoder=[undefined,encode.BYTE,encode.USHORT,encode.UINT24,encode.ULONG][offSize];for(i=0;i<offsets.length;i+=1){var encodedOffset=offsetEncoder(offsets[i]);Array.prototype.push.apply(encodedOffsets,encodedOffset)}return Array.prototype.concat(encode.Card16(l.length),encode.OffSize(offSize),encodedOffsets,data)};sizeOf.INDEX=function(v){return encode.INDEX(v).length};encode.DICT=function(m){var d=[];var keys=Object.keys(m);var length=keys.length;for(var i=0;i<length;i+=1){var k=parseInt(keys[i],0);var v=m[k];d=d.concat(encode.OPERAND(v.value,v.type));d=d.concat(encode.OPERATOR(k))}return d};sizeOf.DICT=function(m){return encode.DICT(m).length};encode.OPERATOR=function(v){if(v<1200){return[v]}else{return[12,v-1200]}};encode.OPERAND=function(v,type){var d=[];if(Array.isArray(type)){for(var i=0;i<type.length;i+=1){assert(v.length===type.length,"Not enough arguments given for type"+type);d=d.concat(encode.OPERAND(v[i],type[i]))}}else{if(type==="SID"){d=d.concat(encode.NUMBER(v))}else if(type==="offset"){d=d.concat(encode.NUMBER32(v))}else if(type==="number"){d=d.concat(encode.NUMBER(v))}else if(type==="real"){d=d.concat(encode.REAL(v))}else{throw new Error("Unknown operand type "+type)}}return d};encode.OP=encode.BYTE;sizeOf.OP=sizeOf.BYTE;var wmm=typeof WeakMap==="function"&&new WeakMap;encode.CHARSTRING=function(ops){if(wmm){var cachedValue=wmm.get(ops);if(cachedValue!==undefined){return cachedValue}}var d=[];var length=ops.length;for(var i=0;i<length;i+=1){var op=ops[i];d=d.concat(encode[op.type](op.value))}if(wmm){wmm.set(ops,d)}return d};sizeOf.CHARSTRING=function(ops){return encode.CHARSTRING(ops).length};encode.OBJECT=function(v){var encodingFunction=encode[v.type];assert(encodingFunction!==undefined,"No encoding function for type "+v.type);return encodingFunction(v.value)};sizeOf.OBJECT=function(v){var sizeOfFunction=sizeOf[v.type];assert(sizeOfFunction!==undefined,"No sizeOf function for type "+v.type);return sizeOfFunction(v.value)};encode.TABLE=function(table){var d=[];var length=table.fields.length;var subtables=[];var subtableOffsets=[];var i;for(i=0;i<length;i+=1){var field=table.fields[i];var encodingFunction=encode[field.type];assert(encodingFunction!==undefined,"No encoding function for field type "+field.type+" ("+field.name+")");var value=table[field.name];if(value===undefined){value=field.value}var bytes=encodingFunction(value);if(field.type==="TABLE"){subtableOffsets.push(d.length);d=d.concat([0,0]);subtables.push(bytes)}else{d=d.concat(bytes)}}for(i=0;i<subtables.length;i+=1){var o=subtableOffsets[i];var offset=d.length;assert(offset<65536,"Table "+table.tableName+" too big.");d[o]=offset>>8;d[o+1]=offset&255;d=d.concat(subtables[i])}return d};sizeOf.TABLE=function(table){var numBytes=0;var length=table.fields.length;for(var i=0;i<length;i+=1){var field=table.fields[i];var sizeOfFunction=sizeOf[field.type];assert(sizeOfFunction!==undefined,"No sizeOf function for field type "+field.type+" ("+field.name+")");var value=table[field.name];if(value===undefined){value=field.value}numBytes+=sizeOfFunction(value);if(field.type==="TABLE"){numBytes+=2}}return numBytes};encode.RECORD=encode.TABLE;sizeOf.RECORD=sizeOf.TABLE;encode.LITERAL=function(v){return v};sizeOf.LITERAL=function(v){return v.length};opentype_isBrowser=function(){return typeof window!=="undefined"};opentype_isNode=function(){return typeof window==="undefined"};opentype_nodeBufferToArrayBuffer=function(buffer){var ab=new ArrayBuffer(buffer.length);var view=new Uint8Array(ab);for(var i=0;i<buffer.length;++i){view[i]=buffer[i]}return ab};opentype_arrayBufferToNodeBuffer=function(ab){var buffer=new Buffer(ab.byteLength);var view=new Uint8Array(ab);for(var i=0;i<buffer.length;++i){buffer[i]=view[i]}return buffer};opentype_checkArgument=function(expression,message){if(!expression){throw message}};if(typeof Float32Array!="undefined"){glMatrixArrayType=Float32Array}else if(typeof WebGLFloatArray!="undefined"){glMatrixArrayType=WebGLFloatArray}else{glMatrixArrayType=Array}var vec3={};vec3.create=function(vec){var dest=new glMatrixArrayType(3);if(vec){dest[0]=vec[0];dest[1]=vec[1];dest[2]=vec[2]}return dest};vec3.set=function(vec,dest){dest[0]=vec[0];dest[1]=vec[1];dest[2]=vec[2];return dest};vec3.add=function(vec,vec2,dest){if(!dest||vec==dest){vec[0]+=vec2[0];vec[1]+=vec2[1];vec[2]+=vec2[2];return vec}dest[0]=vec[0]+vec2[0];dest[1]=vec[1]+vec2[1];dest[2]=vec[2]+vec2[2];return dest};vec3.subtract=function(vec,vec2,dest){if(!dest||vec==dest){vec[0]-=vec2[0];vec[1]-=vec2[1];vec[2]-=vec2[2];return vec}dest[0]=vec[0]-vec2[0];dest[1]=vec[1]-vec2[1];dest[2]=vec[2]-vec2[2];return dest};vec3.negate=function(vec,dest){if(!dest){dest=vec}dest[0]=-vec[0];dest[1]=-vec[1];dest[2]=-vec[2];return dest};vec3.scale=function(vec,val,dest){if(!dest||vec==dest){vec[0]*=val;vec[1]*=val;vec[2]*=val;return vec}dest[0]=vec[0]*val;dest[1]=vec[1]*val;dest[2]=vec[2]*val;return dest};vec3.normalize=function(vec,dest){if(!dest){dest=vec}var x=vec[0],y=vec[1],z=vec[2];var len=Math.sqrt(x*x+y*y+z*z);if(!len){dest[0]=0;dest[1]=0;dest[2]=0;return dest}else if(len==1){dest[0]=x;dest[1]=y;dest[2]=z;return dest}len=1/len;dest[0]=x*len;dest[1]=y*len;dest[2]=z*len;return dest};vec3.cross=function(vec,vec2,dest){if(!dest){dest=vec}var x=vec[0],y=vec[1],z=vec[2];var x2=vec2[0],y2=vec2[1],z2=vec2[2];dest[0]=y*z2-z*y2;dest[1]=z*x2-x*z2;dest[2]=x*y2-y*x2;return dest};vec3.length=function(vec){var x=vec[0],y=vec[1],z=vec[2];return Math.sqrt(x*x+y*y+z*z)};vec3.dot=function(vec,vec2){return vec[0]*vec2[0]+vec[1]*vec2[1]+vec[2]*vec2[2]};vec3.direction=function(vec,vec2,dest){if(!dest){dest=vec}var x=vec[0]-vec2[0];var y=vec[1]-vec2[1];var z=vec[2]-vec2[2];var len=Math.sqrt(x*x+y*y+z*z);if(!len){dest[0]=0;dest[1]=0;dest[2]=0;return dest}len=1/len;dest[0]=x*len;dest[1]=y*len;dest[2]=z*len;return dest};vec3.lerp=function(vec,vec2,lerp,dest){if(!dest){dest=vec}dest[0]=vec[0]+lerp*(vec2[0]-vec[0]);dest[1]=vec[1]+lerp*(vec2[1]-vec[1]);dest[2]=vec[2]+lerp*(vec2[2]-vec[2]);return dest};vec3.str=function(vec){return"["+vec[0]+", "+vec[1]+", "+vec[2]+"]"};var mat3={};mat3.create=function(mat){var dest=new glMatrixArrayType(9);if(mat){dest[0]=mat[0];dest[1]=mat[1];dest[2]=mat[2];dest[3]=mat[3];dest[4]=mat[4];dest[5]=mat[5];dest[6]=mat[6];dest[7]=mat[7];dest[8]=mat[8]}return dest};mat3.set=function(mat,dest){dest[0]=mat[0];dest[1]=mat[1];dest[2]=mat[2];dest[3]=mat[3];dest[4]=mat[4];dest[5]=mat[5];dest[6]=mat[6];dest[7]=mat[7];dest[8]=mat[8];return dest};mat3.identity=function(dest){dest[0]=1;dest[1]=0;dest[2]=0;dest[3]=0;dest[4]=1;dest[5]=0;dest[6]=0;dest[7]=0;dest[8]=1;return dest};mat3.transpose=function(mat,dest){if(!dest||mat==dest){var a01=mat[1],a02=mat[2];var a12=mat[5];mat[1]=mat[3];mat[2]=mat[6];mat[3]=a01;mat[5]=mat[7];mat[6]=a02;mat[7]=a12;return mat}dest[0]=mat[0];dest[1]=mat[3];dest[2]=mat[6];dest[3]=mat[1];dest[4]=mat[4];dest[5]=mat[7];dest[6]=mat[2];dest[7]=mat[5];dest[8]=mat[8];return dest};mat3.toMat4=function(mat,dest){if(!dest){dest=mat4.create()}dest[0]=mat[0];dest[1]=mat[1];dest[2]=mat[2];dest[3]=0;dest[4]=mat[3];dest[5]=mat[4];dest[6]=mat[5];dest[7]=0;dest[8]=mat[6];dest[9]=mat[7];dest[10]=mat[8];dest[11]=0;dest[12]=0;dest[13]=0;dest[14]=0;dest[15]=1;return dest};mat3.str=function(mat){return"["+mat[0]+", "+mat[1]+", "+mat[2]+", "+mat[3]+", "+mat[4]+", "+mat[5]+", "+mat[6]+", "+mat[7]+", "+mat[8]+"]"};var mat4={};mat4.create=function(mat){var dest=new glMatrixArrayType(16);if(mat){dest[0]=mat[0];dest[1]=mat[1];dest[2]=mat[2];dest[3]=mat[3];dest[4]=mat[4];dest[5]=mat[5];dest[6]=mat[6];dest[7]=mat[7];dest[8]=mat[8];dest[9]=mat[9];dest[10]=mat[10];dest[11]=mat[11];dest[12]=mat[12];dest[13]=mat[13];dest[14]=mat[14];dest[15]=mat[15]}return dest};mat4.set=function(mat,dest){dest[0]=mat[0];dest[1]=mat[1];dest[2]=mat[2];dest[3]=mat[3];dest[4]=mat[4];dest[5]=mat[5];dest[6]=mat[6];dest[7]=mat[7];dest[8]=mat[8];dest[9]=mat[9];dest[10]=mat[10];dest[11]=mat[11];dest[12]=mat[12];dest[13]=mat[13];dest[14]=mat[14];dest[15]=mat[15];return dest};
  mat4.identity=function(dest){dest[0]=1;dest[1]=0;dest[2]=0;dest[3]=0;dest[4]=0;dest[5]=1;dest[6]=0;dest[7]=0;dest[8]=0;dest[9]=0;dest[10]=1;dest[11]=0;dest[12]=0;dest[13]=0;dest[14]=0;dest[15]=1;return dest};mat4.transpose=function(mat,dest){if(!dest||mat==dest){var a01=mat[1],a02=mat[2],a03=mat[3];var a12=mat[6],a13=mat[7];var a23=mat[11];mat[1]=mat[4];mat[2]=mat[8];mat[3]=mat[12];mat[4]=a01;mat[6]=mat[9];mat[7]=mat[13];mat[8]=a02;mat[9]=a12;mat[11]=mat[14];mat[12]=a03;mat[13]=a13;mat[14]=a23;return mat}dest[0]=mat[0];dest[1]=mat[4];dest[2]=mat[8];dest[3]=mat[12];dest[4]=mat[1];dest[5]=mat[5];dest[6]=mat[9];dest[7]=mat[13];dest[8]=mat[2];dest[9]=mat[6];dest[10]=mat[10];dest[11]=mat[14];dest[12]=mat[3];dest[13]=mat[7];dest[14]=mat[11];dest[15]=mat[15];return dest};mat4.determinant=function(mat){var a00=mat[0],a01=mat[1],a02=mat[2],a03=mat[3];var a10=mat[4],a11=mat[5],a12=mat[6],a13=mat[7];var a20=mat[8],a21=mat[9],a22=mat[10],a23=mat[11];var a30=mat[12],a31=mat[13],a32=mat[14],a33=mat[15];return a30*a21*a12*a03-a20*a31*a12*a03-a30*a11*a22*a03+a10*a31*a22*a03+a20*a11*a32*a03-a10*a21*a32*a03-a30*a21*a02*a13+a20*a31*a02*a13+a30*a01*a22*a13-a00*a31*a22*a13-a20*a01*a32*a13+a00*a21*a32*a13+a30*a11*a02*a23-a10*a31*a02*a23-a30*a01*a12*a23+a00*a31*a12*a23+a10*a01*a32*a23-a00*a11*a32*a23-a20*a11*a02*a33+a10*a21*a02*a33+a20*a01*a12*a33-a00*a21*a12*a33-a10*a01*a22*a33+a00*a11*a22*a33};mat4.inverse=function(mat,dest){if(!dest){dest=mat}var a00=mat[0],a01=mat[1],a02=mat[2],a03=mat[3];var a10=mat[4],a11=mat[5],a12=mat[6],a13=mat[7];var a20=mat[8],a21=mat[9],a22=mat[10],a23=mat[11];var a30=mat[12],a31=mat[13],a32=mat[14],a33=mat[15];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var invDet=1/(b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06);dest[0]=(a11*b11-a12*b10+a13*b09)*invDet;dest[1]=(-a01*b11+a02*b10-a03*b09)*invDet;dest[2]=(a31*b05-a32*b04+a33*b03)*invDet;dest[3]=(-a21*b05+a22*b04-a23*b03)*invDet;dest[4]=(-a10*b11+a12*b08-a13*b07)*invDet;dest[5]=(a00*b11-a02*b08+a03*b07)*invDet;dest[6]=(-a30*b05+a32*b02-a33*b01)*invDet;dest[7]=(a20*b05-a22*b02+a23*b01)*invDet;dest[8]=(a10*b10-a11*b08+a13*b06)*invDet;dest[9]=(-a00*b10+a01*b08-a03*b06)*invDet;dest[10]=(a30*b04-a31*b02+a33*b00)*invDet;dest[11]=(-a20*b04+a21*b02-a23*b00)*invDet;dest[12]=(-a10*b09+a11*b07-a12*b06)*invDet;dest[13]=(a00*b09-a01*b07+a02*b06)*invDet;dest[14]=(-a30*b03+a31*b01-a32*b00)*invDet;dest[15]=(a20*b03-a21*b01+a22*b00)*invDet;return dest};mat4.toRotationMat=function(mat,dest){if(!dest){dest=mat4.create()}dest[0]=mat[0];dest[1]=mat[1];dest[2]=mat[2];dest[3]=mat[3];dest[4]=mat[4];dest[5]=mat[5];dest[6]=mat[6];dest[7]=mat[7];dest[8]=mat[8];dest[9]=mat[9];dest[10]=mat[10];dest[11]=mat[11];dest[12]=0;dest[13]=0;dest[14]=0;dest[15]=1;return dest};mat4.toMat3=function(mat,dest){if(!dest){dest=mat3.create()}dest[0]=mat[0];dest[1]=mat[1];dest[2]=mat[2];dest[3]=mat[4];dest[4]=mat[5];dest[5]=mat[6];dest[6]=mat[8];dest[7]=mat[9];dest[8]=mat[10];return dest};mat4.toInverseMat3=function(mat,dest){var a00=mat[0],a01=mat[1],a02=mat[2];var a10=mat[4],a11=mat[5],a12=mat[6];var a20=mat[8],a21=mat[9],a22=mat[10];var b01=a22*a11-a12*a21;var b11=-a22*a10+a12*a20;var b21=a21*a10-a11*a20;var d=a00*b01+a01*b11+a02*b21;if(!d){return null}var id=1/d;if(!dest){dest=mat3.create()}dest[0]=b01*id;dest[1]=(-a22*a01+a02*a21)*id;dest[2]=(a12*a01-a02*a11)*id;dest[3]=b11*id;dest[4]=(a22*a00-a02*a20)*id;dest[5]=(-a12*a00+a02*a10)*id;dest[6]=b21*id;dest[7]=(-a21*a00+a01*a20)*id;dest[8]=(a11*a00-a01*a10)*id;return dest};mat4.multiply=function(mat,mat2,dest){if(!dest){dest=mat}var a00=mat[0],a01=mat[1],a02=mat[2],a03=mat[3];var a10=mat[4],a11=mat[5],a12=mat[6],a13=mat[7];var a20=mat[8],a21=mat[9],a22=mat[10],a23=mat[11];var a30=mat[12],a31=mat[13],a32=mat[14],a33=mat[15];var b00=mat2[0],b01=mat2[1],b02=mat2[2],b03=mat2[3];var b10=mat2[4],b11=mat2[5],b12=mat2[6],b13=mat2[7];var b20=mat2[8],b21=mat2[9],b22=mat2[10],b23=mat2[11];var b30=mat2[12],b31=mat2[13],b32=mat2[14],b33=mat2[15];dest[0]=b00*a00+b01*a10+b02*a20+b03*a30;dest[1]=b00*a01+b01*a11+b02*a21+b03*a31;dest[2]=b00*a02+b01*a12+b02*a22+b03*a32;dest[3]=b00*a03+b01*a13+b02*a23+b03*a33;dest[4]=b10*a00+b11*a10+b12*a20+b13*a30;dest[5]=b10*a01+b11*a11+b12*a21+b13*a31;dest[6]=b10*a02+b11*a12+b12*a22+b13*a32;dest[7]=b10*a03+b11*a13+b12*a23+b13*a33;dest[8]=b20*a00+b21*a10+b22*a20+b23*a30;dest[9]=b20*a01+b21*a11+b22*a21+b23*a31;dest[10]=b20*a02+b21*a12+b22*a22+b23*a32;dest[11]=b20*a03+b21*a13+b22*a23+b23*a33;dest[12]=b30*a00+b31*a10+b32*a20+b33*a30;dest[13]=b30*a01+b31*a11+b32*a21+b33*a31;dest[14]=b30*a02+b31*a12+b32*a22+b33*a32;dest[15]=b30*a03+b31*a13+b32*a23+b33*a33;return dest};mat4.multiplyVec3=function(mat,vec,dest){if(!dest){dest=vec}var x=vec[0],y=vec[1],z=vec[2];dest[0]=mat[0]*x+mat[4]*y+mat[8]*z+mat[12];dest[1]=mat[1]*x+mat[5]*y+mat[9]*z+mat[13];dest[2]=mat[2]*x+mat[6]*y+mat[10]*z+mat[14];return dest};mat4.multiplyVec4=function(mat,vec,dest){if(!dest){dest=vec}var x=vec[0],y=vec[1],z=vec[2],w=vec[3];dest[0]=mat[0]*x+mat[4]*y+mat[8]*z+mat[12]*w;dest[1]=mat[1]*x+mat[5]*y+mat[9]*z+mat[13]*w;dest[2]=mat[2]*x+mat[6]*y+mat[10]*z+mat[14]*w;dest[3]=mat[3]*x+mat[7]*y+mat[11]*z+mat[15]*w;return dest};mat4.translate=function(mat,vec,dest){var x=vec[0],y=vec[1],z=vec[2];if(!dest||mat==dest){mat[12]=mat[0]*x+mat[4]*y+mat[8]*z+mat[12];mat[13]=mat[1]*x+mat[5]*y+mat[9]*z+mat[13];mat[14]=mat[2]*x+mat[6]*y+mat[10]*z+mat[14];mat[15]=mat[3]*x+mat[7]*y+mat[11]*z+mat[15];return mat}var a00=mat[0],a01=mat[1],a02=mat[2],a03=mat[3];var a10=mat[4],a11=mat[5],a12=mat[6],a13=mat[7];var a20=mat[8],a21=mat[9],a22=mat[10],a23=mat[11];dest[0]=a00;dest[1]=a01;dest[2]=a02;dest[3]=a03;dest[4]=a10;dest[5]=a11;dest[6]=a12;dest[7]=a13;dest[8]=a20;dest[9]=a21;dest[10]=a22;dest[11]=a23;dest[12]=a00*x+a10*y+a20*z+mat[12];dest[13]=a01*x+a11*y+a21*z+mat[13];dest[14]=a02*x+a12*y+a22*z+mat[14];dest[15]=a03*x+a13*y+a23*z+mat[15];return dest};mat4.scale=function(mat,vec,dest){var x=vec[0],y=vec[1],z=vec[2];if(!dest||mat==dest){mat[0]*=x;mat[1]*=x;mat[2]*=x;mat[3]*=x;mat[4]*=y;mat[5]*=y;mat[6]*=y;mat[7]*=y;mat[8]*=z;mat[9]*=z;mat[10]*=z;mat[11]*=z;return mat}dest[0]=mat[0]*x;dest[1]=mat[1]*x;dest[2]=mat[2]*x;dest[3]=mat[3]*x;dest[4]=mat[4]*y;dest[5]=mat[5]*y;dest[6]=mat[6]*y;dest[7]=mat[7]*y;dest[8]=mat[8]*z;dest[9]=mat[9]*z;dest[10]=mat[10]*z;dest[11]=mat[11]*z;dest[12]=mat[12];dest[13]=mat[13];dest[14]=mat[14];dest[15]=mat[15];return dest};mat4.rotate=function(mat,angle,axis,dest){var x=axis[0],y=axis[1],z=axis[2];var len=Math.sqrt(x*x+y*y+z*z);if(!len){return null}if(len!=1){len=1/len;x*=len;y*=len;z*=len}var s=Math.sin(angle);var c=Math.cos(angle);var t=1-c;var a00=mat[0],a01=mat[1],a02=mat[2],a03=mat[3];var a10=mat[4],a11=mat[5],a12=mat[6],a13=mat[7];var a20=mat[8],a21=mat[9],a22=mat[10],a23=mat[11];var b00=x*x*t+c,b01=y*x*t+z*s,b02=z*x*t-y*s;var b10=x*y*t-z*s,b11=y*y*t+c,b12=z*y*t+x*s;var b20=x*z*t+y*s,b21=y*z*t-x*s,b22=z*z*t+c;if(!dest){dest=mat}else if(mat!=dest){dest[12]=mat[12];dest[13]=mat[13];dest[14]=mat[14];dest[15]=mat[15]}dest[0]=a00*b00+a10*b01+a20*b02;dest[1]=a01*b00+a11*b01+a21*b02;dest[2]=a02*b00+a12*b01+a22*b02;dest[3]=a03*b00+a13*b01+a23*b02;dest[4]=a00*b10+a10*b11+a20*b12;dest[5]=a01*b10+a11*b11+a21*b12;dest[6]=a02*b10+a12*b11+a22*b12;dest[7]=a03*b10+a13*b11+a23*b12;dest[8]=a00*b20+a10*b21+a20*b22;dest[9]=a01*b20+a11*b21+a21*b22;dest[10]=a02*b20+a12*b21+a22*b22;dest[11]=a03*b20+a13*b21+a23*b22;return dest};mat4.rotateX=function(mat,angle,dest){var s=Math.sin(angle);var c=Math.cos(angle);var a10=mat[4],a11=mat[5],a12=mat[6],a13=mat[7];var a20=mat[8],a21=mat[9],a22=mat[10],a23=mat[11];if(!dest){dest=mat}else if(mat!=dest){dest[0]=mat[0];dest[1]=mat[1];dest[2]=mat[2];dest[3]=mat[3];dest[12]=mat[12];dest[13]=mat[13];dest[14]=mat[14];dest[15]=mat[15]}dest[4]=a10*c+a20*s;dest[5]=a11*c+a21*s;dest[6]=a12*c+a22*s;dest[7]=a13*c+a23*s;dest[8]=a10*-s+a20*c;dest[9]=a11*-s+a21*c;dest[10]=a12*-s+a22*c;dest[11]=a13*-s+a23*c;return dest};mat4.rotateY=function(mat,angle,dest){var s=Math.sin(angle);var c=Math.cos(angle);var a00=mat[0],a01=mat[1],a02=mat[2],a03=mat[3];var a20=mat[8],a21=mat[9],a22=mat[10],a23=mat[11];if(!dest){dest=mat}else if(mat!=dest){dest[4]=mat[4];dest[5]=mat[5];dest[6]=mat[6];dest[7]=mat[7];dest[12]=mat[12];dest[13]=mat[13];dest[14]=mat[14];dest[15]=mat[15]}dest[0]=a00*c+a20*-s;dest[1]=a01*c+a21*-s;dest[2]=a02*c+a22*-s;dest[3]=a03*c+a23*-s;dest[8]=a00*s+a20*c;dest[9]=a01*s+a21*c;dest[10]=a02*s+a22*c;dest[11]=a03*s+a23*c;return dest};mat4.rotateZ=function(mat,angle,dest){var s=Math.sin(angle);var c=Math.cos(angle);var a00=mat[0],a01=mat[1],a02=mat[2],a03=mat[3];var a10=mat[4],a11=mat[5],a12=mat[6],a13=mat[7];if(!dest){dest=mat}else if(mat!=dest){dest[8]=mat[8];dest[9]=mat[9];dest[10]=mat[10];dest[11]=mat[11];dest[12]=mat[12];dest[13]=mat[13];dest[14]=mat[14];dest[15]=mat[15]}dest[0]=a00*c+a10*s;dest[1]=a01*c+a11*s;dest[2]=a02*c+a12*s;dest[3]=a03*c+a13*s;dest[4]=a00*-s+a10*c;dest[5]=a01*-s+a11*c;dest[6]=a02*-s+a12*c;dest[7]=a03*-s+a13*c;return dest};mat4.frustum=function(left,right,bottom,top,near,far,dest){if(!dest){dest=mat4.create()}var rl=right-left;var tb=top-bottom;var fn=far-near;dest[0]=near*2/rl;dest[1]=0;dest[2]=0;dest[3]=0;dest[4]=0;dest[5]=near*2/tb;dest[6]=0;dest[7]=0;dest[8]=(right+left)/rl;dest[9]=(top+bottom)/tb;dest[10]=-(far+near)/fn;dest[11]=-1;dest[12]=0;dest[13]=0;dest[14]=-(far*near*2)/fn;dest[15]=0;return dest};mat4.perspective=function(fovy,aspect,near,far,dest){var top=near*Math.tan(fovy*Math.PI/360);var right=top*aspect;return mat4.frustum(-right,right,-top,top,near,far,dest)};mat4.ortho=function(left,right,bottom,top,near,far,dest){if(!dest){dest=mat4.create()}var rl=right-left;var tb=top-bottom;var fn=far-near;dest[0]=2/rl;dest[1]=0;dest[2]=0;dest[3]=0;dest[4]=0;dest[5]=2/tb;dest[6]=0;dest[7]=0;dest[8]=0;dest[9]=0;dest[10]=-2/fn;dest[11]=0;dest[12]=-(left+right)/rl;dest[13]=-(top+bottom)/tb;dest[14]=-(far+near)/fn;dest[15]=1;return dest};mat4.lookAt=function(eye,center,up,dest){if(!dest){dest=mat4.create()}var eyex=eye[0],eyey=eye[1],eyez=eye[2],upx=up[0],upy=up[1],upz=up[2],centerx=center[0],centery=center[1],centerz=center[2];if(eyex==centerx&&eyey==centery&&eyez==centerz){return mat4.identity(dest)}var z0,z1,z2,x0,x1,x2,y0,y1,y2,len;z0=eyex-center[0];z1=eyey-center[1];z2=eyez-center[2];len=1/Math.sqrt(z0*z0+z1*z1+z2*z2);z0*=len;z1*=len;z2*=len;x0=upy*z2-upz*z1;x1=upz*z0-upx*z2;x2=upx*z1-upy*z0;len=Math.sqrt(x0*x0+x1*x1+x2*x2);if(!len){x0=0;x1=0;x2=0}else{len=1/len;x0*=len;x1*=len;x2*=len}y0=z1*x2-z2*x1;y1=z2*x0-z0*x2;y2=z0*x1-z1*x0;len=Math.sqrt(y0*y0+y1*y1+y2*y2);if(!len){y0=0;y1=0;y2=0}else{len=1/len;y0*=len;y1*=len;y2*=len}dest[0]=x0;dest[1]=y0;dest[2]=z0;dest[3]=0;dest[4]=x1;dest[5]=y1;dest[6]=z1;dest[7]=0;dest[8]=x2;dest[9]=y2;dest[10]=z2;dest[11]=0;dest[12]=-(x0*eyex+x1*eyey+x2*eyez);dest[13]=-(y0*eyex+y1*eyey+y2*eyez);dest[14]=-(z0*eyex+z1*eyey+z2*eyez);dest[15]=1;return dest};mat4.str=function(mat){return"["+mat[0]+", "+mat[1]+", "+mat[2]+", "+mat[3]+", "+mat[4]+", "+mat[5]+", "+mat[6]+", "+mat[7]+", "+mat[8]+", "+mat[9]+", "+mat[10]+", "+mat[11]+", "+mat[12]+", "+mat[13]+", "+mat[14]+", "+mat[15]+"]"};quat4={};quat4.create=function(quat){var dest=new glMatrixArrayType(4);if(quat){dest[0]=quat[0];dest[1]=quat[1];dest[2]=quat[2];dest[3]=quat[3]}return dest};quat4.set=function(quat,dest){dest[0]=quat[0];dest[1]=quat[1];dest[2]=quat[2];dest[3]=quat[3];return dest};quat4.calculateW=function(quat,dest){var x=quat[0],y=quat[1],z=quat[2];if(!dest||quat==dest){quat[3]=-Math.sqrt(Math.abs(1-x*x-y*y-z*z));return quat}dest[0]=x;dest[1]=y;dest[2]=z;dest[3]=-Math.sqrt(Math.abs(1-x*x-y*y-z*z));return dest};quat4.inverse=function(quat,dest){if(!dest||quat==dest){quat[0]*=-1;quat[1]*=-1;quat[2]*=-1;return quat}dest[0]=-quat[0];dest[1]=-quat[1];dest[2]=-quat[2];dest[3]=quat[3];return dest};quat4.length=function(quat){var x=quat[0],y=quat[1],z=quat[2],w=quat[3];return Math.sqrt(x*x+y*y+z*z+w*w)};quat4.normalize=function(quat,dest){if(!dest){dest=quat}var x=quat[0],y=quat[1],z=quat[2],w=quat[3];var len=Math.sqrt(x*x+y*y+z*z+w*w);if(len==0){dest[0]=0;dest[1]=0;dest[2]=0;dest[3]=0;return dest}len=1/len;dest[0]=x*len;dest[1]=y*len;dest[2]=z*len;dest[3]=w*len;return dest};quat4.multiply=function(quat,quat2,dest){if(!dest){dest=quat}var qax=quat[0],qay=quat[1],qaz=quat[2],qaw=quat[3];var qbx=quat2[0],qby=quat2[1],qbz=quat2[2],qbw=quat2[3];dest[0]=qax*qbw+qaw*qbx+qay*qbz-qaz*qby;dest[1]=qay*qbw+qaw*qby+qaz*qbx-qax*qbz;dest[2]=qaz*qbw+qaw*qbz+qax*qby-qay*qbx;dest[3]=qaw*qbw-qax*qbx-qay*qby-qaz*qbz;return dest};quat4.multiplyVec3=function(quat,vec,dest){if(!dest){dest=vec}var x=vec[0],y=vec[1],z=vec[2];var qx=quat[0],qy=quat[1],qz=quat[2],qw=quat[3];var ix=qw*x+qy*z-qz*y;var iy=qw*y+qz*x-qx*z;var iz=qw*z+qx*y-qy*x;var iw=-qx*x-qy*y-qz*z;dest[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;dest[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;dest[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;return dest};quat4.toMat3=function(quat,dest){if(!dest){dest=mat3.create()}var x=quat[0],y=quat[1],z=quat[2],w=quat[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var xy=x*y2;var xz=x*z2;var yy=y*y2;var yz=y*z2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;dest[0]=1-(yy+zz);dest[1]=xy-wz;dest[2]=xz+wy;dest[3]=xy+wz;dest[4]=1-(xx+zz);dest[5]=yz-wx;dest[6]=xz-wy;dest[7]=yz+wx;dest[8]=1-(xx+yy);return dest};quat4.toMat4=function(quat,dest){if(!dest){dest=mat4.create()}var x=quat[0],y=quat[1],z=quat[2],w=quat[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var xy=x*y2;var xz=x*z2;var yy=y*y2;var yz=y*z2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;dest[0]=1-(yy+zz);dest[1]=xy-wz;dest[2]=xz+wy;dest[3]=0;dest[4]=xy+wz;dest[5]=1-(xx+zz);dest[6]=yz-wx;dest[7]=0;dest[8]=xz-wy;dest[9]=yz+wx;dest[10]=1-(xx+yy);dest[11]=0;dest[12]=0;dest[13]=0;dest[14]=0;dest[15]=1;return dest};quat4.slerp=function(quat,quat2,slerp,dest){if(!dest){dest=quat}var cosHalfTheta=quat[0]*quat2[0]+quat[1]*quat2[1]+quat[2]*quat2[2]+quat[3]*quat2[3];if(Math.abs(cosHalfTheta)>=1){if(dest!=quat){dest[0]=quat[0];dest[1]=quat[1];dest[2]=quat[2];dest[3]=quat[3]}return dest}var halfTheta=Math.acos(cosHalfTheta);var sinHalfTheta=Math.sqrt(1-cosHalfTheta*cosHalfTheta);if(Math.abs(sinHalfTheta)<.001){dest[0]=quat[0]*.5+quat2[0]*.5;dest[1]=quat[1]*.5+quat2[1]*.5;dest[2]=quat[2]*.5+quat2[2]*.5;dest[3]=quat[3]*.5+quat2[3]*.5;return dest}var ratioA=Math.sin((1-slerp)*halfTheta)/sinHalfTheta;var ratioB=Math.sin(slerp*halfTheta)/sinHalfTheta;dest[0]=quat[0]*ratioA+quat2[0]*ratioB;dest[1]=quat[1]*ratioA+quat2[1]*ratioB;dest[2]=quat[2]*ratioA+quat2[2]*ratioB;dest[3]=quat[3]*ratioA+quat2[3]*ratioB;return dest};quat4.str=function(quat){return"["+quat[0]+", "+quat[1]+", "+quat[2]+", "+quat[3]+"]"};WebGLUtils=function(){var makeFailHTML=function(msg){return""+'<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>'+'<td align="center">'+'<div style="display: table-cell; vertical-align: middle;">'+'<div style="">'+msg+"</div>"+"</div>"+"</td></tr></table>"};var GET_A_WEBGL_BROWSER=""+"This page requires a browser that supports WebGL.<br/>"+'<a href="http://get.webgl.org" target="_blank">Click here to upgrade your browser.</a>';var OTHER_PROBLEM=""+"It doesn't appear your computer can support WebGL.<br/>"+'<a href="http://get.webgl.org/troubleshooting/" target="_blank">Click here for more information.</a>';var setupWebGL=function(canvas,opt_attribs){function showLink(str){var container=canvas.parentNode;if(container){container.innerHTML=makeFailHTML(str)}}if(!window.WebGLRenderingContext){showLink(GET_A_WEBGL_BROWSER);return null}var context=create3DContext(canvas,opt_attribs);if(!context){showLink(OTHER_PROBLEM)}return context};var create3DContext=function(canvas,opt_attribs){var names=["webgl","experimental-webgl","webkit-3d","moz-webgl"];var context=null;for(var ii=0;ii<names.length;++ii){try{context=canvas.getContext(names[ii],opt_attribs)}catch(e){}if(context){break}}return context};return{create3DContext:create3DContext,setupWebGL:setupWebGL}}();window.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback,element){window.setTimeout(callback,1e3/60)}}();(function(){"use strict";var glowscript={version:"2.4"};var property={declare:function(proto,propertyMap){$.each(propertyMap,function(name,definition){if(definition===null||definition.value===undefined&&!definition.get)definition={value:definition};definition.name=name;var internal=definition.internal||name.substr(0,2)==="__";if(definition.enumerable===undefined)definition.enumerable=!internal;if(definition.type===undefined&&!definition.get&&!internal){var tp=typeof definition.value;if(tp==="number")definition.type=property.check_number;else if(tp==="string")definition.type=property.check_string;else if(definition.value instanceof attributeVector)definition.type=property.check_attributeVector;else if(definition.value instanceof attributeVectorPos)definition.type=property.check_attributeVectorPos;else if(definition.value instanceof attributeVectorAxis)definition.type=property.check_attributeVectorAxis;else if(definition.value instanceof attributeVectorSize)definition.type=property.check_attributeVectorSize;else if(definition.value instanceof attributeVectorUp)definition.type=property.check_attributeVectorUp;else if(definition.value instanceof vec)definition.type=property.check_vec}if(definition.readonly&&definition.set||definition.onchanged&&definition.set||definition.value!==undefined&&definition.get)throw new Error("Erroneous property definition '"+name+"'.");function readOnlyError(){throw new Error("Property '"+name+"' is read-only.")}if(definition.get){Object.defineProperty(proto,name,{enumerable:definition.enumerable,get:definition.get,set:definition.set||readOnlyError})}else{if(!definition.type&&!definition.onchanged)Object.defineProperty(proto,name,{enumerable:definition.enumerable,writable:!definition.readonly,value:definition.value});else{var internal="__"+name;var prop={enumerable:definition.enumerable,get:function(){return this[internal]}};if(definition.set)prop.set=definition.set;else if(definition.onchanged&&definition.type)prop.set=function(val){var old=this[internal];this[internal]=definition.type.call(this,val,definition);definition.onchanged.call(this,old)};else if(definition.onchanged)prop.set=function(val){var old=this[internal];this[internal]=val;definition.onchanged.call(this,old)};else if(definition.type)prop.set=function(val){this[internal]=definition.type.call(this,val,definition)};Object.defineProperty(proto,internal,{enumerable:false,writable:true,value:definition.value});Object.defineProperty(proto,name,prop)}}})},nullable_attributeVector:function nullable_attributeVector(v,def){if(v===null)return null;return property.check_attributeVector.call(this,v,def)},check_attributeVector:function check_attributeVector(v,def){if(!(v instanceof vec))throw new Error("Property '"+def.name+"' must be a vector.");return new attributeVector(this,v.x,v.y,v.z)},check_attributeVectorPos:function check_attributeVectorPos(v,def){if(!(v instanceof vec))throw new Error("Property '"+def.name+"' must be a vector.");return new attributeVectorPos(this,v.x,v.y,v.z)},check_attributeVectorAxis:function check_attributeVectorAxis(v,def){if(!(v instanceof vec))throw new Error("Property '"+def.name+"' must be a vector.");return new attributeVectorAxis(this,v.x,v.y,v.z)},check_attributeVectorSize:function check_attributeVectorSize(v,def){if(!(v instanceof vec))throw new Error("Property '"+def.name+"' must be a vector.");return new attributeVectorSize(this,v.x,v.y,v.z)},check_attributeVectorUp:function check_attributeVectorUp(v,def){if(!(v instanceof vec))throw new Error("Property '"+def.name+"' must be a vector.");return new attributeVectorUp(this,v.x,v.y,v.z)},check_vec:function check_vec(v,def){if(!v instanceof vec)throw new Error("Property '"+def.name+"' must be a vector.");return v},check_number:function check_number(v,def){return v},check_string:function check_string(v,def){return v}};var global=window;function Export(exports){for(var id in exports){glowscript[id]=exports[id];global[id]=exports[id]}}var module_exports={glowscript:glowscript,property:property,Export:Export};Export(module_exports)})();(function(){"use strict";function adjust_up(parent,oldaxis,newaxis){parent.__change();if(newaxis.mag2===0){if(parent.__oldaxis===undefined)parent.__oldaxis=oldaxis;return}if(parent.__oldaxis!==undefined){oldaxis=parent.__oldaxis;parent.__oldaxis=undefined}var angle=oldaxis.diff_angle(newaxis);if(angle>1e-6){var rotaxis,newup;if(Math.abs(angle-Math.PI)<1e-6)newup=parent.__up.multiply(-1);else{rotaxis=cross(oldaxis,newaxis);newup=parent.__up.rotate({angle:angle,axis:rotaxis})}parent.__up.__x=newup.x;parent.__up.__y=newup.y;parent.__up.__z=newup.z}}function adjust_axis(parent,oldup,newup){parent.__change();if(newup.mag2===0){if(parent.__oldup===undefined)parent.__oldup=oldup}if(parent.__oldup!==undefined){oldup=parent.__oldup;parent.__oldup=undefined}var angle=oldup.diff_angle(newup);if(angle>1e-6){var rotaxis,newaxis;if(Math.abs(angle-Math.PI)<1e-6)newaxis=parent.__axis.multiply(-1);else{rotaxis=cross(oldup,newup);newaxis=parent.__axis.rotate({angle:angle,axis:rotaxis})}parent.__axis.__x=newaxis.x;parent.__axis.__y=newaxis.y;parent.__axis.__z=newaxis.z}}function vec(x,y,z){if(!(this instanceof vec)){if(y===undefined)if(z===undefined)return new vec(x.x,x.y,x.z);return new vec(x,y,z)}if(z===undefined||y===undefined)throw new Error("vector() requires 3 arguments: x, y, and z.");this.x=x;this.y=y;this.z=z}function attributeVector(parent,x,y,z){this.__parent=parent;this.__x=x;this.__y=y;this.__z=z;if(parent){parent.__change()}}attributeVector.prototype=new vec(0,0,0);attributeVector.prototype.constructor=attributeVector;function attributeVectorPos(parent,x,y,z){this.__parent=parent;this.__x=x;this.__y=y;this.__z=z;if(parent){parent.__change();parent._pos_set=true;if(parent.__make_trail)parent.__update_trail(vec(x,y,z))}}attributeVectorPos.prototype=new vec(0,0,0);attributeVectorPos.prototype.constructor=attributeVectorPos;function attributeVectorAxis(parent,x,y,z){var oldaxis;this.__parent=parent;if(parent)oldaxis=norm(parent.__axis);this.__x=x;this.__y=y;this.__z=z;if(parent){if(parent.__sizing)parent.__size.__x=Math.sqrt(x*x+y*y+z*z);if(window.__adjustupaxis)adjust_up(parent,oldaxis,this);parent.__change()}}attributeVectorAxis.prototype=new vec(1,0,0);attributeVectorAxis.prototype.constructor=attributeVectorAxis;function attributeVectorSize(parent,x,y,z){this.__parent=parent;this.__x=x;this.__y=y;this.__z=z;if(parent){if(parent.__sizing){var v=parent.__axis.norm().multiply(x);parent.__axis.__x=v.x;parent.__axis.__y=v.y;parent.__axis.__z=v.z}parent.__change()}}attributeVectorSize.prototype=new vec(1,1,1);attributeVectorSize.prototype.constructor=attributeVectorSize;function attributeVectorUp(parent,x,y,z){var oldup;this.__parent=parent;if(parent)oldup=norm(parent.__up);this.__x=x;this.__y=y;this.__z=z;if(parent){if(window.__adjustupaxis)adjust_axis(parent,oldup,this);parent.__change()}}attributeVectorUp.prototype=new vec(0,1,0);attributeVectorUp.prototype.constructor=attributeVectorUp;Object.defineProperty(attributeVector.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVector.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){this.__x=value;this.__parent.__change()}});Object.defineProperty(attributeVector.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVector.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){this.__y=value;this.__parent.__change()}});Object.defineProperty(attributeVector.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVector.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){this.__z=value;this.__parent.__change()}});Object.defineProperty(attributeVectorPos.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorPos.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){this.__x=value;this.__parent.__change();this.__parent._pos_set=true;if(this.__parent.__make_trail)this.__parent.__update_trail(vec(this.__x,this.__y,this.__z))}});Object.defineProperty(attributeVectorPos.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorPos.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){this.__y=value;this.__parent.__change();this.__parent._pos_set=true;if(this.__parent.__make_trail)this.__parent.__update_trail(vec(this.__x,this.__y,this.__z))}});Object.defineProperty(attributeVectorPos.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorPos.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){this.__z=value;this.__parent.__change();this.__parent._pos_set=true;if(this.__parent.__make_trail)this.__parent.__update_trail(vec(this.__x,this.__y,this.__z))}});Object.defineProperty(attributeVectorAxis.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorAxis.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){var oldaxis=norm(this.__parent.__axis);this.__x=value;if(this.__parent.__sizing)this.__parent.__size.x=this.mag;adjust_up(this.__parent,oldaxis,this)}});Object.defineProperty(attributeVectorAxis.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorAxis.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){var oldaxis=norm(this.__parent.__axis);this.__y=value;if(this.__parent.__sizing)this.__parent.__size.x=this.mag;adjust_up(this.__parent,oldaxis,this)}});Object.defineProperty(attributeVectorAxis.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorAxis.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){var oldaxis=norm(this.__parent.__axis);this.__z=value;if(this.__parent.__sizing)this.__parent.__size.x=this.mag;adjust_up(this.__parent,oldaxis,this)}});Object.defineProperty(attributeVectorSize.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorSize.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){this.__x=value;if(this.__parent.__sizing){var v=this.__parent.__axis.norm().multiply(value);this.__parent.__axis.__x=v.x;this.__parent.__axis.__y=v.y;this.__parent.__axis.__z=v.z}this.__parent.__change()}});Object.defineProperty(attributeVectorSize.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorSize.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){this.__y=value;this.__parent.__change()}});Object.defineProperty(attributeVectorSize.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorSize.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){this.__z=value;this.__parent.__change()}});Object.defineProperty(attributeVectorUp.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorUp.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){var oldup=norm(this.__parent.__up);this.__x=value;adjust_axis(parent,oldup,this)}});Object.defineProperty(attributeVectorUp.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorUp.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){var oldup=norm(this.__parent.__up);this.__y=value;adjust_axis(parent,oldup,this)}});Object.defineProperty(attributeVectorUp.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorUp.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){var oldup=norm(this.__parent.__up);this.__z=value;adjust_axis(parent,oldup,this)}});vec.prototype.toString=function(){var input=[this.x,this.y,this.z];var output=[];var c,eloc,period,char,end;for(var i=0;i<3;i++){var c=input[i];if(c==0){output.push("0");continue}if(Math.abs(c)<1e-4)c=c.toExponential(5);else c=c.toPrecision(6);period=c.indexOf(".");if(period>=0){end=c.indexOf("e");if(end<0)end=c.length;char=end;while(true){char--;if(c.charAt(char)=="0")continue;if(char==period){output.push(c.slice(0,period).concat(c.slice(end,c.length)));break}if(end==c.length)output.push(c.slice(0,char+1));else output.push(c.slice(0,char+1).concat(c.slice(end,c.length)));break}}else output.push(c)}return"< "+output[0]+", "+output[1]+", "+output[2]+" >"};vec.prototype.add=function(v){return new vec(this.x+v.x,this.y+v.y,this.z+v.z)};vec.prototype.sub=function(v){return new vec(this.x-v.x,this.y-v.y,this.z-v.z)};vec.prototype.multiply=function(s){return new vec(this.x*s,this.y*s,this.z*s)};vec.prototype.divide=function(s){return new vec(this.x/s,this.y/s,this.z/s)};property.declare(vec.prototype,{mag:{get:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},set:function(value){var v=this.norm().multiply(value);this.x=v.x;this.y=v.y;this.z=v.z}},mag2:{get:function(){return this.x*this.x+this.y*this.y+this.z*this.z},set:function(value){var v=this.norm().multiply(Math.sqrt(value));this.x=v.x;this.y=v.y;this.z=v.z}},hat:{get:function(){return this.norm()},set:function(value){var v=value.hat.multiply(this.mag);this.x=v.x;this.y=v.y;this.z=v.z}}});vec.prototype.norm=function(){var r=this.mag;if(r==0)return new vec(0,0,0);return new vec(this.x/r,this.y/r,this.z/r)};vec.prototype.dot=function(v){return this.x*v.x+this.y*v.y+this.z*v.z};vec.prototype.equals=function(v){if(v===null)return false;return this.x===v.x&&this.y===v.y&&this.z===v.z};vec.prototype.proj=function(v){var B=norm(v);return B.multiply(this.dot(B))};vec.prototype.comp=function(v){return this.dot(norm(v))};vec.prototype.cross=function(v){return new vec(this.y*v.z-this.z*v.y,this.z*v.x-this.x*v.z,this.x*v.y-this.y*v.x)};vec.prototype.diff_angle=function(v){var a=this.norm().dot(v.norm());if(a>1)return 0;if(a<-1)return Math.PI;return Math.acos(a)};vec.prototype.rotate=function(args){var angle,axis;if(arguments.length==1){if(args!==null&&args!==undefined){if(typeof args==="number"){angle=args}else{angle=args.angle;axis=args.axis}}}else if(arguments.length==2){angle=arguments[0];axis=arguments[1]}if(angle===undefined)throw new Error("To rotate a vector you must specify an angle.");if(axis===undefined)axis=new vec(0,0,1);if(angle===0)return new vec(this.x,this.y,this.z);var axis=axis.norm();var parallel=axis.multiply(axis.dot(this));var perp=axis.cross(this);var pmag=perp.mag;perp=perp.norm();var y=perp.cross(axis);var rotated=y.multiply(pmag*Math.cos(angle)).add(perp.multiply(pmag*Math.sin(angle)));return parallel.add(rotated)};vec.random=function(){return new vec(-1+2*Math.random(),-1+2*Math.random(),-1+2*Math.random())};String.prototype["+"]=function(r){return this+r};Number.prototype["+"]=function(r){return this+r};Number.prototype["-"]=function(r){return this-r};Number.prototype["*"]=function(r){return r instanceof vec?r.multiply(this):r*this};Number.prototype["/"]=function(r){return this/r};Number.prototype["%"]=function(r){return this%r};Number.prototype["-u"]=function(){return-this};vec.prototype["+"]=vec.prototype.add;vec.prototype["-"]=vec.prototype.sub;vec.prototype["*"]=vec.prototype.multiply;vec.prototype["/"]=function(r){return this.divide(r)};vec.prototype["-u"]=function(){return new vec(-this.x,-this.y,-this.z)};var exports={vec:vec,attributeVector:attributeVector,
  attributeVectorPos:attributeVectorPos,attributeVectorAxis:attributeVectorAxis,attributeVectorSize:attributeVectorSize,attributeVectorUp:attributeVectorUp};Export(exports)})();(function vectorLibraryWrappers(){"use strict";function mag(A){return A.mag}function mag2(A){return A.mag2}function norm(A){return A.norm()}function hat(A){return A.hat}function dot(A,B){return A.dot(B)}function cross(A,B){return A.cross(B)}function proj(A,B){return A.proj(B)}function comp(A,B){return A.comp(B)}function diff_angle(A,B){return A.diff_angle(B)}function rotate(args){var angle,axis;var v=arguments[0];if(arguments.length==2){var args=arguments[1];if(args!==null&&args!==undefined){if(typeof args==="number"){angle=args}else{angle=args.angle;axis=args.axis}}}else if(arguments.length==3){angle=arguments[1];axis=arguments[2]}if(angle===undefined)throw new Error("To rotate a vector you must specify an angle.");if(axis===undefined)axis=new vec(0,0,1);return v.rotate({angle:angle,axis:axis})}var exports={mag:mag,mag2:mag2,norm:norm,hat:hat,dot:dot,cross:cross,proj:proj,comp:comp,diff_angle:diff_angle,rotate:rotate};Export(exports)})();(function(){"use strict";function Mesh(){this.pos=[];this.normal=[];this.color=[];this.opacity=[];this.shininess=[];this.emissive=[];this.texpos=[];this.bumpaxis=[];this.index=[];this.model_transparent=false}$.extend(Mesh.prototype,{merge:function merge(otherMesh,object,bias){var xmin=null,xmax=null,ymin=null,ymax=null,zmin=null,zmax=null;var offset=this.pos.length/3;if(object instanceof vertex){if(bias<0)this.index.push(offset+bias);else{if(xmin===null||object.__pos.x<xmin)xmin=object.__pos.x;if(xmax===null||object.__pos.x>xmax)xmax=object.__pos.x;if(ymin===null||object.__pos.y<ymin)ymin=object.__pos.y;if(ymax===null||object.__pos.y>ymax)ymax=object.__pos.y;if(zmin===null||object.__pos.z<zmin)zmin=object.__pos.z;if(zmax===null||object.__pos.z>zmax)zmax=object.__pos.z;this.pos.push(object.__pos.x,object.__pos.y,object.__pos.z);this.normal.push(object.__normal.x,object.__normal.y,object.__normal.z);this.color.push(object.__color.x,object.__color.y,object.__color.z);if(object.__opacity<1)this.model_transparent=true;this.opacity.push(object.__opacity);this.shininess.push(object.__shininess);this.emissive.push(object.__emissive);this.texpos.push(object.__texpos.x,object.__texpos.y);this.bumpaxis.push(object.__bumpaxis.x,object.__bumpaxis.y,object.__bumpaxis.z);this.index.push(offset)}}else{var c=[object.__color.x,object.__color.y,object.__color.z];for(var j=0;j<otherMesh.pos.length;j++){if(j%3===0){if(xmin===null||otherMesh.pos[j]<xmin)xmin=otherMesh.pos[j];if(xmax===null||otherMesh.pos[j]>xmax)xmax=otherMesh.pos[j]}else if(j%3===1){if(ymin===null||otherMesh.pos[j]<ymin)ymin=otherMesh.pos[j];if(ymax===null||otherMesh.pos[j]>ymax)ymax=otherMesh.pos[j]}else if(j%3===2){if(zmin===null||otherMesh.pos[j]<zmin)zmin=otherMesh.pos[j];if(zmax===null||otherMesh.pos[j]>zmax)zmax=otherMesh.pos[j]}this.pos.push(otherMesh.pos[j])}for(var j=0;j<otherMesh.normal.length;j++)this.normal.push(otherMesh.normal[j]);for(var j=0;j<otherMesh.color.length;j++)this.color.push(c[j%3]*otherMesh.color[j]);for(var j=0;j<otherMesh.opacity.length;j++){var opacity=object.__opacity*otherMesh.opacity[j];if(opacity<1)this.model_transparent=true;this.opacity.push(opacity)}for(var j=0;j<otherMesh.shininess.length;j++){var shininess=object.__shininess*otherMesh.shininess[j];this.shininess.push(shininess)}for(var j=0;j<otherMesh.emissive.length;j++){var emissive=object.__emissive||otherMesh.emissive[j]?1:0;this.emissive.push(emissive)}for(var j=0;j<otherMesh.texpos.length;j++)this.texpos.push(otherMesh.texpos[j]);for(var j=0;j<otherMesh.bumpaxis.length;j++)this.bumpaxis.push(otherMesh.bumpaxis[j]);for(var j=0;j<otherMesh.index.length;j++)this.index.push(offset+otherMesh.index[j])}return{__xmin:xmin,__ymin:ymin,__zmin:zmin,__xmax:xmax,__ymax:ymax,__zmax:zmax}},transformed:function transformed(matrix){var normalTrans=mat3.toMat4(mat3.transpose(mat4.toInverseMat3(matrix)));var out=new Mesh;out.index=this.index;out.color=this.color;out.opacity=this.opacity;out.shininess=this.shininess;out.emissive=this.emissive;out.texpos=this.texpos;for(var i=0;i<this.pos.length;i+=3){var v=[this.pos[i],this.pos[i+1],this.pos[i+2]];var n=[this.normal[i],this.normal[i+1],this.normal[i+2],0];var b=[this.bumpaxis[i],this.bumpaxis[i+1],this.bumpaxis[i+2]];mat4.multiplyVec3(matrix,v);mat4.multiplyVec4(normalTrans,n);mat4.multiplyVec3(matrix,b);out.pos.push(v[0],v[1],v[2]);out.normal.push(n[0],n[1],n[2]);out.bumpaxis.push(b[0],b[1],b[2])}return out},adjust:function adjust(v,s){var dx=v.x,dy=v.y,dz=v.z;var sx=s.x,sy=s.y,sz=s.z;for(var i=0;i<this.pos.length;i+=3){this.pos[i]=(this.pos[i]-dx)/sx;this.pos[i+1]=(this.pos[i+1]-dy)/sy;this.pos[i+2]=(this.pos[i+2]-dz)/sz;this.normal[i]*=sx;this.normal[i+1]*=sy;this.normal[i+2]*=sz}}});$.extend(Mesh,{makeCube:function(){var m=new Mesh;var s=.5;m.pos.push(+s,+s,+s,+s,-s,+s,+s,-s,-s,+s,+s,-s,-s,+s,-s,-s,-s,-s,-s,-s,+s,-s,+s,+s,-s,-s,+s,-s,-s,-s,+s,-s,-s,+s,-s,+s,-s,+s,-s,-s,+s,+s,+s,+s,+s,+s,+s,-s,-s,+s,+s,-s,-s,+s,+s,-s,+s,+s,+s,+s,+s,+s,-s,+s,-s,-s,-s,-s,-s,-s,+s,-s);m.normal.push(+1,0,0,+1,0,0,+1,0,0,+1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,-1,0,0,-1,0,0,-1,0,0,-1);m.color.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);m.opacity.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);m.shininess.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);m.emissive.push(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);m.texpos.push(0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1);m.bumpaxis.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,+1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,+1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0);m.index.push(0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23);return m},makeQuad:function(){var m=new Mesh;m.pos.push(-1,-1,0,+1,-1,0,+1,+1,0,-1,+1,0);m.normal.push(0,0,1,0,0,1,0,0,1,0,0,1);m.color.push(1,1,1,1,1,1,1,1,1,1,1,1);m.opacity.push(1,1,1,1);m.shininess.push(1,1,1,1);m.emissive.push(0,0,0,0);m.texpos.push(0,0,1,0,1,1,0,1);m.bumpaxis.push(1,0,0,1,0,0,1,0,0,1,0,0);m.index.push(0,1,2,0,2,3);return m},makeCylinder:function(R){var N=50;var dtheta=2*Math.PI/N;var sind=Math.sin(dtheta),cosd=Math.cos(dtheta);var y=-R,z=0;var newy,newz;var m=new Mesh;m.pos.push(0,0,0,1,0,0);m.normal.push(-1,0,0,1,0,0);m.color.push(1,1,1,1,1,1);m.opacity.push(1,1);m.shininess.push(1,1);m.emissive.push(0,0);m.texpos.push(.5,.5,.5,.5);m.bumpaxis.push(0,0,1,0,0,-1);var k=4*N;for(var i=2;i<=2+4*N;i+=4){m.pos.push(0,y,z,0,y,z,1,y,z,1,y,z);m.normal.push(-1,0,0,0,y,z,1,0,0,0,y,z);m.color.push(1,1,1,1,1,1,1,1,1,1,1,1);m.opacity.push(1,1,1,1);m.shininess.push(1,1,1,1);m.emissive.push(0,0,0,0);if(i<2+2*N){m.texpos.push(.5*(1+z/R),.5+.5*y/R,0,(i-2)/4/(N/2),.5*(1-z/R),.5+.5*y/R,1,(i-2)/4/(N/2))}else{m.texpos.push(.5*(1+z/R),.5+.5*y/R,0,1-(i-2-2*N)/4/(N/2),.5*(1-z/R),.5+.5*y/R,1,1-(i-2-2*N)/4/(N/2))}m.bumpaxis.push(0,0,1,1,0,0,0,0,-1,1,0,0);if(i!=2+4*N)m.index.push(0,(i-2)%k+2,(i+4-2)%k+2,i+1,(i+3-2)%k+2,(i+7-2)%k+2,i+1,(i+7-2)%k+2,(i+5-2)%k+2,1,(i+6-2)%k+2,(i+2-2)%k+2);newy=y*cosd+z*sind;newz=z*cosd-y*sind;y=newy;z=newz}return m},makeRing:function(R1,R2){var NC=64;var dphi=2*Math.PI/NC;var sphi=Math.sin(dphi),cphi=Math.cos(dphi);var N=20;var dtheta=2*Math.PI/N;var sind=Math.sin(dtheta),cosd=Math.cos(dtheta);var x=0,z=R2,newx,newz;var shape=[];for(var c=0;c<N;c++){shape.push(vec(x,0,z-R2));newx=x*cosd+z*sind;newz=z*cosd-x*sind;x=newx;z=newz}var m=new Mesh;var y=0,z=R1+R2,newy,newz;var pts=[];var normals=[];for(var c=0;c<NC;c++){var r=vec(0,y,z);for(var i=0;i<N;i++){pts.push(shape[i]);normals.push(r)}newy=y*cphi+z*sphi;newz=z*cphi-y*sphi;y=newy;z=newz}for(var c=0;c<NC;c++){for(var i=0;i<N;i++){var inext=(i+1)%N;var cnext=(c+1)%NC;var v0=pts[c*N+i];m.pos.push(v0.x,v0.y,v0.z);v0=normals[c*N+i];m.normal.push(v0.x,v0.y,v0.z);m.color.push(1,1,1);m.opacity.push(1);m.shininess.push(1);m.emissive.push(0);m.texpos.push(i/N,c/NC);v0=pts[c*N+inext].sub(pts[c*N+i]);m.bumpaxis.push(v0.x,v0.y,v0.z);m.index.push(N*c+i,N*cnext+i,N*cnext+inext,N*c+i,N*cnext+inext,N*c+inext)}}return m},makeRing_compound:function(size){var R2=size.x/2;var R1=size.y/2-R2;var NC=64;var dphi=2*Math.PI/NC;var sphi=Math.sin(dphi),cphi=Math.cos(dphi);var N=20;var dtheta=2*Math.PI/N;var sind=Math.sin(dtheta),cosd=Math.cos(dtheta);var x=0,z=R2,newx,newz;var shape=[];for(var c=0;c<N;c++){shape.push(vec(x,0,z-R2));newx=x*cosd+z*sind;newz=z*cosd-x*sind;x=newx;z=newz}var y=0,z=.5,newy,newz;var pts=[];var normals=[];for(var c=0;c<NC;c++){var r=vec(0,y*size.y,z*size.z);var n=vec(0,y,z).norm();var center=r.sub(n.multiply(R2));for(var i=0;i<N;i++){var xc=shape[i].x;var zc=shape[i].z;var p=vec(xc,0,0).add(n.multiply(zc)).add(r);pts.push(p);normals.push(p.sub(center).norm())}newy=y*cphi+z*sphi;newz=z*cphi-y*sphi;y=newy;z=newz}var m=new Mesh;for(var c=0;c<NC;c++){for(var i=0;i<N;i++){var inext=(i+1)%N;var cnext=(c+1)%NC;var v0=pts[c*N+i];m.pos.push(v0.x,v0.y,v0.z);v0=normals[c*N+i];m.normal.push(v0.x,v0.y,v0.z);m.color.push(1,1,1);m.opacity.push(1);m.shininess.push(1);m.emissive.push(0);m.texpos.push(i/N,c/NC);v0=pts[c*N+inext].sub(pts[c*N+i]);m.bumpaxis.push(v0.x,v0.y,v0.z);m.index.push(N*c+i,N*cnext+i,N*cnext+inext,N*c+i,N*cnext+inext,N*c+inext)}}return m},makeSphere:function(R,N,hemi){var Nlat=N,Nlong=N;var offset=Nlong;var dtheta=Math.PI/Nlat;var dphi=2*Math.PI/Nlong;var sint=Math.sin(dtheta),cost=Math.cos(dtheta);var sinp=Math.sin(dphi),cosp=Math.cos(dphi);var offset=Nlong;if(hemi){Nlat=N/2;Nlong=4;offset=Nlong+1;dtheta=Math.PI/Nlat;sint=-Math.sin(dtheta);cost=Math.cos(dtheta);dphi=Math.PI/Nlong;sinp=Math.sin(dphi);cosp=Math.cos(dphi)}var m=new Mesh;var x1,x2,y1,y2,z1,z2,newx1,newz1,s,firstz2;var i,j;x1=0;y1=R;z1=0;for(i=0;i<Nlat+1;i++){x2=0;y2=y1*cost+z1*sint;firstz2=z2=z1*cost-y1*sint;for(j=0;j<Nlong+1;j++){m.pos.push(x1,y1,z1);m.normal.push(x1/R,y1/R,z1/R);m.color.push(1,1,1);m.opacity.push(1);m.shininess.push(1);m.emissive.push(0);m.texpos.push(j/Nlong,1-i/Nlat);m.bumpaxis.push(z1/R,0,-x1/R);newx1=x1*cosp+z1*sinp;newz1=z1*cosp-x1*sinp;x1=newx1;z1=newz1;if(hemi&&j>=Nlong)break;s=i*offset;if(j<Nlong)m.index.push(s+j,s+j+offset,s+j+offset+1,s+j,s+j+offset+1,s+j+1);else m.index.push(s+j,s+j+offset,s+0+offset,s+j,s+0+offset,s+0)}x1=0;y1=y2;z1=firstz2;if(i==Nlat){z1=0;for(j=0;j<Nlong;j+=1){m.pos.push(0,-R,0);m.normal.push(-1,0,0);m.color.push(1,1,1);m.opacity.push(1);m.shininess.push(1);m.emissive.push(0);m.texpos.push(j/Nlong,0);m.bumpaxis.push(z1/R,0,-x1/R);newx1=x1*cosp+z1*sinp;newz1=z1*cosp-x1*sinp;x1=newx1;z1=newz1}}}return m},makeCone:function(R){var N=200;var m=new Mesh;m.pos.push(0,0,0);m.normal.push(-1,0,0);m.color.push(1,1,1);m.opacity.push(1);m.shininess.push(1);m.emissive.push(0);m.texpos.push(.5,.5);m.bumpaxis.push(0,0,1);var dtheta=2*Math.PI/N;var sind=Math.sin(dtheta),cosd=Math.cos(dtheta);var k=1/(R*Math.sqrt(5));var y=0,z=-R;var newy,newz;for(var i=1;i<=1+3*N;i+=3){newy=y*cosd+z*sind;newz=z*cosd-y*sind;m.pos.push(0,y,z,0,y,z,1,0,0);m.normal.push(-1,0,0,k*R,2*k*y,2*k*z,k*R,2*k*(y+newy)/2,2*k*(z+newz)/2);m.color.push(1,1,1,1,1,1,1,1,1);m.opacity.push(1,1,1);m.shininess.push(1,1,1);m.emissive.push(0,0,0);m.texpos.push(.5*(1+z/R),.5*(1+y/R),1-(i-1)/N/3,0,1-(i-1)/N/3,1);m.bumpaxis.push(0,0,1,0,0,1,0,-z,y);if(i!=1+3*N)m.index.push(0,i,i+3,i+1,i+2,i+4);y=newy;z=newz}return m},makePyramid:function(){var m=new Mesh;var k=1/Math.sqrt(5);m.pos.push(0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,.5,-.5,0,.5,.5,1,0,0,0,-.5,-.5,0,.5,-.5,1,0,0,0,-.5,.5,0,-.5,-.5,1,0,0,0,.5,.5,0,-.5,.5,1,0,0);m.normal.push(-1,0,0,-1,0,0,-1,0,0,-1,0,0,k,2*k,0,k,2*k,0,k,2*k,0,k,0,-2*k,k,0,-2*k,k,0,-2*k,k,-2*k,0,k,-2*k,0,k,-2*k,0,k,0,2*k,k,0,2*k,k,0,2*k);m.color.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);m.opacity.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);m.shininess.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);m.emissive.push(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);m.texpos.push(1,1,0,1,0,0,1,0,0,0,.25,0,.125,1,1,0,.75,0,.875,1,.5,0,.75,0,.625,1,.25,0,.5,0,.375,1);m.bumpaxis.push(0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,0,0,-1,0,0,-1,0,0,-1,0,-1,0,0,-1,0,0,-1,0);m.index.push(0,1,2,0,2,3,4,5,6,7,8,9,10,11,12,13,14,15);return m},makeCurveSegment:function(R){var N=16;var dtheta=2*Math.PI/N;var sind=Math.sin(dtheta),cosd=Math.cos(dtheta);var y=0,z=-R;var newy,newz;var m=new Mesh;for(var i=0;i<=2*N;i+=2){m.pos.push(0,y,z,0,0,y,z,1);m.normal.push(0,y,z,0,y,z);m.color.push(1,1,1,1,1,1);m.opacity.push(1,1);m.shininess.push(1,1);m.emissive.push(0,0);m.texpos.push(0,0,0,0);m.bumpaxis.push(0,0,0,0,0,0);if(i!=2*N)m.index.push(i,i+2,i+1,i+1,i+2,i+3);newy=y*cosd+z*sind;newz=z*cosd-y*sind;y=newy;z=newz}var offset=m.pos.length/4;var sph=Mesh.makeSphere(R,N,true);var L=sph.pos.length;for(var i=0;i<L;i++){m.pos.push(sph.pos[3*i],sph.pos[3*i+1],sph.pos[3*i+2],1);m.normal.push(sph.normal[3*i],sph.normal[3*i+1],sph.normal[3*i+2]);m.color.push(1,1,1);m.opacity.push(1);m.shininess.push(1);m.emissive.push(0);m.texpos.push(sph.texpos[2*i],sph.texpos[2*i+1]);m.bumpaxis.push(sph.bumpaxis[3*i],sph.bumpaxis[3*i+1],sph.bumpaxis[3*i+2])}for(var i=0;i<sph.index.length;i++)m.index.push(sph.index[i]+offset);return m}});var exports={Mesh:Mesh};Export(exports)})();(function(){"use strict";var _unshifted=["","","","","","","","","backspace","tab","","","","\n","","","shift","ctrl","alt","","caps lock","","","","","","","esc","","","",""," ","pageup","pagedown","end","home","left","up","right","down","","","",",","insert","delete","/","0","1","2","3","4","5","6","7","8","9","",";","","=","","","","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","[","\\","]","","","`","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","delete"];_unshifted[187]="=";_unshifted[189]="-";_unshifted[192]="`";_unshifted[219]="[";_unshifted[220]="\\";_unshifted[221]="]";_unshifted[186]=";";_unshifted[222]="'";_unshifted[188]=",";_unshifted[190]=".";_unshifted[191]="/";var _shifted=["","","","","","","","","backspace","tab","","","","\n","","","shift","ctrl","alt","break","caps lock","","","","","","","esc","","","","","","!",'"',"//","$","%","&",'"',"(",")","*","+","<","_",">","?",")","!","@","#","$","%","^","&","*","(",":",":","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","{","|","}","^","_","~","","","","","","","","","","*","+","","","","","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","","{","|","}","~","delete"];_shifted[187]="+";_shifted[189]="_";_shifted[192]="~";_shifted[219]="{";_shifted[220]="|";_shifted[221]="}";_shifted[186]=":";_shifted[222]='"';_shifted[188]="<";_shifted[190]=">";_shifted[191]="?";var shiftlock=false;var __waitfor;var __waitfor_canvas;var __waitfor__expecting_key;$.fn.extend({gsmenubar:function(cmd){if(!this.is("ul")){alert("MenuBar top level must be unordered list, i.e. <ul>.");return}this.addClass("gsmenubar");this.children("li").children("ul").each(function(){$(this).menu()})}});$.fn.waitfor=function(eventTypes,callback){var self=this;function cb(ev){self.unbind(eventTypes,cb);__waitfor="";__waitfor_canvas.__expecting_key=__waitfor__expecting_key;callback(null,ev)}this.bind(eventTypes,cb)};$.fn.pause=function(prompt,callback){var self=this;function cb(ev){prompt.visible=false;self.unbind("click",cb);__waitfor="";__waitfor_canvas.__expecting_key=__waitfor__expecting_key;callback(null,ev)}this.bind("click",cb)};window.print_anchor=$("<div/>").css("white-space","pre").appendTo($("body"));window.print_anchor.css({float:"left"});function canvas(options){if(!(this instanceof canvas))return new canvas(options);if(!options)options={};canvas.all.push(this);canvas.selected=this;canvas.hasmouse=null;this.__title_anchor=$("<div/>");this.__caption_anchor=$("<div/>");this.__titletext="";this.__captiontext="";if("title"in options){this.__titletext=options.title;delete options.title}if("caption"in options){this.__captiontext=options.caption;delete options.caption}this.__align="none";if("align"in options){this.__align=options.align;delete options.align}this.__lastevent=null;this.__autoscale=true;if("autoscale"in options){this.__autoscale=options.autoscale;delete options.autoscale}this.__range=10;for(var id in options)this[id]=options[id];this.hasmouse=false;this.__needs_update=false;this.events=$("<div/>");this.wrapper=$("<div/>");this.menu=$("<div/>");this.__canvas_element=document.createElement("canvas");this.__overlay_element=document.createElement("canvas");this.elements=$([this.__canvas_element,this.__overlay_element]);this.__overlay_objects={objects:[],__changed:false};this.__visiblePrimitives={};this.lights=[{direction:vec(.21821789,.4364357,.8728715),color:vec(.8,.8,.8)},{direction:vec(-.872872,-.218218,-.436436),color:vec(.3,.3,.3)}];this.trails=[];this.arrows=[];this.billboards=[];this.update_billboards=false;this.__points_objects=[];this.__opaque_objects={};this.__transparent_objects={};this.vertex_id=1;var N=100;this.__vertices={Nalloc:N,pos:new Float32Array(3*N),normal:new Float32Array(3*N),color:new Float32Array(3*N),opacity:new Float32Array(N),shininess:new Float32Array(N),emissive:new Float32Array(N),texpos:new Float32Array(2*N),bumpaxis:new Float32Array(3*N),index:new Uint16Array(N),model_transparent:false,object_info:{},available:[]};this.__vertices.normal[2]=1;this.__sort_objects={opaque:{plain:{},textures:{},bumpmaps:{},textures_and_bumpmaps:{}},transparent:{plain:{},textures:{},bumpmaps:{},textures_and_bumpmaps:{}}};this.camera=orbital_camera(this);this.mouse=new Mouse(this);this.mouse.pos=vec(0,0,0);this.mouse.ray=vec(0,0,1);this.textures={};this.textures_requested={};this.__changed={};this.__vertex_changed={};this.visible=true;this.waitfor_textures=false;__waitfor="";this.__expecting_key=false}property.declare(canvas.prototype,{__activate:function(){this.__activated=true;this.__activate=function(){};var container=canvas.container;this.__title_anchor.css("white-space","pre").appendTo(container);this.menu.css("white-space","pre").appendTo(container);this.wrapper.addClass("glowscript-canvas-wrapper").appendTo(container);this.__caption_anchor.css("white-space","pre").appendTo(container);this.wrapper.css("position","relative");var cv=this.__canvas_element;cv.style.position="absolute";var overlay=this.__overlay_element;overlay.style.position="relative";overlay.style.backgroundColor="transparent";this.__canvas_element.setAttribute("width",this.width);this.__overlay_element.setAttribute("width",this.width);this.__canvas_element.setAttribute("height",this.height);this.__overlay_element.setAttribute("height",this.height);this.wrapper.append(this.__canvas_element);this.wrapper.append(this.__overlay_element);$(this.wrapper).resizable();$(this.wrapper).on("resize",{this:this},function(event,ui){event.data.this.width=ui.size.width;event.data.this.height=ui.size.height});if(!this.resizable)$(this.wrapper).resizable("disable");this.wrapper.css("float",this.__align);this.__renderer=new WebGLRenderer(this,cv,overlay);if(this.camera.__activate)this.camera.__activate();this.__handleEvents();if(this.__titletext)this.title=this.__titletext;if(this.__captiontext)this.caption=this.__captiontext},remove:function(){for(var id in this.__visiblePrimitives)this.__visiblePrimitives[id].visible=false;for(var id in this.__overlay_objects.objects)this.__overlay_objects.objects[id].visible=false;this.wrapper.remove()},__change_size:function(){if(this.__activated){this.__canvas_element.style.width=Math.floor(this.width).toString()+"px";this.__overlay_element.style.width=Math.floor(this.width).toString()+"px";this.__canvas_element.style.height=Math.floor(this.height).toString()+"px";this.__overlay_element.style.height=Math.floor(this.height).toString()+"px"}},__handleEvents:function(){var canvas=this;var elements=canvas.elements;elements.bind("mouseenter mouseleave",function(ev){canvas.trigger("mouse",ev)});var keys={shift:16,ctrl:17,alt:18};$(document).bind("keydown keyup",function(ev){for(var k in keys){if(keys[k]==ev.which){canvas.mouse[k]=ev.type=="keydown";break}}if(!canvas.__expecting_key)return;ev.event=ev.type;if(ev.which==20&&ev.type=="keydown")shiftlock=!shiftlock;ev.shift=canvas.mouse.shift||shiftlock;ev.key=_unshifted[ev.which];if(shiftlock&&(65<=ev.which&&ev.which<=90))ev.key=_shifted[ev.which];else if(canvas.mouse.shift)ev.key=_shifted[ev.which];ev.alt=canvas.mouse.alt;ev.ctrl=canvas.mouse.ctrl;canvas.trigger(ev.type,ev)})},waitfor:function(eventTypes,callback){__waitfor_canvas=this;__waitfor__expecting_key=this.__expecting_key;if(eventTypes.search("key")>=0){__waitfor=eventTypes;this.__expecting_key=true}else{__waitfor="";this.__expecting_key=false}if(eventTypes=="textures")this.waitfor_textures=true;return this.events.waitfor(eventTypes,callback)},pause:function(args){__waitfor_canvas=this;__waitfor__expecting_key=this.__expecting_key;__waitfor="";var prompt="",callback;if(arguments.length==1)callback=arguments[0];else{prompt=arguments[0];callback=arguments[1]}if(prompt.length>0){if(this.__prompt==undefined){this.__prompt=label({canvas:this,align:"right",pixel_pos:true,height:14,color:color.black,background:color.white,opacity:1,box:false})}this.__prompt.pos=vec(this.__width,this.__height-12,0);this.__prompt.text=prompt;this.__prompt.visible=true;this.events.pause(this.__prompt,callback)}else{if(this.__draw==undefined)this.__draw=draw({canvas:this});var x=this.width-5,y=this.height-20;this.__draw.points=[vec(x,y,0),vec(x-30,y-13,0),vec(x-30,y+15,0),vec(x,y,0)];this.__draw.opacity=1;this.__draw.color=color.black;this.__draw.fillcolor=color.white;this.__draw.visible=true;this.events.pause(this.__draw,callback)}},select:function(){window.__context.canvas_selected=this},title_anchor:{get:function(){if(!this.__activated)this.__activate();return this.__title_anchor},set:function(value){throw new Error("Cannot change title_anchor")}},caption_anchor:{get:function(){if(!this.__activated)this.__activate();return this.__caption_anchor},set:function(value){throw new Error("Cannot change caption_anchor")}},title:{get:function(){return this.__titletext},set:function(value){this.__titletext=value;this.__title_anchor.html(value)}},caption:{get:function(){return this.__captiontext},set:function(value){this.__captiontext=value;this.__caption_anchor.html(value)}},append_to_title:function(args){var s="";var L=arguments.length;for(var i=0;i<L;i++)s+=print_to_string(arguments[i])+" ";s=s.slice(0,-1);this.__titletext+=s;this.__title_anchor.append(s)},append_to_caption:function(args){var s="";var L=arguments.length;for(var i=0;i<L;i++)s+=print_to_string(arguments[i])+" ";s=s.slice(0,-1);this.__captiontext+=s;this.__caption_anchor.append(s)},bind:function(eventTypes,callback){if(eventTypes.search("key")>=0)this.__expecting_key=true;return this.events.bind(eventTypes,callback)},unbind:function(eventTypes,callback){if(eventTypes.search("key")>=0)this.__expecting_key=false;return this.events.unbind(eventTypes,callback)},one:function(eventTypes,callback){return this.events.one(eventTypes,callback)},trigger:function(type,ev){if(ev===undefined)ev={type:type,event:event};if(type=="mouse"){type=ev.type;var ev={type:type,pageX:ev.pageX,pageY:ev.pageY,which:1};this.mouse.__update(ev);ev.event=ev.type;ev.pos=this.mouse.pos;if(ev.type=="mousedown"){ev.press="left";ev.release=null}else if(ev.type=="mousemove"){ev.press=null;ev.release=null}else if(ev.type=="mouseup"){ev.press=null;ev.release="left"}else if(ev.type=="mouseenter"||ev.type=="mouseleave"){ev.press=null;ev.release=null}else if(ev.type=="click"){ev.press=null;ev.release="left"}}if(ev!==null)ev.canvas=this;var nev=new $.Event(type,ev);this.events.trigger(nev)},background:new vec(0,0,0),ambient:new vec(.2,.2,.2),__change:function(){if(this.__lastevent!==null&&this.hasmouse)this.mouse.__update(this.__lastevent)},center:new attributeVector(null,0,0,0),forward:new attributeVector(null,0,0,-1),up:new attributeVector(null,0,1,0),__last_forward:null,__activated:false,userzoom:true,userspin:true,fov:60*Math.PI/180,width:{value:640,onchanged:function(){this.__change_size()}},height:{value:400,onchanged:function(){this.__change_size()}},align:{get:function(){return this.__align},set:function(value){if(value=="left"||value=="right"||value=="none"){this.__align=value}else throw new Error("align must be 'left', 'right', or 'none' (the default).")}},resizable:{value:false,onchanged:function(){if(this.__activated){$(this.wrapper).resizable((this.resizable?"en":"dis")+"able")}}},autoscale:{get:function(){return this.__autoscale},set:function(value){if(this.__autoscale&&!value)Autoscale.compute_autoscale(this);this.__autoscale=value}},range:{get:function(){if(this.__autoscale){Autoscale.compute_autoscale(this)}return this.__range},set:function(value){this.__autoscale=false;this.__range=value;if(this.__lastevent!==null)this.mouse.__update(this.__lastevent)}},pixel_to_world:{get:function(){var w=this.__width;var h=this.__height;var d=2*this.range;if(w>=h){return d/h}else{return d/w}},set:function(value){throw new Error("Cannot assign a value to pixel_to_world.")}},objects:{get:function(){var all=[];for(var id in this.__visiblePrimitives){var v=this.__visiblePrimitives[id];if(v.__obj){if(v==v.__obj.__components[0]&&v.__obj.visible)all.push(v.__obj)}else all.push(v)}for(var id in this.__overlay_objects.objects){var obj=this.__overlay_objects.objects[id];if(obj instanceof label)all.push(obj)}return all}}});property.declare(canvas,{selected:{get:function(){return window.__context.canvas_selected||null},set:function(value){window.__context.canvas_selected=value}},get_selected:function(){return window.__context.canvas_selected||null},all:{get:function(){var v=window.__context.canvas_all;if(v===undefined)v=window.__context.canvas_all=[];return v}},container:{get:function(){return window.__context.glowscript_container||null},set:function(value){window.__context.glowscript_container=$(value)}}});function Mouse(canvas){this.canvas=canvas}property.declare(Mouse.prototype,{canvas:null,pos:null,ray:null,__pickx:null,__picky:null,pick:function(){return this.canvas.__renderer.render(1)},project:function(args){if(args.normal===undefined)throw new Error("scene.mouse.project() must specify a normal");var normal=args.normal;var dist;if(args.d===undefined&&args.point===undefined)dist=normal.dot(this.canvas.__center);else if(args.d!==undefined){dist=args.d}else if(args.point!==undefined){dist=normal.dot(args.point)}var ndc=normal.dot(this.canvas.camera.pos)-dist;var ndr=normal.dot(this.ray);if(ndr==0)return null;var t=-ndc/ndr;return this.canvas.camera.pos.add(this.ray.multiply(t))},alt:false,ctrl:false,shift:false,__update:function(ev){var cv=this.canvas,factor;if(cv.__width>cv.__height)factor=2*cv.__range/cv.__height;else factor=2*cv.__range/cv.__width;var o=$(cv.__canvas_element).offset();this.__pickx=ev.pageX-o.left;this.__picky=cv.__height-(ev.pageY-o.top);var mx=(this.__pickx-cv.__width/2)*factor;var my=(this.__picky-cv.__height/2)*factor;var xaxis=cv.__forward.norm().cross(cv.__up).norm();var yaxis=xaxis.cross(cv.__forward.norm());this.pos=cv.__center.add(xaxis.multiply(mx).add(yaxis.multiply(my)));this.ray=this.pos.sub(cv.camera.pos).norm();canvas.hasmouse=cv;cv.__lastevent=ev}});var exports={canvas:canvas};Export(exports)})();(function(){"use strict";function orbital_camera(canvas,args){if(!(this instanceof orbital_camera))return new orbital_camera(canvas,args);this.canvas=canvas;this.follower=null}property.declare(orbital_camera.prototype,{pos:{get:function(){var c=this.canvas;return c.center.sub(c.forward.norm().multiply(c.range/Math.tan(c.fov/2)))},set:function(val){var c=this.canvas;c.center=val.add(this.axis)}},axis:{get:function(){var c=this.canvas;return c.forward.norm().multiply(c.range/Math.tan(c.fov/2))},set:function(val){var c=this.canvas;c.center=this.pos.add(val);c.forward=norm(val);c.range=mag(val)*Math.tan(c.fov/2)}},rotate:function(args){if(args===undefined||args.angle===undefined){throw new Error("object.rotate() requires an angle")}var angle=args.angle;var rotaxis,origin;if(args.axis===undefined){rotaxis=this.axis.norm()}else rotaxis=args.axis.norm();if(args.origin===undefined){origin=this.pos}else origin=args.origin;this.pos=origin.add(this.pos.sub(origin).rotate({angle:angle,axis:rotaxis}));this.axis=this.axis.rotate({angle:angle,axis:rotaxis})},follow:function(objectOrFunction){this.follower=objectOrFunction},__activate:function(){var canvas=this.canvas;var camera=this;var contextMenuDisabled=false;var lastX=[null,null],lastY=[null,null];var downX=[null,null],downY=[null,null];var angleX=0,angleY=0;var afterdown=false;var rotating,zrotating,zooming;var leftButton=false,rightButton=false,mouseWheel=false;var lastSep=null;var lastAngle=null;var fingers=0;var nomove=false;var tstart;var zoompos=[null,null];var saveEvent;var zoom=function(delta){var z=Math.exp(-delta*.05);canvas.range=canvas.range*z};var zrotate=function(dtheta){canvas.up=canvas.up.rotate({angle:2*dtheta,axis:canvas.__forward})};var spin=function(ev){var dx=ev.pageX-lastX[0];var dy=ev.pageY-lastY[0];angleX+=dx*.01;angleY+=dy*.01;if(angleY<-1.4)angleY=-1.4;if(angleY>1.4)angleY=1.4;canvas.__forward=canvas.__forward.rotate({angle:-.01*dx,axis:canvas.up});var max_vertical_angle=canvas.up.diff_angle(canvas.__forward.multiply(-1));var vertical_angle=.01*dy;if(!(vertical_angle>=max_vertical_angle||vertical_angle<=max_vertical_angle-Math.PI)){canvas.__forward=canvas.__forward.rotate({angle:-vertical_angle,axis:canvas.__forward.cross(canvas.__up)})}};$(document).bind("contextmenu",function(e){return!contextMenuDisabled});canvas.elements.mousewheel(function(ev,delta){if(canvas.userzoom)zoom(delta);return false});canvas.elements.mousedown(function(ev){if(ev.which==1)leftButton=true;if(ev.which==3)rightButton=true;rotating=canvas.userspin&&(ev.which==3||ev.which==1&&canvas.mouse.ctrl&&!canvas.mouse.alt);zooming=canvas.userzoom&&(ev.which==2||ev.which==1&&canvas.mouse.alt&&!canvas.mouse.ctrl||leftButton&&rightButton);if(ev.which==3&&!(rotating||zooming))return;downX[0]=lastX[0]=ev.pageX;downY[0]=lastY[0]=ev.pageY;if(rotating||zooming)contextMenuDisabled=true;else if(ev.which==1)canvas.trigger("mouse",ev);afterdown=true;ev.preventDefault();ev.stopPropagation();return false});canvas.elements.mousemove(function(ev){if(ev.pageX===lastX[0]&&ev.pageY===lastY[0])return;if(!afterdown){canvas.mouse.__update(ev);return}if(zooming){var dy=lastY[0]-ev.pageY;if(dy!==0)zoom(.1*dy)}else if(rotating){spin(ev)}else if(ev.which==1)canvas.trigger("mouse",ev);lastX[0]=ev.pageX;lastY[0]=ev.pageY});canvas.elements.mouseup(function(ev){if(ev.which==1)leftButton=false;if(ev.which==3)rightButton=false;if(!afterdown)return;if(ev.which==3&&contextMenuDisabled)setTimeout(function(){contextMenuDisabled=false},0);if(!(rotating||zooming)){if(ev.which==1){canvas.trigger("mouse",ev);if(abs(ev.pageX-downX[0])<=5&&abs(ev.pageY-downY[0])<=5){ev.type="click";canvas.trigger("mouse",ev)}}else if(ev.which==3){contextMenuDisabled=true;return}}rotating=zooming=afterdown=false;lastX=[null,null];lastY=[null,null]});canvas.elements.bind("touchstart",function(ev){rotating=zooming=nomove=false;lastSep=lastAngle=null;var pt;var data=ev.originalEvent.targetTouches;if(data.length>2)return;if(data.length==2&&!(canvas.userspin||canvas.userzoom))return;fingers++;for(var i=0;i<data.length;i++){pt=data[i];downX[i]=lastX[i]=pt.clientX;downY[i]=lastY[i]=pt.clientY;zoompos[i]=vec(downX[i],downY[i],0)}lastSep=null;saveEvent={type:"mousedown",pageX:downX[0],pageY:downY[0],which:1};if(!(canvas.userspin||canvas.userzoom)){canvas.trigger("mouse",saveEvent);saveEvent=null}tstart=msclock();ev.preventDefault();
  ev.stopPropagation();return false});canvas.elements.bind("touchmove",function(ev){if(nomove){canvas.mouse.__update(ev);return}var t=msclock()-tstart;var data=ev.originalEvent.targetTouches;if(data.length>2)return;var pt;var newx=[null,null],newy=[null,null];var relx=[0,0],rely=[0,0];for(var i=0;i<data.length;i++){pt=data[i];newx[i]=pt.clientX;newy[i]=pt.clientY;relx[i]=newx[i]-downX[i];rely[i]=newy[i]-downY[i]}if(data.length==2){if(!(canvas.userspin||canvas.userzoom))return;var dzoom=[null,null];if(!zooming){zrotating=false;for(var i=0;i<2;i++)dzoom[i]=vec(newx[i],newy[i],0).sub(zoompos[i]);if(dzoom[0].mag>15||dzoom[1].mag>15){saveEvent=null;zooming=true;var r=zoompos[1].sub(zoompos[0]).norm();var angmom=r.cross(dzoom[1]).sub(r.cross(dzoom[0])).mag;if(angmom>10){zrotating=canvas.userspin;if(!canvas.userspin)zooming=false}}else return}}if(saveEvent!==null){if(data.length==2){saveEvent=null}else{var near=relx[0]<=5&&rely[0]<=5;if(!rotating&&t>150&&near){canvas.trigger("mouse",saveEvent);saveEvent=null}else if(!near){rotating=canvas.userspin;saveEvent=null}}}else{if(newx[0]===lastX[0]&&newy[0]===lastY[0]&&newx[1]===lastX[1]&&newy[1]===lastY[1])return;ev.pageX=newx[0];ev.pageY=newy[0];ev.type="mousemove";if(rotating)spin(ev);else if(zooming){var xx=newx[1]-newx[0];var yy=newy[1]-newy[0];if(zrotating){var angle=Math.atan2(yy,xx);if(lastAngle!==null){var dangle;var va=vec(Math.cos(lastAngle),Math.sin(lastAngle),0);var vb=vec(Math.cos(angle),Math.sin(angle),0);var vc=va.cross(vb);var amag=Math.abs(Math.asin(vc.mag));if(vc.z>=0)dangle=-amag;else dangle=amag;zrotate(dangle)}lastAngle=angle}else if(canvas.userzoom){var sep=Math.sqrt(xx*xx+yy*yy);if(lastSep!==null&&sep!=lastSep)zoom(.2*(sep-lastSep));lastSep=sep}}else canvas.trigger("mouse",ev)}lastX[0]=newx[0];lastX[1]=newx[1];lastY[0]=newy[0];lastY[1]=newy[1]});canvas.elements.bind("touchend",function(ev){fingers--;if(saveEvent!==null&&!(rotating||zooming)){canvas.trigger("mouse",saveEvent);saveEvent=null}var data=ev.originalEvent.changedTouches;ev.pageX=data[0].clientX;ev.pageY=data[0].clientY;if(!(rotating||zooming)){ev.type="mouseup";canvas.trigger("mouse",ev);if(abs(ev.pageX-downX[0])<=5&&abs(ev.pageY-downY[0])<=5){ev.type="click";canvas.trigger("mouse",ev)}}if(zooming){if(fingers>0)nomove=true;else zooming=nomove=false}rotating=false;lastX=[null,null];lastY=[null,null];lastSep=lastAngle=null})}});var exports={orbital_camera:orbital_camera};Export(exports)})();(function(){"use strict";function extent(){}$.extend(extent.prototype,{xmin:null,ymin:null,zmin:null,xmax:null,ymax:null,zmax:null,zx_camera:0,zy_camera:0,last_zx_camera:-1,last_zy_camera:-1,point_extent:function(obj,p){this.xmin=Math.min(p.x,this.xmin);this.ymin=Math.min(p.y,this.ymin);this.zmin=Math.min(p.z,this.zmin);this.xmax=Math.max(p.x,this.xmax);this.ymax=Math.max(p.y,this.ymax);this.zmax=Math.max(p.z,this.zmax);obj.__xmin=Math.min(p.x,obj.__xmin);obj.__ymin=Math.min(p.y,obj.__ymin);obj.__zmin=Math.min(p.z,obj.__zmin);obj.__xmax=Math.max(p.x,obj.__xmax);obj.__ymax=Math.max(p.y,obj.__ymax);obj.__zmax=Math.max(p.z,obj.__zmax)}});var exports={Autoscale:{compute_autoscale:function compute_autoscale(canvas){var ext=canvas.__extent;if(!ext)ext=canvas.__extent=new extent;var ctrx=canvas.center.x,ctry=canvas.center.y,ctrz=canvas.center.z;var all=canvas.__visiblePrimitives;ext.zx_camera=0;ext.zy_camera=0;var cot_hfov=1/Math.tan(canvas.__fov/2);ext.__cot_hfov=cot_hfov;ext.__centerx=canvas.center.x;ext.__centery=canvas.center.y;ext.__centerz=canvas.center.z;var check=false;var obj;for(var id in all){obj=all[id];if(obj.constructor.name=="point")continue;if(obj.constructor.name=="points")continue;check=true;if(canvas.__changed[obj.__id]||obj.__zx_camera===null||obj.__zy_camera===null){obj.__get_extent(ext);if(obj.__xmin===null)continue;var xx=Math.max(Math.abs(obj.__xmin-ctrx),Math.abs(obj.__xmax-ctrx));var yy=Math.max(Math.abs(obj.__ymin-ctry),Math.abs(obj.__ymax-ctry));var zz=Math.max(Math.abs(obj.__zmin-ctrz),Math.abs(obj.__zmax-ctrz));obj.__zx_camera=xx*cot_hfov+zz;obj.__zy_camera=yy*cot_hfov+zz}ext.zx_camera=Math.max(ext.zx_camera,obj.__zx_camera);ext.zy_camera=Math.max(ext.zy_camera,obj.__zy_camera)}if(check){if(ext.zx_camera>ext.last_zx_camera||ext.zx_camera<ext.last_zx_camera/3||ext.zy_camera>ext.last_zy_camera||ext.zy_camera<ext.last_zy_camera/3){var predicted_zy=ext.zx_camera*canvas.__height/canvas.__width;if(predicted_zy>ext.zy_camera){if(canvas.__width>=canvas.__height){canvas.__range=1.1*(canvas.__height/canvas.__width)*ext.zx_camera/cot_hfov}else{canvas.__range=1.1*ext.zx_camera/cot_hfov}}else{if(canvas.__width>=canvas.__height){canvas.__range=1.1*ext.zy_camera/cot_hfov}else{canvas.__range=1.1*(canvas.__width/canvas.__height)*ext.zy_camera/cot_hfov}}ext.last_zx_camera=ext.zx_camera;ext.last_zy_camera=ext.zy_camera}}},find_extent:function find_extent(obj,ext){if(obj.constructor.name=="points")return;var size=obj.__size;var sizex=size.x,sizey=size.y,sizez=size.z;var start=obj.__pos;var startx=start.x,starty=start.y,startz=start.z;var center_pos=obj.__hasPosAtCenter;var length;if(center_pos)length=Math.sqrt(sizex*sizex+sizey*sizey+sizez*sizez)/2;else length=Math.sqrt(sizex*sizex+sizey*sizey/4+sizez*sizez/4);var px=startx-ext.__centerx;var py=starty-ext.__centery;var pz=startz-ext.__centerz;var zzx=(Math.abs(px)+length)*ext.__cot_hfov+Math.abs(pz)+length;var zzy=(Math.abs(py)+length)*ext.__cot_hfov+Math.abs(pz)+length;if(zzx<ext.zx_camera&&zzy<ext.zy_camera)return;var axis=obj.__axis.norm();var up=obj.__up.norm();if(center_pos)start=start.sub(axis.multiply(sizex/2));var long=axis.multiply(sizex);var z=axis.cross(up).norm();if(z.dot(z)<1e-10){z=axis.cross(vec(1,0,0)).norm();if(z.dot(z)<1e-10)z=axis.cross(vec(0,1,0)).norm()}var y=z.cross(axis);var pt1=start.add(y.multiply(-sizey/2).add(z.multiply(-sizez/2)));var pt2=pt1.add(y.multiply(sizey));var pt3=pt1.add(z.multiply(sizez));var pt4=pt2.add(z.multiply(sizez));var pt5=pt1.add(long);var pt6=pt2.add(long);var pt7=pt3.add(long);var pt8=pt4.add(long);ext.point_extent(obj,pt1);ext.point_extent(obj,pt2);ext.point_extent(obj,pt3);ext.point_extent(obj,pt4);ext.point_extent(obj,pt5);ext.point_extent(obj,pt6);ext.point_extent(obj,pt7);ext.point_extent(obj,pt8)}}};Export(exports)})();(function(){"use strict";var RENDER=0,PICK=1,EXTENT=2,RENDER_TEXTURE=3;var PEEL_C0=4;var PEEL_D0=5;var PEEL_C1=6;var PEEL_D1=7;var PEEL_C2=8;var PEEL_D2=9;var PEEL_C3=10;var PEEL_D3=11;var PEEL_C4=12;var MERGE=13;var fps=0;var renderMS=0;var lastStartRedraw=0;var lastEndRedraw=0;function WebGLRenderer(canvas,canvasElement,overlay){var renderer=this;var gl=WebGLUtils.setupWebGL(canvasElement);if(!gl)throw new Error("Can't create canvas: WebGL not supported");canvas.overlay_context=overlay.getContext("2d");var MAX_LIGHTS=8;var light_pos=new Float32Array(MAX_LIGHTS*4);var light_color=new Float32Array(MAX_LIGHTS*3);var light_ambient=new Float32Array(3);var canvas_size=new Float32Array(2);var save=new Array(4);var pixels=new Uint8Array(4);var standard_program=null,curve_program=null,triangle_program=null;var ring_program=null;var peel_depth_programD0=null;var peel_color_programC1=null;var peel_depth_programD1=null;var peel_color_programC2=null;var peel_depth_programD2=null;var peel_color_programC3=null;var peel_depth_programD3=null;var peel_color_programC4=null;var ring_peel_depth_programD0=null;var ring_peel_color_programC1=null;var ring_peel_depth_programD1=null;var ring_peel_color_programC2=null;var ring_peel_depth_programD2=null;var ring_peel_color_programC3=null;var ring_peel_depth_programD3=null;var ring_peel_color_programC4=null;var tri_peel_depth_programD0=null;var tri_peel_color_programC1=null;var tri_peel_depth_programD1=null;var tri_peel_color_programC2=null;var tri_peel_depth_programD2=null;var tri_peel_color_programC3=null;var tri_peel_depth_programD3=null;var tri_peel_color_programC4=null;var curve_peel_depth_programD0=null;var pick_program=null,curve_pick_program=null,tri_pick_program=null,ring_pick_program=null;var extent_program=null,curve_extent_program=null;var merge_program=null;var merge_program2=null;function shaderProgram(fragSrc,vertSrc,gls){function makeShader(text,type,glx){var shader=glx.createShader(type);glx.shaderSource(shader,text);glx.compileShader(shader);if(!glx.getShaderParameter(shader,glx.COMPILE_STATUS)){alert(glx.getShaderInfoLog(shader));throw new Error("Shader compile error")}return shader}var vertexShader=makeShader(vertSrc,gls.VERTEX_SHADER,gls);var fragmentShader=makeShader(fragSrc,gls.FRAGMENT_SHADER,gls);var P=gls.createProgram();gls.attachShader(P,vertexShader);gls.attachShader(P,fragmentShader);gls.linkProgram(P);if(!gls.getProgramParameter(P,gls.LINK_STATUS)){alert(gls.getProgramInfoLog(P));throw new Error("Shader link error")}var uniforms=gls.getProgramParameter(P,gls.ACTIVE_UNIFORMS);P.uniforms={};for(var i=0;i<uniforms;i++){var t=gls.getActiveUniform(P,i);var name=t.name;if(name.substring(name.length-3)=="[0]")name=name.substring(0,name.length-3);P.uniforms[name]=gls.getUniformLocation(P,name)}var attributes=gls.getProgramParameter(P,gls.ACTIVE_ATTRIBUTES);P.attributes={};for(var i=0;i<attributes;i++){var t=gls.getActiveAttrib(P,i);P.attributes[t.name]=gls.getAttribLocation(P,t.name)}return P}var Model=function(mesh,dynamism){if(dynamism)this.dynamism=gl.DYNAMIC_DRAW;else this.dynamism=gl.STATIC_DRAW;this.elementType=gl.TRIANGLES;this.mesh=mesh;this.model_transparent=mesh.model_transparent;this.pos=new Float32Array(mesh.pos);this.normal=new Float32Array(mesh.normal);this.color=new Float32Array(mesh.color);this.opacity=new Float32Array(mesh.opacity);this.shininess=new Float32Array(mesh.shininess);this.emissive=new Float32Array(mesh.emissive);this.texpos=new Float32Array(mesh.texpos);this.bumpaxis=new Float32Array(mesh.bumpaxis);this.index=new Uint16Array(mesh.index);this.posBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.posBuffer);gl.bufferData(gl.ARRAY_BUFFER,this.pos,this.dynamism);this.normalBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.normalBuffer);gl.bufferData(gl.ARRAY_BUFFER,this.normal,this.dynamism);this.colorBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,this.color,this.dynamism);this.opacityBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.opacityBuffer);gl.bufferData(gl.ARRAY_BUFFER,this.opacity,this.dynamism);this.shininessBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.shininessBuffer);gl.bufferData(gl.ARRAY_BUFFER,this.shininess,this.dynamism);this.emissiveBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.emissiveBuffer);gl.bufferData(gl.ARRAY_BUFFER,this.emissive,this.dynamism);this.texposBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.texposBuffer);gl.bufferData(gl.ARRAY_BUFFER,this.texpos,this.dynamism);this.bumpaxisBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.bumpaxisBuffer);gl.bufferData(gl.ARRAY_BUFFER,this.bumpaxis,this.dynamism);this.indexBuffer=gl.createBuffer();gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,this.indexBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,this.index,this.dynamism)};var mbox=new Model(Mesh.makeCube(),false);var mcylinder=new Model(Mesh.makeCylinder(.5),false);var msphere=new Model(Mesh.makeSphere(.5,30,false),false);var mpyramid=new Model(Mesh.makePyramid(),false);var mcone=new Model(Mesh.makeCone(.5),false);var mring=new Model(Mesh.makeRing(.5-.05,.05),false);var object_models={triangle:new Model(canvas.__vertices,true),quad:new Model(Mesh.makeQuad(),false),curve:new Model(Mesh.makeCurveSegment(1),false)};if(window.__GSlang=="vpython"){object_models.vp_box=mbox;object_models.vp_pyramid=mpyramid;object_models.vp_cylinder=mcylinder;object_models.vp_cone=mcone;object_models.vp_sphere=msphere;object_models.vp_ellipsoid=msphere;object_models.vp_ring=mring}else{object_models.box=mbox;object_models.pyramid=mpyramid;object_models.cylinder=mcylinder;object_models.cone=mcone;object_models.sphere=msphere;object_models.ring=mring}var models=this.models={};for(var id in object_models)models[id]=object_models[id];this.add_model=function(mesh,dynamism){var i=mesh.__mesh_id;models[i]=object_models[i]=new Model(mesh,dynamism);models[i].id_object={}};this.remove_model=function(mesh,dynamism){var i=mesh.__mesh_id;delete models[i];delete object_models[i]};this.screenshot=function screenshot(callback){canvas.waitfor("draw_complete",function(err){var image=new Image;image.src=canvasElement.toDataURL();callback(err,image)})};this.reset=function(){for(var t in object_models)object_models[t].id_object={}};var camera={target:vec3.create([0,0,0]),up:vec3.create([0,1,0]),fovy:60,angleX:0,angleY:0,distance:1};this.reset();function isPowerOfTwo(x){return(x&x-1)===0}function nextHighestPowerOfTwo(x){--x;for(var i=1;i<32;i<<=1){x=x|x>>i}return x+1}function handleLoadedTexture(image,obj,bump){var name,t0,ref;if(bump){name=obj.__tex.bumpmap;ref=obj.__tex.bumpmap_ref;t0=obj.__tex.bumpmap_t0}else{name=obj.__tex.file;ref=obj.__tex.texture_ref;t0=obj.__tex.texture_t0}var tf=msclock();tf=tf-t0;if(name in canvas.textures){ref.reference=canvas.textures[name]}else{canvas.textures[name]=ref.reference=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,ref.reference);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);if(!isPowerOfTwo(image.width)||!isPowerOfTwo(image.height)){var c=document.createElement("canvas");c.width=nextHighestPowerOfTwo(image.width);c.height=nextHighestPowerOfTwo(image.height);var ctx=c.getContext("2d");ctx.drawImage(image,0,0,c.width,c.height);image=c}gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,image);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_NEAREST);gl.generateMipmap(gl.TEXTURE_2D);gl.bindTexture(gl.TEXTURE_2D,null)}if(name in canvas.textures_requested){var done=canvas.textures_requested[name];while(done.length>0){var data=done.pop();if(data[1]){data[0].__tex.bumpmap_ref.reference=ref.reference}else{data[0].__tex.texture_ref.reference=ref.reference}data[0].__change()}}}this.initTexture=function(name,obj,bump){if(bump)obj.__tex.bumpmap=name;else obj.__tex.file=name;if(name in canvas.textures){if(bump)obj.__tex.bumpmap_ref.reference=canvas.textures[name];else obj.__tex.texture_ref.reference=canvas.textures[name];return}if(name in canvas.textures_requested){canvas.textures_requested[name].push([obj,bump]);return}else canvas.textures_requested[name]=[[obj,bump]];var t0=msclock();if(bump)obj.__tex.bumpmap_t0=t0;else obj.__tex.texture_t0=t0;var image=new Image;image.crossOrigin="anonymous";image.src=name;image.onload=function(){handleLoadedTexture(image,obj,bump)}};var update_vertices=0;var last_width=-1;var last_height=-1;var ktexture=1;var peels={C0:null,D0:null,C1:null,D1:null,C2:null,D2:null,C3:null,D3:null,C4:null,EXTENT_TEXTURE:null};var fullpeels=gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS)>=16;var textureN={C0:gl.TEXTURE2,D0:gl.TEXTURE3,C1:gl.TEXTURE4,D1:gl.TEXTURE5,C2:gl.TEXTURE6,D2:gl.TEXTURE7,C3:gl.TEXTURE8,D3:gl.TEXTURE9,C4:gl.TEXTURE10,EXTENT_TEXTURE:gl.TEXTURE11};function makeTexture(T){gl.activeTexture(textureN[T]);gl.bindTexture(gl.TEXTURE_2D,peels[T]);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_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);if(false&&T=="EXTENT_TEXTURE")gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,3,3,0,gl.RGBA,gl.UNSIGNED_BYTE,null);else gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,ktexture*canvas.__width,ktexture*canvas.__height,0,gl.RGBA,gl.UNSIGNED_BYTE,null);gl.bindTexture(gl.TEXTURE_2D,null)}for(var T in peels){peels[T]=gl.createTexture();makeTexture(T)}var peelFramebuffer=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,peelFramebuffer);var peelRenderbuffer=gl.createRenderbuffer();gl.bindRenderbuffer(gl.RENDERBUFFER,peelRenderbuffer);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,ktexture*canvas.__width,ktexture*canvas.__height);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_ATTACHMENT,gl.RENDERBUFFER,peelRenderbuffer);gl.bindRenderbuffer(gl.RENDERBUFFER,null);gl.bindFramebuffer(gl.FRAMEBUFFER,null);last_width=canvas.__width;last_height=canvas.__height;var data=new Uint8Array(3);var tex1=gl.createTexture();gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,tex1);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGB,1,1,0,gl.RGB,gl.UNSIGNED_BYTE,data);var tex0=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,tex0);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGB,1,1,0,gl.RGB,gl.UNSIGNED_BYTE,data);this.render=function(mode){if(mode==RENDER){if(canvas.waitfor_textures){var check_objects=canvas.objects;for(var o in check_objects){var obj=check_objects[o];if(obj.__tex===undefined)continue;if(!obj.ready)return}canvas.waitfor_textures=false;canvas.trigger("textures",null)}}if(!canvas.visible){if(mode==RENDER)return;return null}if(canvas.__width!=last_width||canvas.__height!=last_height){for(var T in peels){makeTexture(T)}last_width=canvas.__width;last_height=canvas.__height}if(canvas.autoscale)Autoscale.compute_autoscale(canvas);if(canvas.camera.follower!==null){canvas.center=typeof canvas.camera.follower!=="function"?canvas.camera.follower.pos:canvas.camera.follower()}if(mode==RENDER){for(var i in canvas.arrows){var pos;var a=canvas.arrows[i];if(!a.run)continue;if(a.obj!==undefined){if(a.obj.pos!==undefined)pos=a.obj.pos;else continue}if(a.last_pos!==null&&pos.equals(a.last_pos))continue;a.arrow.pos=pos;if(a.obj[a.attr]!==undefined){if(!a.arrow.visible)a.arrow.visible=true;if(window.__GSlang=="vpython")a.arrow.axis=a.obj[a.attr].multiply(a.scale);else a.arrow.axis_and_length=a.obj[a.attr].multiply(a.scale)}}for(var i in canvas.trails){var pos;var a=canvas.trails[i];if(!a.__run)continue;var obj=a.__obj;if(obj===undefined)continue;if(typeof obj==="string"){pos=a[obj];if(pos===undefined)continue}else if(typeof obj!=="function"){if(obj!==undefined&&obj.visible){if(!obj._pos_set)continue;if(obj.__interval>0)continue;if(obj.__pos!==undefined)pos=obj.__pos;else continue}else continue}else pos=obj();if(a.__last_pos!==null&&pos.equals(a.__last_pos))continue;if(a.pps>0){var tnow=msclock();if(a.__last_time===null)a.last_time=tnow;if(tnow-a.__last_time>1e3/a.pps)a.__last_time=tnow;else if(tnow!=a.__last_time)continue}a.__trail.push({pos:pos,color:a.color,radius:a.radius,retain:a.retain});a.__last_pos=vec(pos)}if(canvas.update_billboards||!canvas.__forward.equals(canvas.__last_forward)||!canvas.__up.equals(canvas.__last_up)){canvas.update_billboards=false;for(var i=0;i<canvas.billboards.length;i++){var T=canvas.billboards[i];if(T.billboard){var x=cross(canvas.__forward,canvas.__up);var y=cross(x,canvas.forward);if(window.__GSlang=="vpython")T.axis=norm(x).multiply(mag(T.axis));else T.axis=x;T.up=y}}}}camera.target=vec3.create([canvas.__center.x,canvas.__center.y,canvas.__center.z]);camera.up=vec3.create([canvas.__up.x,canvas.__up.y,canvas.__up.z]);camera.fovy=canvas.__fov*180/Math.PI;var xz_unit_vector=vec(canvas.__forward.x,0,canvas.__forward.z).norm();camera.angleX=Math.atan2(xz_unit_vector.x,-xz_unit_vector.z);camera.angleY=Math.PI/2-Math.acos(-canvas.__forward.norm().y);if(canvasElement.clientWidth>=canvasElement.clientHeight)camera.distance=canvas.__range/Math.tan(canvas.__fov/2);else camera.distance=canvas.__range*(canvasElement.clientHeight/canvasElement.clientWidth)/Math.tan(canvas.__fov/2);camera.pos=mat4.multiplyVec3(mat4.rotateX(mat4.rotateY(mat4.identity(mat4.create()),-camera.angleX),-camera.angleY),vec3.create([0,0,camera.distance]));camera.pos=vec3.create([canvas.__center.x+camera.pos[0],canvas.__center.y+camera.pos[1],canvas.__center.z+camera.pos[2]]);camera.zNear=camera.distance/100;camera.zFar=camera.distance*10;var projMatrix=mat4.perspective(camera.fovy,canvasElement.clientWidth/canvasElement.clientHeight,camera.zNear,camera.zFar);var viewMatrix=mat4.lookAt(camera.pos,camera.target,camera.up);var light_count=Math.min(canvas.lights.length,MAX_LIGHTS);for(var i=0;i<light_count;i++){var light=canvas.lights[i];if(light.direction===undefined)var lightVec4=[light.pos.x,light.pos.y,light.pos.z,1];else var lightVec4=[light.direction.x,light.direction.y,light.direction.z,0];mat4.multiplyVec4(viewMatrix,lightVec4);for(var c=0;c<4;c++)light_pos[i*4+c]=lightVec4[c];light_color[i*3]=light.color.x;light_color[i*3+1]=light.color.y;light_color[i*3+2]=light.color.z}light_ambient[0]=canvas.ambient.x;light_ambient[1]=canvas.ambient.y;light_ambient[2]=canvas.ambient.z;if(canvas.__points_objects.length>0){var ptsobj=canvas.__points_objects;var scale=3*canvas.__range/canvas.__width;var D;for(var i=0;i<ptsobj.length;i++){var p=ptsobj[i];if(p.__pixels){if(p===undefined||p.__last_range===canvas.__range)continue;p.__last_range=canvas.__range;D=p.__radius===0?10*scale:2*scale*p.__radius}else D=2*p.__radius;for(var s=0;s<p.__points.length;s++)p.__points[s].size=vec(D,D,D)}}if(mode==RENDER){if(canvas.__overlay_objects.objects.length>0&&(canvas.__overlay_objects.__changed||!(canvas.__forward.equals(canvas.__last_forward)&&canvas.__up.equals(canvas.__last_up)&&canvas.__range==canvas.__last_range))){canvas.__overlay_objects.__changed=false;var ctx=canvas.overlay_context;ctx.clearRect(0,0,canvas.__width,canvas.__height);for(var i=0;i<canvas.__overlay_objects.objects.length;i++){var obj=canvas.__overlay_objects.objects[i];if(!obj.visible)continue;obj.__update(ctx,camera)}}}var lengths={pos:3,normal:3,color:3,opacity:1,shininess:1,emissive:1,texpos:2,bumpaxis:3};var c=canvas.__vertices;for(var id in canvas.__vertex_changed){var vert=canvas.__vertex_changed[id];var Nvert=vert.__id;update_vertices++;for(var t in lengths){var g=vert["__"+t];if(lengths[t]==1){c[t][Nvert]=g}else if(lengths[t]==2){c[t][2*Nvert]=g.x;c[t][2*Nvert+1]=g.y}else{c[t][3*Nvert]=g.x;c[t][3*Nvert+1]=g.y;c[t][3*Nvert+2]=g.z}}}canvas.__vertex_changed={};for(var i=0;i<2;i++){var arrow_updates=[];for(var id in canvas.__changed){var c=canvas.__changed[id];if(c.__obj){if(!c.__obj.visible)continue;if(arrow_updates.indexOf(c.__obj)<0){c.__obj.__update();arrow_updates.push(c.__obj)}delete canvas.__changed[c.__id];if(!c.__obj.visible)delete c.__model.id_object[c.__id]}else{c.__update();delete canvas.__changed[id]}}}canvas.__changed={};for(var m in object_models){canvas.__opaque_objects[m]={};canvas.__transparent_objects[m]={}}var need_RENDER_TEXTURE=false;for(var m in object_models){if(m=="triangle"||m=="quad"||m=="point")continue;var model=object_models[m];var objs=model.id_object;for(var id in objs){var obj=objs[id];if(m=="curve"){canvas.__opaque_objects[m][id]=obj;continue}if(mode==RENDER&&(obj.__data[19]<1||model.model_transparent)){canvas.__transparent_objects[m][id]=obj;need_RENDER_TEXTURE=true}else{canvas.__opaque_objects[m][id]=obj}}}var sort=canvas.__sort_objects;for(var op in sort){for(var a in sort[op])sort[op][a]={}}var Nvert;var vnames=["v0","v1","v2","v3"];function add_indices(A,T,obj){if(obj.__owner!==undefined&&!obj.__owner.__vis)return;var c=A[T];if(c===undefined)c=A[T]=[obj];if(Nvert==3)c.push(obj.v0.__id,obj.v1.__id,obj.v2.__id);else c.push(obj.v0.__id,obj.v1.__id,obj.v2.__id,obj.v0.__id,obj.v2.__id,obj.v3.__id)}var pickdata={pos:[],color:[],index:[]};var triangles_exist=false,model;for(var m=0;m<2;m++){if(m===0){Nvert=3;model=object_models["triangle"]}else{Nvert=4;model=object_models["quad"]}var objs=model.id_object;for(var id in objs){triangles_exist=true;var obj=objs[id];if(mode==PICK){var color=obj.__falsecolor;var p;for(var i=0;i<3;i++){p=obj[vnames[i]].pos;pickdata.pos.push(p.x,p.y,p.z);pickdata.color.push(color[0],color[1],color[2],color[3]);pickdata.index.push(pickdata.index.length)}if(Nvert==4){var indices=[0,2,3];for(var ind=0;ind<3;ind++){var i=indices[ind];p=obj[vnames[i]].pos;pickdata.pos.push(p.x,p.y,p.z);pickdata.color.push(color[0],color[1],color[2],color[3]);pickdata.index.push(pickdata.index.length)}}}else if(mode==RENDER){var opaque=true;for(var i=0;i<Nvert;i++){if(obj[vnames[i]].opacity<1){opaque=false;break}}var t=obj.__tex.file;var b=obj.__tex.bumpmap;if(opaque){if(t!==null){add_indices(sort.opaque.textures,t,obj);if(b!=null){add_indices(sort.opaque.textures_and_bumpmaps,b,obj)}}else if(b!=null){add_indices(sort.opaque.bumpmaps,b,obj)}else add_indices(sort.opaque.plain,"all",obj)}else{need_RENDER_TEXTURE=true;if(t!==null){add_indices(sort.transparent.textures,t,obj);if(b!=null){add_indices(sort.transparent.textures_and_bumpmaps,b,obj)}}else if(b!=null){add_indices(sort.transparent.bumpmaps,b,obj)}else add_indices(sort.transparent.plain,"all",obj)}}}}if(need_RENDER_TEXTURE)mode=RENDER_TEXTURE;var program;canvas_size[0]=ktexture*canvas.__width;canvas_size[1]=ktexture*canvas.__height;function useProgram(prog,minormode){program=prog;gl.useProgram(prog);gl.enableVertexAttribArray(prog.attributes.pos);if(mode==MERGE||minormode>PEEL_D0)gl.uniform2fv(prog.uniforms.canvas_size,canvas_size);if(minormode!=MERGE){if(mode==RENDER||minormode==PEEL_C0||minormode==PEEL_C1||minormode==PEEL_C2||minormode==PEEL_C3||minormode==PEEL_C4){gl.uniform1i(prog.uniforms.light_count,light_count);gl.uniform4fv(prog.uniforms.light_pos,light_pos);gl.uniform3fv(prog.uniforms.light_color,light_color);gl.uniform3fv(prog.uniforms.light_ambient,light_ambient);gl.enableVertexAttribArray(prog.attributes.normal);if(prog!=curve_program){gl.enableVertexAttribArray(prog.attributes.color);gl.enableVertexAttribArray(prog.attributes.opacity);gl.enableVertexAttribArray(prog.attributes.shininess);gl.enableVertexAttribArray(prog.attributes.emissive);gl.enableVertexAttribArray(prog.attributes.texpos);gl.enableVertexAttribArray(prog.attributes.bumpaxis);gl.uniform1i(prog.uniforms.texmap,0);gl.uniform1i(prog.uniforms.bumpmap,1)}}gl.uniformMatrix4fv(prog.uniforms.viewMatrix,false,viewMatrix);gl.uniformMatrix4fv(prog.uniforms.projMatrix,false,projMatrix)}if(minormode==MERGE){gl.uniform1i(prog.uniforms.C0,2);gl.uniform1i(prog.uniforms.C1,4);if(fullpeels){gl.uniform1i(prog.uniforms.C2,6);gl.uniform1i(prog.uniforms.C3,8);gl.uniform1i(prog.uniforms.C4,10)}}else if(minormode>PEEL_D0){gl.uniform1i(prog.uniforms.D0,3);if(minormode==PEEL_C2||minormode==PEEL_D2)gl.uniform1i(prog.uniforms.D1,5);else if(minormode==PEEL_C3||minormode==PEEL_D3)gl.uniform1i(prog.uniforms.D2,7);else if(minormode==PEEL_C4)gl.uniform1i(prog.uniforms.D3,9)}}function subrender(minormode,T,Trefs){if(mode==RENDER_TEXTURE&&Trefs.length>0){for(var i=0;i<Trefs.length;i++){var a=Trefs[i];if(a==T)continue;gl.activeTexture(textureN[a]);gl.bindTexture(gl.TEXTURE_2D,peels[a])}}if(T===null){gl.bindFramebuffer(gl.FRAMEBUFFER,null)}else{gl.bindFramebuffer(gl.FRAMEBUFFER,peelFramebuffer);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,peels[T],0)}gl.viewport(0,0,canvas_size[0],canvas_size[1]);gl.enable(gl.DEPTH_TEST);if(mode==PICK||minormode>PEEL_C0)gl.clearColor(0,0,0,0);else if(mode==EXTENT)gl.clearColor(0,0,0,1);else gl.clearColor(canvas.__background.x,canvas.__background.y,canvas.__background.z,1);if(mode==EXTENT){gl.depthFunc(gl.GREATER);gl.clearDepth(0)}else{gl.depthFunc(gl.LEQUAL);gl.clearDepth(1)}gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);function render_curves(){var model=object_models.curve;var objs=model.id_object;var elements=model.elementType;var model_length=model.index.length;var setup=true;for(var id in objs){if(!objs[id].visible)break;if(minormode>PEEL_D0)break;if(setup){if(minormode==RENDER||minormode==PEEL_C0){if(curve_program==null)curve_program=shaderProgram(shaders.opaque_render_fragment,shaders.curve_render_vertex,gl);useProgram(curve_program,minormode)}else if(minormode==PEEL_D0){if(curve_peel_depth_programD0==null)curve_peel_depth_programD0=shaderProgram(shaders.peel_depth_fragmentD0,shaders.curve_peel_depth_vertex,gl);useProgram(curve_peel_depth_programD0,minormode)}else if(minormode==PICK){if(curve_pick_program==null)curve_pick_program=shaderProgram(shaders.pick_fragment,shaders.curve_pick_vertex,gl);useProgram(curve_pick_program,minormode)}gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);gl.vertexAttribPointer(program.attributes.pos,4,gl.FLOAT,false,0,0);if(minormode!=PICK&&minormode<PEEL_D0){gl.bindBuffer(gl.ARRAY_BUFFER,model.normalBuffer);gl.vertexAttribPointer(program.attributes.normal,3,gl.FLOAT,false,0,0)}gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,model.indexBuffer);if(mode==EXTENT)elements=gl.POINTS;setup=false}var obj=objs[id];var p=obj.__points;var length=p.length;var save_radius=obj.__data[15];if(save_radius===0){obj.__data[15]=4*canvas.__range/canvas.__width}gl.uniform4fv(program.uniforms.objectData,obj.__data);for(var t=1;t<length;t++){var pnt=p[t];if(!pnt.visible)continue;var data=pnt.__prevsegment;if(mode==PICK){var falsecolor=pnt.__falsecolor;for(var i=0;i<4;i++){save[i]=data[8+i];save[i+4]=data[12+i];data[12+i]=data[8+i]=falsecolor[i]}}gl.uniform4fv(program.uniforms.segmentData,data);gl.drawElements(elements,model_length,gl.UNSIGNED_SHORT,0);if(mode==PICK){for(var i=0;i<8;i++)data[8+i]=save[i]}}obj.__data[15]=save_radius}}function render_triangles(){var model=object_models.triangle;var elements=model.elementType;var model_arrays=canvas.__vertices;if(mode==PICK){if(tri_pick_program==null)tri_pick_program=shaderProgram(shaders.pick_fragment,shaders.tri_pick_vertex,gl);useProgram(tri_pick_program,minormode);model_arrays={};model_arrays.pos=new Float32Array(pickdata.pos);model_arrays.color=new Float32Array(pickdata.color);model_index=new Uint16Array(pickdata.index);model_length=model_index.length;gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);gl.bufferData(gl.ARRAY_BUFFER,model_arrays.pos,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.pos,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,model_arrays.color,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.color,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,model.indexBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,model_index,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.color,4,gl.FLOAT,false,0,0);gl.drawElements(elements,model_length,gl.UNSIGNED_SHORT,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);gl.bufferData(gl.ARRAY_BUFFER,canvas.__vertices.pos,gl.DYNAMIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,model.colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,canvas.__vertices.color,gl.DYNAMIC_DRAW);return}var sort=canvas.__sort_objects;for(var op in sort){if(minormode>PEEL_D0){if(op=="opaque")continue}else{if(op=="transparent")continue}var first=true;for(var sort_type in sort[op]){for(var sort_list in sort[op][sort_type]){if(first){first=false;switch(minormode){case RENDER:case PEEL_C0:if(triangle_program===null)triangle_program=shaderProgram(shaders.opaque_render_fragment,shaders.tri_render_vertex,gl);useProgram(triangle_program,minormode);break;case EXTENT:if(extent_program===null)extent_program=shaderProgram(shaders.pick_fragment,shaders.extent_vertex,gl);useProgram(extent_program,minormode);break;case PEEL_D0:if(tri_peel_depth_programD0===null)tri_peel_depth_programD0=shaderProgram(shaders.peel_depth_fragmentD0,shaders.tri_peel_depth_vertex,gl);useProgram(tri_peel_depth_programD0,minormode);break;case PEEL_D1:if(tri_peel_depth_programD1===null)tri_peel_depth_programD1=shaderProgram(shaders.peel_depth_fragmentD1,shaders.tri_peel_depth_vertex,gl);useProgram(tri_peel_depth_programD1,minormode);break;case PEEL_D2:if(tri_peel_depth_programD2===null)tri_peel_depth_programD2=shaderProgram(shaders.peel_depth_fragmentD2,shaders.tri_peel_depth_vertex,gl);useProgram(tri_peel_depth_programD2,minormode);break;case PEEL_D3:if(tri_peel_depth_programD3===null)tri_peel_depth_programD3=shaderProgram(shaders.peel_depth_fragmentD3,shaders.tri_peel_depth_vertex,gl);useProgram(tri_peel_depth_programD3,minormode);break;case PEEL_C1:if(tri_peel_color_programC1===null)tri_peel_color_programC1=shaderProgram(shaders.peel_color_fragmentC1,shaders.tri_render_vertex,gl);useProgram(tri_peel_color_programC1,minormode);break;case PEEL_C2:if(tri_peel_color_programC2===null)tri_peel_color_programC2=shaderProgram(shaders.peel_color_fragmentC2,shaders.tri_render_vertex,gl);
  useProgram(tri_peel_color_programC2,minormode);break;case PEEL_C3:if(tri_peel_color_programC3===null)tri_peel_color_programC3=shaderProgram(shaders.peel_color_fragmentC3,shaders.tri_render_vertex,gl);useProgram(tri_peel_color_programC3,minormode);break;case PEEL_C4:if(tri_peel_color_programC4===null)tri_peel_color_programC4=shaderProgram(shaders.peel_color_fragmentC4,shaders.tri_render_vertex,gl);useProgram(tri_peel_color_programC4,minormode);break}gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.pos,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.pos,3,gl.FLOAT,false,0,0);if(mode==RENDER||minormode==PEEL_C0||minormode==PEEL_C1||minormode==PEEL_C2||minormode==PEEL_C3||minormode==PEEL_C4){gl.bindBuffer(gl.ARRAY_BUFFER,model.normalBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.normal,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.normal,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.colorBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.color,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.color,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.opacityBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.opacity,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.opacity,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.shininessBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.shininess,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.shininess,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.emissiveBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.emissive,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.emissive,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.texposBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.texpos,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.texpos,2,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.bumpaxisBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.bumpaxis,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.bumpaxis,3,gl.FLOAT,false,0,0);update_vertices=0}}var indices=sort[op][sort_type][sort_list];var tbobj=indices[0];var model_index=new Uint16Array(indices.slice(1));var model_length=model_index.length;gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,model.indexBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,model_index,gl.DYNAMIC_DRAW);if(mode==EXTENT)elements=gl.POINTS;var Tdata=0,Bdata=0;if(sort_type=="textures"){if((mode==RENDER||mode==RENDER_TEXTURE)&&tbobj.__tex.file!==null){if(tbobj.__tex.texture_ref.reference!==null){gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,tbobj.__tex.texture_ref.reference);Tdata=1}else continue}}else if(sort_type=="bumpmaps"){if((mode==RENDER||mode==RENDER_TEXTURE)&&tbobj.__tex.bumpmap!==null){if(tbobj.__tex.bumpmap_ref.reference!==null){gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,tbobj.__tex.bumpmap_ref.reference);Bdata=1}else continue}}else if(sort_type=="textures_and_bumpmaps"){if((mode==RENDER||mode==RENDER_TEXTURE)&&tbobj.__tex.file!==null){if(tbobj.__tex.texture_ref.reference!==null){gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,tbobj.__tex.texture_ref.reference);Tdata=1}else continue}if((mode==RENDER||mode==RENDER_TEXTURE)&&tbobj.__tex.bumpmap!==null){if(tbobj.__tex.bumpmap_ref.reference!==null){gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,tbobj.__tex.bumpmap_ref.reference);Bdata=1}else continue}}gl.uniform1f(program.uniforms.T,Tdata);gl.uniform1f(program.uniforms.B,Bdata);gl.drawElements(elements,model_length,gl.UNSIGNED_SHORT,0)}}}}function render_merge(){var model=object_models.quad;var elements=model.elementType;var model_length=model.index.length;if(fullpeels){if(merge_program==null)merge_program=shaderProgram(shaders.merge_fragment,shaders.merge_vertex,gl);useProgram(merge_program,minormode)}else{if(merge_program2==null)merge_program2=shaderProgram(shaders.merge_fragment2,shaders.merge_vertex,gl);useProgram(merge_program2,minormode)}gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);gl.vertexAttribPointer(program.attributes.pos,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,model.indexBuffer);gl.drawElements(elements,model_length,gl.UNSIGNED_SHORT,0)}for(var m in object_models){if(minormode>=MERGE){render_merge();break}if(m=="quad"||m=="triangle"){if(triangles_exist)render_triangles();continue}else if(m=="curve"){render_curves();continue}var model=object_models[m];var elements=model.elementType;var model_length=model.index.length;var objs;if(minormode>PEEL_D0){if(canvas.__transparent_objects[m]===undefined)continue;objs=canvas.__transparent_objects[m]}else{if(canvas.__opaque_objects[m]===undefined)continue;objs=canvas.__opaque_objects[m]}var gotobjects=false;for(var id in objs){gotobjects=true;break}if(!gotobjects)continue;var ringobject=m=="ring"||m=="vp_ring";switch(minormode){case RENDER:case PEEL_C0:if(ringobject){if(ring_program===null)ring_program=shaderProgram(shaders.opaque_render_fragment,shaders.ring_render_vertex,gl);useProgram(ring_program,minormode)}else{if(standard_program===null)standard_program=shaderProgram(shaders.opaque_render_fragment,shaders.render_vertex,gl);useProgram(standard_program,minormode)}break;case PICK:if(ringobject){if(ring_pick_program===null)ring_pick_program=shaderProgram(shaders.pick_fragment,shaders.ring_pick_vertex,gl);useProgram(ring_pick_program,minormode)}else{if(pick_program===null)pick_program=shaderProgram(shaders.pick_fragment,shaders.pick_vertex,gl);useProgram(pick_program,minormode)}break;case EXTENT:if(extent_program===null)extent_program=shaderProgram(shaders.pick_fragment,shaders.extent_vertex,gl);useProgram(extent_program,minormode);break;case PEEL_D0:if(ringobject){if(ring_peel_depth_programD0===null)ring_peel_depth_programD0=shaderProgram(shaders.peel_depth_fragmentD0,shaders.ring_peel_depth_vertex,gl);useProgram(ring_peel_depth_programD0,minormode)}else{if(peel_depth_programD0===null)peel_depth_programD0=shaderProgram(shaders.peel_depth_fragmentD0,shaders.peel_depth_vertex,gl);useProgram(peel_depth_programD0,minormode)}break;case PEEL_D1:if(ringobject){if(ring_peel_depth_programD1===null)ring_peel_depth_programD1=shaderProgram(shaders.peel_depth_fragmentD1,shaders.ring_peel_depth_vertex,gl);useProgram(ring_peel_depth_programD1,minormode)}else{if(peel_depth_programD1===null)peel_depth_programD1=shaderProgram(shaders.peel_depth_fragmentD1,shaders.peel_depth_vertex,gl);useProgram(peel_depth_programD1,minormode)}break;case PEEL_D2:if(ringobject){if(ring_peel_depth_programD2===null)ring_peel_depth_programD2=shaderProgram(shaders.peel_depth_fragmentD2,shaders.ring_peel_depth_vertex,gl);useProgram(ring_peel_depth_programD2,minormode)}else{if(peel_depth_programD2===null)peel_depth_programD2=shaderProgram(shaders.peel_depth_fragmentD2,shaders.peel_depth_vertex,gl);useProgram(peel_depth_programD2,minormode)}break;case PEEL_D3:if(ringobject){if(ring_peel_depth_programD3===null)ring_peel_depth_programD3=shaderProgram(shaders.peel_depth_fragmentD3,shaders.ring_peel_depth_vertex,gl);useProgram(ring_peel_depth_programD3,minormode)}else{if(peel_depth_programD3===null)peel_depth_programD3=shaderProgram(shaders.peel_depth_fragmentD3,shaders.peel_depth_vertex,gl);useProgram(peel_depth_programD3,minormode)}break;case PEEL_C1:if(ringobject){if(ring_peel_color_programC1===null)ring_peel_color_programC1=shaderProgram(shaders.peel_color_fragmentC1,shaders.ring_render_vertex,gl);useProgram(ring_peel_color_programC1,minormode)}else{if(peel_color_programC1===null)peel_color_programC1=shaderProgram(shaders.peel_color_fragmentC1,shaders.render_vertex,gl);useProgram(peel_color_programC1,minormode)}break;case PEEL_C2:if(ringobject){if(ring_peel_color_programC2===null)ring_peel_color_programC2=shaderProgram(shaders.peel_color_fragmentC2,shaders.ring_render_vertex,gl);useProgram(ring_peel_color_programC2,minormode)}else{if(peel_color_programC2===null)peel_color_programC2=shaderProgram(shaders.peel_color_fragmentC2,shaders.render_vertex,gl);useProgram(peel_color_programC2,minormode)}break;case PEEL_C3:if(ringobject){if(ring_peel_color_programC3===null)ring_peel_color_programC3=shaderProgram(shaders.peel_color_fragmentC3,shaders.ring_render_vertex,gl);useProgram(ring_peel_color_programC3,minormode)}else{if(peel_color_programC3===null)peel_color_programC3=shaderProgram(shaders.peel_color_fragmentC3,shaders.render_vertex,gl);useProgram(peel_color_programC3,minormode)}break;case PEEL_C4:if(ringobject){if(ring_peel_color_programC4===null)ring_peel_color_programC4=shaderProgram(shaders.peel_color_fragmentC4,shaders.ring_render_vertex,gl);useProgram(ring_peel_color_programC4,minormode)}else{if(peel_color_programC4===null)peel_color_programC4=shaderProgram(shaders.peel_color_fragmentC4,shaders.render_vertex,gl);useProgram(peel_color_programC4,minormode)}break}gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);gl.vertexAttribPointer(program.attributes.pos,3,gl.FLOAT,false,0,0);if(mode!=PICK&&(mode==RENDER||minormode==PEEL_C0||minormode==PEEL_C1||minormode==PEEL_C2||minormode==PEEL_C3||minormode==PEEL_C4)){gl.bindBuffer(gl.ARRAY_BUFFER,model.normalBuffer);gl.vertexAttribPointer(program.attributes.normal,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.colorBuffer);gl.vertexAttribPointer(program.attributes.color,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.opacityBuffer);gl.vertexAttribPointer(program.attributes.opacity,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.shininessBuffer);gl.vertexAttribPointer(program.attributes.shininess,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.emissiveBuffer);gl.vertexAttribPointer(program.attributes.emissive,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.texposBuffer);gl.vertexAttribPointer(program.attributes.texpos,2,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.bumpaxisBuffer);gl.vertexAttribPointer(program.attributes.bumpaxis,3,gl.FLOAT,false,0,0)}else if(ringobject){gl.bindBuffer(gl.ARRAY_BUFFER,model.normalBuffer);gl.vertexAttribPointer(program.attributes.normal,3,gl.FLOAT,false,0,0)}gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,model.indexBuffer);if(mode==EXTENT)elements=gl.POINTS;for(var id in objs){var obj=objs[id];var data=obj.__data;if(minormode<MERGE&&mode!=PICK){if((mode==RENDER||mode==RENDER_TEXTURE)&&obj.__tex.file!==null){if(obj.__tex.texture_ref.reference!==null){gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,obj.__tex.texture_ref.reference)}else continue}if((mode==RENDER||mode==RENDER_TEXTURE)&&obj.__tex.bumpmap!==null){if(obj.__tex.bumpmap_ref.reference!==null){gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,obj.__tex.bumpmap_ref.reference)}else continue}}if(mode==PICK){var falsecolor=obj.__falsecolor;for(var i=0;i<4;i++){save[i]=data[16+i];data[16+i]=falsecolor[i]}}gl.uniform4fv(program.uniforms.objectData,data);gl.drawElements(elements,model_length,gl.UNSIGNED_SHORT,0);if(mode==PICK){for(var i=0;i<4;i++)data[16+i]=save[i]}}}if(mode!=PICK){gl.bindRenderbuffer(gl.RENDERBUFFER,null);gl.bindFramebuffer(gl.FRAMEBUFFER,null)}}if(mode==RENDER){subrender(mode,null,[])}else if(mode==PICK){subrender(mode,"C0",[""])}else if(mode==EXTENT){subrender(mode,"EXTENT_TEXTURE",[])}else if(mode==RENDER_TEXTURE){subrender(PEEL_C0,"C0",[]);subrender(PEEL_D0,"D0",[]);subrender(PEEL_C1,"C1",["D0"]);if(fullpeels){subrender(PEEL_D1,"D1",["D0"]);subrender(PEEL_C2,"C2",["D0","D1"]);subrender(PEEL_D2,"D2",["D0","D1"]);subrender(PEEL_C3,"C3",["D0","D2"]);subrender(PEEL_D3,"D3",["D0","D2"]);subrender(PEEL_C4,"C4",["D0","D3"]);subrender(MERGE,null,["C0","C1","C2","C3","C4"])}else subrender(MERGE,null,["C0","C1"])}if(mode==EXTENT){gl.readPixels(0,0,1,1,gl.RGBA,gl.UNSIGNED_BYTE,pixels);var mantissa=(256*pixels[1]+pixels[2])/65536;var exponent=pixels[0];if(exponent>128){exponent=-(exponent-128);mantissa=-mantissa}var extent;if(mantissa==0&&exponent==0)extent=0;else extent=Math.exp(mantissa+exponent);return null}else if(mode==PICK){gl.readPixels(canvas.mouse.__pickx,canvas.mouse.__picky,1,1,gl.RGBA,gl.UNSIGNED_BYTE,pixels);var id=16777216*pixels[0]+65536*pixels[1]+256*pixels[2]+pixels[3];var obj=canvas.__visiblePrimitives[id];if(!obj)return null;else if(obj.__obj&&obj.__obj.pickable)return obj.__obj;else if(obj.constructor.name=="point"){if(!obj.__curve.pickable||!obj.pickable)return null;var pts=obj.__curve.__points;var L=pts.length;for(var i=0;i<L;i++){if(pts[i]===obj){obj=obj.__curve;obj.pick=i;obj.segment=i;return obj}}return null}if(!obj.pickable)return null;else return obj}};function trigger_render(){var doAverage=lastStartRedraw>0;var t=msclock();var elapsed=0;if(doAverage)elapsed=t-lastStartRedraw;lastStartRedraw=t;canvas.trigger("redraw",{dt:elapsed});renderer.render(RENDER);t=msclock();elapsed=0;if(doAverage)elapsed=t-lastEndRedraw;lastEndRedraw=t;if(doAverage){renderMS=renderMS*.95+(t-lastStartRedraw)*.05;fps=fps*.95+1e3/elapsed*.05}else{renderMS=t-lastStartRedraw;fps=0}var total=fps*renderMS;$("#fps").text(fps.toFixed(1)+" renders/s * "+renderMS.toFixed(1)+" ms/render = "+total.toFixed(1)+" ms rendering/s");canvas.trigger("draw_complete",{dt:elapsed});canvas.__last_forward=canvas.__forward;canvas.__last_range=canvas.__range;canvas.__last_up=canvas.__up;window.requestAnimFrame(trigger_render,canvasElement)}this.reset();trigger_render()}var desired_fps=60;var N=0;var enditers;function rate(iters,cb){if(cb===undefined)throw new Error("rate(iterations_per_second, wait) called without wait");if(N>0){N--;if(msclock()>enditers)N=0;if(N>0)cb();else{setTimeout(cb,Math.ceil(1e3/desired_fps))}}else{if(iters<=120){setTimeout(cb,Math.ceil(1e3/iters))}else{N=Math.ceil(iters/desired_fps);enditers=msclock()+Math.ceil(1e3/desired_fps);cb()}}}var exports={WebGLRenderer:WebGLRenderer,rate:rate};Export(exports)})();(function(){"use strict";function log10(val){return Math.log(val)/Math.LN10}var eformat=false;var nformat=0;var nmax=0;function format_number(val,axis){if(axis.ticks.length==0){var delta=axis.tickSize;var amin=axis.min,amax=axis.max;var nticks=Math.floor((amax-amin)/delta+.5)+1;var vmax,test;for(var i=0;i<nticks;i++){test=abs(amin+i*delta);if(vmax===undefined||test>vmax&&test!=0)vmax=test}nmax=Math.floor(log10(vmax))+1;var n=Math.floor(log10(delta))+1;if(n>3){eformat=true;nformat=n}else if(n>0){eformat=false;nformat=0}else if(n<0){eformat=true;nformat=n;if(nmax>=0){eformat=false;nformat=-n+1}}else{eformat=false;nformat=1}}if(val==0)return"0";if(eformat){var nf,nexp;var mantissa=val*pow(10,-nformat+1);nf=0;nexp=nformat-1;if(nmax>nformat){mantissa*=.1;nf+=1;nexp+=1}return mantissa.toFixed(nf)+"e"+nexp}else{return val.toFixed(nformat)}}function graph(options){if(!(this instanceof graph))return new graph(options);if(options===undefined)options={};this.graph_options={series:{shadowSize:0},crosshair:{mode:"xy",color:"rgba(0,0,0,1)"}};this.__width=640;this.__height=400;this.__title="";this.__plot=null;this.__xmin=this.__xmax=this.__ymin=this.__ymax=null;this.wrapper=$("<div/>");if(options.width!==undefined){this.__width=options.width;delete options.width}if(options.height!==undefined){this.__height=options.height;delete options.height}this.__align="none";if(options.align!==undefined){this.__align=options.align;delete options.align}this.graph_options.xaxis={min:null,max:null,tickFormatter:format_number};this.graph_options.yaxis={min:null,max:null,tickFormatter:format_number};if(options.title!==undefined){if(options.title!==null)this.__title=options.title;delete options.title}this.__foreground=color.black;this.__background=color.gray(.95);if(options.foreground!==undefined){var v=options.foreground;if(!(v instanceof vec))throw new Error("graph foreground must be a vector.");this.__foreground=v;delete options.foreground}if(options.background!==undefined){var v=options.background;if(!(v instanceof vec))throw new Error("graph background must be a vector.");this.__background=v;delete options.background}this.graph_options.grid={color:color.to_html(this.__foreground),backgroundColor:color.to_html(this.__background)};if(options.xmin!==undefined){this.__xmin=this.graph_options.xaxis.min=options.xmin;delete options.xmin}if(options.xmax!==undefined){this.__xmax=this.graph_options.xaxis.max=options.xmax;delete options.xmax}if(options.ymin!==undefined){this.__ymin=this.graph_options.yaxis.min=options.ymin;delete options.ymin}if(options.ymax!==undefined){this.__ymax=this.graph_options.yaxis.max=options.ymax;delete options.ymax}this.__logx=this.__logy=false;if(options.logx!==undefined){this.__logx=this.graph_options.logx=options.logx;delete options.logx}if(options.logy!==undefined){this.__logy=this.graph_options.logy=options.logy;delete options.logy}if(this.__logx){this.graph_options.xaxis.transform=function(v){return log10(v)};this.graph_options.xaxis.inverseTransform=function(v){return pow(10,v)}}if(this.__logy){this.graph_options.yaxis.transform=function(v){return log10(v)};this.graph_options.yaxis.inverseTransform=function(v){return pow(10,v)}}var err="",count=0;for(var attr in options){count+=1;err+=attr+", "}if(err.length>0){if(count==1)throw new Error(err.slice(0,err.length-2)+" is not an attribute of a graph");else throw new Error("These are not attributes of a graph: "+err.slice(0,err.length-2))}graph.selected=this;this.graph_series=[];this.__activated=false}property.declare(graph,{selected:{get:function(){return window.__context.graph_selected||null},set:function(value){window.__context.graph_selected=value}}});property.declare(graph.prototype,{__activate:function(){if(this.__activated)return;this.__activated=true;this.__activate=function(){};if(this.__title!==undefined&&this.__title.length>0)$("<div>"+this.__title+"</div>").appendTo(canvas.container);this.wrapper.addClass("glowscript-graph").css("width",this.__width).css("height",this.__height).appendTo(canvas.container);this.wrapper.css("float",this.__align);this.__update()},__update:function(){var self=this;window.requestAnimFrame(function(){self.__update.call(self)},this.wrapper.get(0));if(!this.changed)return;var info=[];for(var i=0;i<this.graph_series.length;i++){var thisseries=this.graph_series[i];if(thisseries.__visible){info.push(thisseries.options);if(thisseries.__dot&&thisseries.__type=="line"&&thisseries.options.data.length>0){var dotdisplay={points:{show:true}};if(thisseries.__dot_radius!==null)dotdisplay.points.radius=thisseries.__dot_radius;else dotdisplay.points.radius=thisseries.__width+1;if(thisseries.__dot_color!==null)dotdisplay.color=color.to_html(thisseries.__dot_color);else dotdisplay.color=color.to_html(thisseries.__color);dotdisplay.points.fillColor=dotdisplay.color;dotdisplay.data=[thisseries.options.data[thisseries.options.data.length-1]];info.push(dotdisplay)}}}this.changed=false;if(info.length==0)return;this.__plot=$.plot(this.wrapper,info,this.graph_options);this.__plot.draw()},add_to_graph:function(obj){this.graph_series.push(obj);if(obj.options.data.length>0)this.__activate()},changed:false,remove:function(){this.wrapper.remove()},width:{get:function(){return this.__width},set:function(value){this.__width=value;this.wrapper.css("width",value);var plot=$.plot(this.wrapper,[],this.graph_options);plot.resize();plot.setupGrid();this.changed=true}},height:{get:function(){return this.__height},set:function(value){this.__height=value;this.wrapper.css("height",value);var plot=$.plot(this.wrapper,[],this.graph_options);plot.resize();plot.setupGrid();this.changed=true}},align:{get:function(){return this.__align},set:function(value){if(value=="left"||value=="right"||value=="none"){this.__align=value}else throw new Error("align must be 'left', 'right', or 'none' (the default).")}},title:{get:function(){return this.__title},set:function(value){this.__title=value;this.changed=true}},xmin:{get:function(){return this.__xmin},set:function(value){this.__xmin=this.graph_options.xaxis.min=value;this.changed=true}},xmax:{get:function(){return this.__xmax},set:function(value){this.__xmax=this.graph_options.xaxis.max=value;this.changed=true}},ymin:{get:function(){return this.__ymin},set:function(value){this.__ymin=this.graph_options.yaxis.min=value;this.changed=true}},ymax:{get:function(){return this.__ymax},set:function(value){this.__ymax=this.graph_options.yaxis.max=value;this.changed=true}},logx:{get:function(){return this.__logx},set:function(value){if(this.__logx==value)return;if(value){this.graph_options.xaxis.transform=function(v){return log10(v)};this.graph_options.xaxis.inverseTransform=function(v){return pow(10,v)}}else{delete this.graph_options.xaxis.transform;delete this.graph_options.xaxis.inverseTransform}this.__logx=value;this.changed=true}},logy:{get:function(){return this.__logy},set:function(value){if(this.__logy==value)return;if(value){this.graph_options.yaxis.transform=function(v){return log10(v)};this.graph_options.yaxis.inverseTransform=function(v){return pow(10,v)}}else{delete this.graph_options.yaxis.transform;delete this.graph_options.yaxis.inverseTransform}this.__logy=value;this.changed=true}},foreground:{get:function(){return this.__foreground},set:function(value){if(!(value instanceof vec))throw new Error("graph foreground color must be a vector.");if(this.__foreground.equals(value))return;this.__foreground=value;this.graph_options.grid.color=color.to_html(value);this.changed=true}},background:{get:function(){return this.__background},set:function(value){if(!(value instanceof vec))throw new Error("graph background color must be a vector.");if(this.__background.equals(value))return;this.__background=value;this.graph_options.grid.backgroundColor=color.to_html(value);this.changed=true}}});var type_to_flot_type={line:"lines",scatter:"points",bar:"bars",__proto__:null};function gobject(options){if(options===undefined)options={data:[]};else if(options.data===undefined)options.data=[];this.__color=vec(0,0,0);this.__label=null;this.__delta=1;this.__width=1;this.__radius=3;this.__horizontal=false;this.__dot=false;this.__dot_color=null;this.__dot_radius=null;this.__data=[];this.__xmin=null;this.__xmax=null;this.__ymin=null;this.__ymax=null;this.__interval=-1;if(options.graph!==undefined){this.__graph=options.graph;delete options.graph}else if(options.gdisplay!==undefined){this.__graph=options.gdisplay;delete options.gdisplay}else{this.__graph=graph.selected;if(!this.__graph)this.__graph=graph()}this.__type="line";if(options.type!==undefined){this.__type=options.type;delete options.type}var ftype=this.__ftype=type_to_flot_type[this.__type];if(!ftype)throw new Error("Unknown series type: "+this.__type);this.options={};this.options.data=options.data;delete options.data;this.options[ftype]={show:true,align:"center",horizontal:false,barWidth:1};if(this.__type=="scatter")this.options.fill=1;else if(this.__type=="bar")this.options.fill=.5;else this.options.fill=0;if(options.horizontal!==undefined){this.__horizontal=this.options[ftype].horizontal=options.horizontal;delete options.horizontal}if(options.delta!==undefined){this.__delta=this.options[ftype].barWidth=options.delta;delete options.delta}if(options.width!==undefined){this.__width=this.options[ftype].lineWidth=options.width;delete options.width}if(options.color!==undefined){var c=options.color;if(!(c instanceof vec))throw new Error("graph color must be a vector.");this.__color=c;delete options.color}this.options.color=color.to_html(this.__color);if(this.__type=="scatter")this.options[ftype].fillColor=this.options.color;else this.options.fillColor=this.options.color;if(options.radius!==undefined){this.__radius=this.options[ftype].radius=options.radius;delete options.radius}if(options.dot!==undefined){this.__dot=options.dot;delete options.dot}if(options.dot_color!==undefined){var v=options.dot_color;if(!(v instanceof vec))throw new Error("graph dot_color must be a vector.");this.__dot_color=v;delete options.dot_color}if(options.dot_radius!==undefined){this.__dot_radius=options.dot_radius;delete options.dot_radius}if(options.label!==undefined){this.__label=this.options.label=options.label;delete options.label}if(options.interval!==undefined){this.__interval=options.interval;this.__ninterval=options.interval;delete options.interval}if(this.options.data.length>0)this.__graph.changed=true;this.__visible=true;if(options.visible!==undefined){this.__visible=options.visible;delete options.visible}var err="",count=0;for(var attr in options){count+=1;err+=attr+", "}if(err.length>0){if(count==1)throw new Error(err.slice(0,err.length-2)+" is not an attribute of a series");else throw new Error("These are not attributes of a graph object: "+err.slice(0,err.length-2))}this.__graph.add_to_graph(this);this.remove=function(){this.__graph.changed=true;this.options.data=[]};var toType=function(obj){return{}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()};var resolveargs=function(args){var v,ret;ret=[];if(toType(arguments[0])=="array"){if(toType(arguments[0][0])!="array"){for(var i=0;i<arguments.length;i++){v=arguments[i];if(toType(v)=="array"&&v.length==2)ret.push(v);else return null}}else{for(var i=0;i<arguments[0].length;i++){v=arguments[0][i];if(toType(v)=="array"&&v.length==2)ret.push(v);else return null}}}else{if(arguments.length==2)return[[arguments[0],arguments[1]]];return null}return ret};var toType=function(obj){return{}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()};var resolveargs=function(args){var v,ret;ret=[];if(toType(arguments[0][0])!="array"){for(var i=0;i<arguments.length;i++){v=arguments[i];if(toType(v)=="array"&&v.length==2)ret.push(v);else return null}}else{for(var i=0;i<arguments[0].length;i++){v=arguments[0][i];if(toType(v)=="array"&&v.length==2)ret.push(v);else return null}}return ret};this.plot=function(args){if(this.__interval===0)return;var data;if(args.color!==undefined)throw new Error("Cannot currently change color in a plot statement.");if(args.pos!==undefined)data=resolveargs(args.pos);else if(toType(args)=="array"&&arguments.length==1)data=resolveargs(args);else{var a=[];for(var i=0;i<arguments.length;i++)a.push(arguments[i]);if(toType(a[0])=="array")data=resolveargs(a);else data=resolveargs([a])}if(data===null)throw new Error("Must be plot(x,y) or plot(pos=[x,y]) or plot([x,y]) or plot([x,y], ...) or plot([ [x,y], ... ])");else{if(this.__type!="line"){for(var i=0;i<data.length;i++){if(this.__interval>0){this.__ninterval++;if(this.__ninterval>=this.__interval)this.__ninterval=0;else continue}this.options.data.push(data[i])}}else{var pt,x,y,xscale,yscale,dx,dy,x1,x2,y1,y2;var g=this.__graph;var gxmin=g.__xmin;var gxmax=g.__xmax;var gymin=g.__ymin;var gymax=g.__ymax;if(this.options.data.length===0){pt=data[0];x=pt[0];y=pt[1];if(gxmin===null)this.__xmin=x;if(gxmax===null)this.__xmax=x;if(gymin===null)this.__ymin=y;if(gymax===null)this.__ymax=y;this.__lastx=1e300;this.__lasty=1e300}for(var i=0;i<data.length;i++){if(this.__interval>0){this.__ninterval++;if(this.__ninterval>=this.__interval)this.__ninterval=0;else continue}pt=data[i];x=pt[0];y=pt[1];if(gxmin===null&&x<this.__xmin)this.__xmin=x;if(gxmax===null&&x>this.__xmax)this.__xmax=x;if(gymin===null&&y>this.__ymin)this.__ymin=y;if(gymax===null&&y<this.__ymax)this.__ymax=y;x1=gxmin===null?this.__xmin:gxmin;x2=gxmax===null?this.__xmax:gxmax;y1=gymin===null?this.__ymin:gymin;y2=gymax===null?this.__ymax:gymax;xscale=g.__width/(x2-x1);yscale=g.__height/(y2-y1);dx=xscale*Math.abs(x-this.__lastx);dy=yscale*Math.abs(y-this.__lasty);if(dx<2&&dy<2)continue;this.__lastx=x;this.__lasty=y;this.options.data.push(pt)}}}this.__graph.changed=true;this.__graph.__activate()}}property.declare(gobject.prototype,{graph:{get:function(){return this.__graph},set:function(value){this.__graph.changed=true;this.__graph.graph_series.splice(this.__graph.graph_series.indexOf(this),1);this.__graph=value;this.__graph.add_to_graph(this);this.__graph.changed=true}},type:{get:function(){return this.__type},set:function(value){var oldftype=this.__ftype;var ftype=type_to_flot_type[value];if(!ftype)throw new Error("Unknown series type: "+value);if(ftype==oldftype)return;this.options[ftype]=this.options[oldftype];delete this.options[oldftype];if(value=="scatter"){this.options.fill=1;this.options[ftype].fillColor=this.options.color}else if(value=="bar"){this.options.fill=.5;this.options.fillColor=this.options.color}else{this.options.fill=0;this.options.fillColor=this.options.color}this.__type=value;this.__graph.changed=true}},color:{get:function(){return this.__color},set:function(value){if(!(value instanceof vec))throw new Error("graph color must be a vector.");if(this.__color.equals(value))return;this.__color=value;this.options.color=color.to_html(value);if(this.__type=="scatter")this.options[this.__ftype].fillColor=this.options.color;else this.options.fillColor=this.options.color;this.__graph.changed=true}},label:{get:function(){if(this.options.label===undefined)return"";return this.options.label},set:function(value){if(this.options.label==value)return;this.options.label=value;this.__graph.changed=true}},delta:{get:function(){return this.__delta},set:function(value){if(this.__delta==value)return;this.__delta=value;var ftype=type_to_flot_type[this.__type];this.options[ftype].barWidth=value;this.__graph.changed=true}},width:{get:function(){return this.__width},set:function(value){if(this.__width==value)return;this.__width=value;var ftype=type_to_flot_type[this.__type];this.options[ftype].lineWidth=value;this.__graph.changed=true}},radius:{get:function(){return this.__radius},set:function(value){if(this.__radius==value)return;this.__radius=value;var ftype=type_to_flot_type[this.__type];this.options[ftype].radius=value;this.__graph.changed=true}},size:{get:function(){return 2*this.__radius},set:function(value){if(2*this.__radius==value)return;this.__radius=value/2;var ftype=type_to_flot_type[this.__type];this.options[ftype].radius=value/2;this.__graph.changed=true}},horizontal:{get:function(){return this.__horizontal},set:function(value){if(this.__horizontal==value)return;this.__horizontal=value;var ftype=type_to_flot_type[this.__type];this.options[ftype].horizontal=value;this.__graph.changed=true}},dot:{get:function(){return this.__dot},set:function(value){if(this.__dot==value)return;this.__dot=value;this.__graph.changed=true}},dot_color:{get:function(){return this.__dot_color},set:function(value){if(!(value instanceof vec))throw new Error("graph dot_color must be a vector.");if(this.__dot_color.equals(value))return;this.__dot_color=value;this.__graph.changed=true}},dot_radius:{get:function(){return this.__dot_radius},set:function(value){if(this.__dot_radius==value)return;this.__dot_radius=value;this.__graph.changed=true}},visible:{get:function(){return this.__visible},set:function(value){if(this.__visible==value)return;this.__visible=value;this.__graph.changed=true}},data:{get:function(){return this.options.data},set:function(value){this.options.data=[];this.plot(value)}}});function series(options){return new gobject(options)}function vp_graph(options){if(options===undefined)return new graph;if(options.x!==undefined)delete options.x;if(options.y!==undefined)delete options.y;var title="",xtitle="",ytitle="";var indent="&nbsp&nbsp&nbsp&nbsp&nbsp";if(options.title!==undefined){if(options.title!==null)title=options.title;delete options.title}if(options.xtitle!==undefined){if(options.xtitle!==null)xtitle=options.xtitle;delete options.xtitle}if(options.ytitle!==undefined){if(options.ytitle!==null)ytitle=options.ytitle;delete options.ytitle}var t1="";var t2="";if(title.length>0&&(xtitle.length>0||ytitle.length>0))t1=title+"<br>";else if(title.length>0)t1=title;if(ytitle.length>0){t2=ytitle;if(xtitle.length>0)t2+=" vs "+xtitle}else if(xtitle.length>0)t2=xtitle;if(t1.length>0)t1=indent+t1;if(t2.length>0)options.title=t1+indent+t2;else if(t1.length>0)options.title=t1;return new graph(options)}function gcurve(options){if(options===undefined)options={};options.type="line";
  if(options.pos!==undefined){options.data=options.pos;delete options.pos}if(options.size!==undefined){options.dot_radius=options.size/2;delete options.size}else options.dot_radius=4;var ret=new gobject(options);ret.gcurve=ret;return ret}function gdots(options){if(options===undefined)options={};options.type="scatter";if(options.pos!==undefined){options.data=options.pos;delete options.pos}if(options.size!==undefined){options.radius=options.size/2;delete options.size}else options.radius=2.6;var ret=new gobject(options);ret.dots=ret;return ret}function gvbars(options){if(options===undefined)options={};options.type="bar";if(options.pos!==undefined){options.data=options.pos;delete options.pos}return new gobject(options)}function ghbars(options){if(options===undefined)options={};options.type="bar";options.horizontal=true;if(options.pos!==undefined){options.data=options.pos;delete options.pos}return new gobject(options)}function ghistogram(options){throw new Error("ghistogram is not implemented in GlowScript.")}var exports={graph:graph,series:series,gdisplay:vp_graph,vp_graph:vp_graph,gcurve:gcurve,gdots:gdots,gvbars:gvbars,ghbars:ghbars};Export(exports)})();(function(){"use strict";var color={red:vec(1,0,0),green:vec(0,1,0),blue:vec(0,0,1),yellow:vec(1,1,0),orange:vec(1,.6,0),cyan:vec(0,1,1),magenta:vec(1,0,1),white:vec(1,1,1),black:vec(0,0,0),gray:function(g){return vec(g,g,g)},hsv_to_rgb:function(hsv){var h=hsv.x;var s=hsv.y;var v=hsv.z;if(s==0){return vec(v,v,v)}var i=Math.floor(6*h);var f=6*h-i;var p=v*(1-s);var q=v*(1-s*f);var t=v*(1-s*(1-f));var i=i%6;switch(i){case 0:return vec(v,t,p);case 1:return vec(q,v,p);case 2:return vec(p,v,t);case 3:return vec(p,q,v);case 4:return vec(t,p,v);case 5:return vec(v,p,q)}},rgb_to_hsv:function(rgb){var r=rgb.x;var g=rgb.y;var b=rgb.z;var maxc=Math.max(r,g,b);var minc=Math.min(r,g,b);var v=maxc;if(minc==maxc){return vec(0,0,v)}var s=(maxc-minc)/maxc;var rc=(maxc-r)/(maxc-minc);var gc=(maxc-g)/(maxc-minc);var bc=(maxc-b)/(maxc-minc);var h;if(r==maxc){h=bc-gc}else if(g==maxc){h=2+rc-bc}else{h=4+gc-rc}h=h/6;if(h<0)h++;return vec(h,s,v)},to_html:function(color){var r=Math.floor(255*color.x);var g=Math.floor(255*color.y);var b=Math.floor(255*color.z);return"rgb("+r+","+g+","+b+")"},to_html_rgba:function(color,opacity){var r=Math.floor(255*color.x);var g=Math.floor(255*color.y);var b=Math.floor(255*color.z);return"rgba("+r+","+g+","+b+","+opacity+")"}};var exports={color:color};Export(exports)})();(function(){"use strict";var npdefault=64;function shape_object(){}shape_object.prototype.roundc=function roundc(cps,args){var cp=[],i;for(i=0;i<cps.length;i++)cp.push(vec(cps[i][0],cps[i][1],0));args=args||{};var roundness=.1;var nseg=16;var invert=false;if(args.roundness!==undefined)roundness=args.roundness;if(args.nseg!==undefined)nseg=args.nseg;if(args.invert!==undefined)invert=args.invert;var dv,vord,p1,p2,lm,L,r,ncp,i1,i2,wrt,v1,v2,rax,afl,cc,ccp,tt,t1,t2,nc,dseg,a;vord=0;cp.pop();var lcp=cp.length;for(i=0;i<lcp;i++){i1=(i+1)%lcp;i2=(i+2)%lcp;v1=cp[i1].sub(cp[i]);v2=cp[i2].sub(cp[i1]);dv=cross(v1,v2).z;vord+=dv}if(vord<0)cp.reverse();L=1e200;for(i=0;i<lcp;i++){p1=cp[i];p2=cp[(i+1)%lcp];lm=mag(p2.sub(p1));if(lm<L){L=lm}}r=L*roundness;var d,dtheta;ncp=[[0,0]];for(i=0;i<lcp;i++){v1=cp[(i+1)%lcp].sub(cp[i%lcp]);v2=cp[(i+2)%lcp].sub(cp[(i+1)%lcp]);var theta=diff_angle(v1,v2);d=r*Math.tan(theta/2);p1=cp[i].add(v1.sub(norm(v1).multiply(d)));p2=cp[(i+1)%lcp].add(norm(v2).multiply(d));ncp.push([p1.x,p1.y]);var N=cross(norm(v1),norm(v2));var center=p1.add(norm(cross(N,v1)).multiply(r));var v=p1.sub(center);dtheta=theta/(nseg+1);if(N.z<0)dtheta=-dtheta;if(invert){var c=p1.add(p2).multiply(.5);center=c.add(c.sub(center));v=p1.sub(center);dtheta=-dtheta}for(var j=1;j<=nseg;j++){v1=center.add(v.rotate(j*dtheta));ncp.push([v1.x,v1.y])}ncp.push([p2.x,p2.y])}v1=cp[1].sub(cp[0]);v1=cp[0].add(norm(v1).multiply(d));ncp[0]=[v1.x,v1.y];return ncp};shape_object.prototype.rotatecp=function rotatecp(cp,pr,angle){var sinr,cosr,cpr,x,y,xRel,yRel,newx,newy,p;sinr=Math.sin(angle);cosr=Math.cos(angle);xRel=pr[0];yRel=pr[1];cpr=[];for(var i=0;i<cp.length;i++){p=cp[i];x=p[0];y=p[1];newx=x*cosr-y*sinr-xRel*cosr+yRel*sinr+xRel;newy=x*sinr+y*cosr-xRel*sinr-yRel*cosr+yRel;cpr.push([newx,newy])}return cpr};shape_object.prototype.scale=function scale(cp,xscale,yscale){var cpr,p;cpr=[];for(var i=0;i<cp.length;i++){p=cp[i];cpr.push([xscale*p[0],yscale*p[1]])}return cpr};shape_object.prototype.addpos=function addpos(pos,cp){var p;for(var i=0;i<cp.length;i++){p=cp[i];p[0]+=pos[0];p[1]+=pos[1]}return cp};shape_object.prototype.rframe=function rframe(args){args=args||{};if(args.thickness===undefined)args.thickness=null;if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=1;if(args.height===undefined)args.height=null;if(args.rotate===undefined)args.rotate=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.height===null){args.height=args.width}if(args.thickness===null)args.thickness=min(args.height,args.width)*.2;else args.thickness=min(args.height,args.width)*args.thickness*2;var outer,inner;outer=this.rectangle({pos:args.pos,width:args.width,height:args.height});inner=this.rectangle({pos:args.pos,width:args.width-args.thickness,height:args.height-args.thickness});if(args.rotate!==0){outer=this.rotatecp(outer,args.pos,args.rotate);inner=this.rotatecp(inner,args.pos,args.rotate)}if(args.xscale!==1||args.yscale!==1){outer=this.scale(outer,args.xscale,args.yscale);inner=this.scale(inner,args.xscale,args.yscale)}if(args.roundness>0){outer=this.roundc(outer,{roundness:args.roundness,invert:args.invert});inner=this.roundc(inner,{roundness:args.roundness,invert:args.invert})}return[outer,inner]};shape_object.prototype.rectangle=function rectangle(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=1;if(args.height===undefined)args.height=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var w2,h2,cp;if(args.height===null){args.height=args.width}if(args.thickness===0){cp=[];w2=args.width/2;h2=args.height/2;cp=[[w2,-h2],[w2,h2],[-w2,h2],[-w2,-h2],[w2,-h2]];cp=this.addpos(args.pos,cp);if(args.rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert})}else{cp=this.rframe(args)}return cp};shape_object.prototype.cross=function cross(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=1;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=.2;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var wtp,w2,t2,cp;wtp=(args.width+args.thickness)/2;w2=args.width/2;t2=args.thickness/2;cp=[[w2,-t2],[w2,t2],[t2,t2],[t2,w2],[-t2,w2],[-t2,t2],[-w2,t2],[-w2,-t2],[-t2,-t2],[-t2,-w2],[t2,-w2],[t2,-t2],[w2,-t2]];cp=this.addpos(args.pos,cp);if(rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert});return cp};shape_object.prototype.trframe=function trframe(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=2;if(args.height===undefined)args.height=1;if(args.top===undefined)args.top=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var angle,db,outer,inner;if(args.top===null){args.top=width/2}if(args.thickness===null){args.thickness=min(args.height,args.top)*.2}else{args.thickness=min(args.height,args.top)*args.thickness*2}outer=this.trapezoid({pos:args.pos,width:args.width,height:args.height,top:args.top});angle=Math.atan((args.width-args.top)/2/args.height);db=args.thickness/Math.cos(angle);inner=this.trapezoid({pos:args.pos,width:args.width-db-args.thickness*Math.tan(angle),height:args.height-args.thickness,top:args.top-(db-args.thickness*Math.tan(angle))});outer=this.addpos(args.pos,outer);inner=this.addpos(args.pos,inner);if(args.rotate!==0){outer=this.rotatecp(outer,args.pos,args.rotate);inner=this.rotatecp(inner,args.pos,args.rotate)}if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1){outer=this.scale(outer,args.xscale,args.yscale);inner=this.scale(inner,args.xscale,args.yscale)}if(args.roundness>0){outer=this.roundc(outer,{roundness:args.roundness,invert:args.invert});inner=this.roundc(inner,{roundness:args.roundness,invert:args.invert})}return[outer,inner]};shape_object.prototype.trapezoid=function trapezoid(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=2;if(args.height===undefined)args.height=1;if(args.top===undefined)args.top=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var w2,h2,t2,cp;w2=args.width/2;h2=args.height/2;if(args.top===null){args.top=w2}t2=args.top/2;if(args.thickness===0){cp=[[w2,-h2],[t2,h2],[-t2,h2],[-w2,-h2],[w2,-h2]];cp=this.addpos(args.pos,cp);if(args.rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert})}else{cp=this.trframe(args)}return cp};shape_object.prototype.circframe=function circframe(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.radius===undefined)args.radius=.5;if(args.iradius===undefined)args.iradius=null;if(args.np===undefined)args.np=npdefault;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.angle1===undefined)args.angle1=0;if(args.angle2===undefined)args.angle2=2*Math.PI;if(args.rotate===undefined)args.rotate=0;args.thickness=0;var outer,inner;if(args.iradius===null)args.iradius=args.radius*.8;outer=this.circle(args);if(args.angle1===0&&args.angle2==2*Math.PI){args.radius=args.iradius}else{var t=args.radius-args.iradius;var angle=(args.angle1+args.angle2)/2;var offset=t/Math.sin((args.angle2-args.angle1)/2);args.corner=[args.pos[0]+offset*Math.cos(angle),args.pos[1]+offset*Math.sin(angle)];var dangle=Math.asin(t/args.iradius);args.angle1=args.angle1+dangle;args.angle2=args.angle2-dangle;args.radius=args.iradius}inner=this.circle(args);if(args.rotate!==0){outer=this.rotatecp(outer,args.pos,args.rotate);inner=this.rotatecp(inner,args.pos,args.rotate)}if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1){outer=this.scale(outer,args.xscale,args.yscale);inner=this.scale(inner,args.xscale,args.yscale)}return[outer,inner]};shape_object.prototype.circle=function circle(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];var corner=args.pos;if(args.corner!==undefined)corner=args.corner;if(args.radius===undefined)args.radius=.5;if(args.np===undefined)args.np=npdefault;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.thickness===undefined)args.thickness=0;if(args.angle1===undefined)args.angle1=0;if(args.angle2===undefined)args.angle2=2*Math.PI;if(args.rotate===undefined)args.rotate=0;var seg,nseg,dc,ds,x0,y0,c2,s2,c,s,i,cp;cp=[];if(args.thickness>0){args.iradius=args.radius-args.radius*args.thickness;cp=this.circframe(args)}else{if(args.angle1!==0||args.angle2!==2*Math.PI){cp.push([corner[0],corner[1]])}seg=2*Math.PI/args.np;nseg=Math.floor(Math.abs((args.angle2-args.angle1)/seg+.5));seg=(args.angle2-args.angle1)/nseg;if(args.angle1!==0||args.angle2!==2*Math.PI){nseg+=1}c=args.radius*Math.cos(args.angle1);s=args.radius*Math.sin(args.angle1);dc=Math.cos(seg);ds=Math.sin(seg);x0=args.pos[0];y0=args.pos[1];cp.push([x0+c,y0+s]);for(i=0;i<nseg-1;i++){c2=c*dc-s*ds;s2=s*dc+c*ds;cp.push([x0+c2,y0+s2]);c=c2;s=s2}cp.push(cp[0]);if(args.rotate!==0&&(args.angle1!==0||args.angle2!==2*Math.PI)){cp=this.rotatecp(cp,args.pos,args.rotate)}if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale)}return cp};shape_object.prototype.arc=function arc(args){args=args||{};if(args.path===undefined)args.path=false;if(args.pos===undefined)args.pos=[0,0];if(args.radius===undefined)args.radius=.5;if(args.np===undefined)args.np=npdefault;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.thickness===undefined)args.thickness=null;if(args.angle1===undefined)args.angle1=0;if(args.angle2===undefined)args.angle2=2*Math.PI;if(args.rotate===undefined)args.rotate=0;if(args.path===undefined)args.path=false;var cpi,nseg,seg,x,y,i,p,cp;if(args.thickness===null){args.thickness=.01*args.radius}cp=[];cpi=[];seg=2*Math.PI/args.np;nseg=Math.floor(Math.abs(args.angle2-args.angle1)/seg)+1;seg=(args.angle2-args.angle1)/nseg;for(i=0;i<nseg+1;i++){x=Math.cos(args.angle1+i*seg);y=Math.sin(args.angle1+i*seg);cp.push([args.radius*x+args.pos[0],args.radius*y+args.pos[1]]);if(!args.path)cpi.push([(args.radius-args.thickness)*x+args.pos[0],(args.radius-args.thickness)*y+args.pos[1]])}if(!args.path){cpi.reverse();for(var i=0;i<cpi.length;i++)cp.push(cpi[i]);cp.push(cp[0])}if(args.rotate!==0)cp=rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)this.scale(cp,args.xscale,args.yscale);return cp};shape_object.prototype.ellipse=function ellipse(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=1;if(args.height===undefined)args.height=null;if(args.np===undefined)args.np=npdefault;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.thickness===undefined)args.thickness=0;if(args.angle1===undefined)args.angle1=0;if(args.angle2===undefined)args.angle2=2*Math.PI;if(args.rotate===undefined)args.rotate=0;if(args.height===null){args.height=.5*args.width}args.yscale*=args.height/args.width;args.radius=args.width;return this.circle(args)};shape_object.prototype.line=function line(args){args=args||{};if(args.path===undefined)path=args.path;if(args.pos===undefined)args.pos=[0,0];if(args.np===undefined)args.np=2;if(args.rotate===undefined)args.rotate=0;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.thickness===undefined)args.thickness=null;if(args.start===undefined)args.start=[0,0];if(args.end===undefined)args.end=[0,1];var v,dv,dx,dy,cpi,vline,mline,x,y,i,p,cp;v=vec(args.end[0]-args.start[0],args.end[1]-args.start[1],0);if(args.thickness===null)args.thickness=.01*mag(v);dv=args.thickness*norm(cross(vec(0,0,1),v));dx=dv.x;dy=dv.y;cp=[];cpi=[];var vstart=vec(args.start[0],args.start[1],0);v=vec(args.end[0]-args.start[0],args.end[1]-args.start[1],0);vline=v.divide(Math.floor(args.np-1));for(i=0;i<args.np;i++){x=args.start[0]+vline.multiply(i).x;y=args.start[1]+vline.multiply(i).y;cp.push([x+args.pos[0],y+args.pos[1]]);cpi.push([x+args.pos[0]+dx,y+args.pos[1]+dy])}cpi.reverse();for(var i=0;i<cpi.length;i++)cp.push(cpi[i]);cp.push(cp[0]);if(args.rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)this.scale(cp,args.xscale,args.yscale);return cp};shape_object.prototype.nframe=function nframe(args){args=args||{};if(args.thickness===undefined)args.thickness=0;if(args.pos===undefined)args.pos=[0,0];if(args.length===undefined)args.length=1;if(args.np===undefined)args.np=3;if(args.thickness===undefined)args.thickness=null;if(args.rotate===undefined)args.rotate=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var angle,length2,outer,inner;if(args.thickness===null){args.thickness=args.length*.1}else{args.thickness=args.length*args.thickness}outer=this.ngon({pos:args.pos,np:args.np,length:args.length});angle=Math.PI*(.5-1/args.np);length2=args.length-2*args.thickness/Math.tan(angle);inner=this.ngon({pos:args.pos,np:args.np,length:length2});if(args.rotate!==0){outer=this.rotatecp(outer,args.pos,args.rotate);inner=this.rotatecp(inner,args.pos,args.rotate)}if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1){outer=this.scale(outer,args.xscale,args.yscale);inner=this.scale(inner,args.xscale,args.yscale)}if(args.roundness>0){outer=this.roundc(outer,{roundness:args.roundness,invert:args.invert});inner=this.roundc(inner,{roundness:args.roundness,invert:args.invert})}return[outer,inner]};shape_object.prototype.ngon=function ngon(args){args=args||{};if(args.thickness===undefined)args.thickness=0;if(args.pos===undefined)args.pos=[0,0];if(args.length===undefined)args.length=1;if(args.rotate===undefined)args.rotate=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.np===undefined)args.np=3;var seg,x,y,angle,radius,i,cp;cp=[];if(args.np<3)throw Error("number of sides can not be less than 3");angle=2*Math.PI/args.np;radius=args.length/2/Math.sin(angle/2);if(args.thickness===0){seg=2*Math.PI/args.np;angle=0;for(i=0;i<args.np;i++){x=radius*Math.cos(angle)+args.pos[0];y=radius*Math.sin(angle)+args.pos[1];cp.push([x,y]);angle+=seg}cp.push(cp[0]);if(args.rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert})}else{cp=this.nframe(args)}return cp};shape_object.prototype.triangle=function triangle(args){args=args||{};if(args.rotate===undefined)args.rotate=0;args.np=3;args.rotate=args.rotate-Math.PI/6;return this.ngon(args)};shape_object.prototype.pentagon=function pentagon(args){args=args||{};if(args.rotate===undefined)args.rotate=0;args.np=5;args.rotate=args.rotate+Math.PI/10;return this.ngon(args)};shape_object.prototype.hexagon=function hexagon(args){args=args||{};if(args.rotate===undefined)args.rotate=0;args.np=6;return this.ngon(args)};shape_object.prototype.octagon=function octagon(args){args=args||{};if(args.rotate===undefined)args.rotate=0;args.np=8;args.rotate=args.rotate+Math.PI/8;return this.ngon(args)};shape_object.prototype.sframe=function sframe(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.radius===undefined)args.radius=1;if(args.n===undefined)args.n=5;if(args.iradius===undefined)args.iradius=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var outer,inner,cp;if(args.iradius===null){args.iradius=.5*args.radius}if(args.thickness===null){args.thickness=.2*args.radius}else{args.thickness=args.thickness*2*args.iradius}outer=this.star({pos:args.pos,n:args.n,radius:args.radius,iradius:args.iradius});inner=this.star({pos:args.pos,n:args.n,radius:args.radius-args.thickness,iradius:(args.radius-args.thickness)*args.iradius/args.radius});if(args.rotate!==0){outer=this.rotatecp(outer,args.pos,args.rotate);inner=this.rotatecp(inner,args.pos,args.rotate)}if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1){outer=this.scale(outer,args.xscale,args.yscale);inner=this.scale(inner,args.xscale,args.yscale)}if(args.roundness>0){outer=this.roundc(outer,{roundness:args.roundness,invert:args.invert});inner=this.roundc(inner,{roundness:args.roundness,invert:args.invert})}return[outer,inner]};shape_object.prototype.star=function star(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.radius===undefined)args.radius=1;if(args.n===undefined)args.n=5;if(args.iradius===undefined)args.iradius=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var dtheta,theta,i,cp;if(args.iradius===null)args.iradius=args.radius*.5;if(args.thickness===0){cp=[];dtheta=Math.PI/args.n;theta=0;for(i=0;i<2*args.n+1;i++){if(i%2===0){cp.push([-args.radius*Math.sin(theta),args.radius*Math.cos(theta)])}else{cp.push([-args.iradius*Math.sin(theta),args.iradius*Math.cos(theta)])}theta+=dtheta}cp=this.addpos(args.pos,cp);cp[cp.length-1]=cp[0];if(args.rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert})}else{cp=this.sframe(args)}return cp};shape_object.prototype.points=function points(args){args=args||{};var path=false;if(args.pos===undefined)args.pos=[];if(args.rotate===undefined)args.rotate=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.path===undefined)path=args.path;var closed,cp;cp=args.pos;closed=cp[cp.length-1][0]===cp[0][0]&&cp[cp.length-1][1]===cp[0][1];if(!closed&&!path)cp.push(cp[0]);if(cp.length&&args.rotate!==0)cp=this.rotatecp(cp,cp[0],args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert});return cp};shape_object.prototype.ToothOutline=function ToothOutline(args){args=args||{};if(args.n===undefined)args.n=30;if(args.res===undefined)args.res=1;if(args.phi===undefined)args.phi=20;if(args.radius===undefined)args.radius=50;if(args.addendum===undefined)args.addendum=.4;if(args.dedendum===undefined)args.dedendum=.5;if(args.fradius===undefined)args.fradius=.1;if(args.bevel===undefined)args.bevel=.05;var TOOTHGEO,R,DiametralPitch,ToothThickness,CircularPitch,U1,U2,ThetaA1,ThetaA2,ThetaA3;var A,pts,normals,i,Aw,r,u,xp,yp,auxth,m,rA,xc,yc,P0,Ra,th,N,P,V;TOOTHGEO={PitchRadius:args.radius,TeethN:args.n,PressureAng:args.phi,Addendum:args.addendum,Dedendum:args.dedendum,Fillet:args.fradius,Bevel:args.bevel,Resolution:args.res};R={Bottom:TOOTHGEO["PitchRadius"]-TOOTHGEO["Dedendum"]-TOOTHGEO["Fillet"],Ded:TOOTHGEO["PitchRadius"]-TOOTHGEO["Dedendum"],Base:TOOTHGEO["PitchRadius"]*cos(TOOTHGEO["PressureAng"]*Math.PI/180),Bevel:TOOTHGEO["PitchRadius"]+TOOTHGEO["Addendum"]-TOOTHGEO["Bevel"],Add:TOOTHGEO["PitchRadius"]+TOOTHGEO["Addendum"]};DiametralPitch=TOOTHGEO["TeethN"]/(2*TOOTHGEO["PitchRadius"]);ToothThickness=Math.PI/2/DiametralPitch;CircularPitch=Math.PI/DiametralPitch;U1=sqrt((1-Math.cos(TOOTHGEO["PressureAng"]*Math.PI/1800))/Math.cos(TOOTHGEO["PressureAng"]*Math.PI/180));U2=sqrt(R["Bevel"]*R["Bevel"]/(R["Ded"]*R["Ded"])-1);ThetaA1=Math.atan((sin(U1)-U1*Math.cos(U1))/(Math.cos(U1)+U1*Math.sin(U1)));ThetaA2=Math.atan((sin(U2)-U2*Math.cos(U2))/(Math.cos(U2)+U2*Math.sin(U2)));ThetaA3=ThetaA1+ToothThickness/(TOOTHGEO["PitchRadius"]*2);A={Theta0:CircularPitch/(TOOTHGEO["PitchRadius"]*2),Theta1:ThetaA3+TOOTHGEO["Fillet"]/R["Ded"],Theta2:ThetaA3,Theta3:ThetaA3-ThetaA2,Theta4:ThetaA3-ThetaA2-TOOTHGEO["Bevel"]/R["Add"]};N=TOOTHGEO["Resolution"];pts=[];normals=[];for(i=0;i<2*N;i++){th=(A["Theta1"]-A["Theta0"])*i/(2*N-1)+A["Theta0"];pts.push([R["Bottom"]*Math.cos(th),R["Bottom"]*Math.sin(th)]);normals.push([-Math.cos(th),-Math.sin(th)])}xc=R["Ded"]*Math.cos(A["Theta1"]);yc=R["Ded"]*Math.sin(A["Theta1"]);Aw=Math.PI/2+A["Theta2"]-A["Theta1"];for(i=0;i<N;i++){th=Aw*(i+1)/N+Math.PI+A["Theta1"];pts.push([xc+TOOTHGEO["Fillet"]*Math.cos(th),yc+TOOTHGEO["Fillet"]*Math.sin(th)]);normals.push([Math.cos(th),Math.sin(th)])}for(i=0;i<N;i++){r=(R["Base"]-R["Ded"])*(i+1)/N+R["Ded"];pts.push([r*Math.cos(A["Theta2"]),r*Math.sin(A["Theta2"])]);normals.push([Math.cos(A["Theta2"]-Math.PI/2),Math.sin(A["Theta2"]-Math.PI/2)])}for(i=0;i<3*N;i++){r=(R["Bevel"]-R["Base"])*(i+1)/(3*N)+R["Base"];u=Math.sqrt(r*r/(R["Base"]*R["Base"])-1);xp=R["Base"]*(Math.cos(u)+u*Math.sin(u));yp=-R["Base"]*(Math.sin(u)-u*Math.cos(u));pts.push([xp*Math.cos(A["Theta2"])-yp*Math.sin(A["Theta2"]),xp*Math.sin(A["Theta2"])+yp*Math.cos(A["Theta2"])]);normals.push([-Math.sin(u),-Math.cos(u)])}auxth=-u;auxth=auxth+ThetaA3+Math.PI/2;m=Math.tan(auxth);P0=pts[pts.length-1];rA=TOOTHGEO["Bevel"]/(1-Math.cos(auxth-A["Theta4"]));xc=P0[0]-rA*Math.cos(auxth);yc=P0[1]-rA*Math.sin(auxth);for(i=0;i<N;i++){th=(A["Theta4"]-auxth)*(i+1)/N+auxth;pts.push([xc+rA*Math.cos(th),yc+rA*Math.sin(th)]);normals.push([-Math.cos(th),-Math.sin(th)])}P0=pts[pts.length-1];A["Theta4"]=Math.atan(P0[1]/P0[0]);Ra=Math.sqrt(P0[0]*P0[0]+P0[1]*P0[1]);for(i=0;i<N;i++){th=-A["Theta4"]*(i+1)/N+A["Theta4"];pts.push([Ra*Math.cos(th),Ra*Math.sin(th)]);normals.push([-Math.cos(th),-Math.sin(th)])}N=pts.length;for(i=0;i<N-1;i++){P=pts[N-2-i];pts.push([P[0],-P[1]]);V=normals[N-2-i];normals.push([V[0],-V[1]])}return pts};shape_object.prototype.RackOutline=function RackOutline(args){args=args||{};if(args.n===undefined)args.n=30;if(args.res===undefined)args.res=1;if(args.phi===undefined)args.phi=20;if(args.radius===undefined)args.radius=5;if(args.addendum===undefined)args.addendum=.4;if(args.dedendum===undefined)args.dedendum=.5;if(args.fradius===undefined)args.fradius=.1;if(args.bevel===undefined)args.bevel=.05;var TOOTHGEO,X,DiametralPitch,ToothThickness,CircularPitch,Pa,yA1,yA2,yA3,A;var pts,normals,ist,i,Aw,Xded,x,rA,xc,yc,th,y,N,P,V;TOOTHGEO={PitchRadius:args.radius,TeethN:args.n,PressureAng:args.phi,Addendum:args.addendum,Dedendum:args.dedendum,Fillet:args.fradius,Bevel:args.bevel,Resolution:args.res};X={Bottom:-TOOTHGEO["Dedendum"]-TOOTHGEO["Fillet"],Ded:-TOOTHGEO["Dedendum"],Bevel:TOOTHGEO["Addendum"]-TOOTHGEO["Bevel"],Add:TOOTHGEO["Addendum"]};DiametralPitch=TOOTHGEO["TeethN"]/(2*TOOTHGEO["PitchRadius"]);ToothThickness=Math.PI/2/DiametralPitch;CircularPitch=Math.PI/DiametralPitch;Pa=TOOTHGEO["PressureAng"]*Math.PI/180;yA1=ToothThickness/2;yA2=(-X["Ded"]+TOOTHGEO["Fillet"]*Math.sin(Pa))*Math.tan(Pa);yA3=TOOTHGEO["Fillet"]*Math.cos(Pa);A={y0:CircularPitch/2,y1:yA1+yA2+yA3,y2:yA1+yA2,y3:yA1-(X["Add"]-TOOTHGEO["Bevel"])*Math.tan(Pa),y4:yA1-(X["Add"]-TOOTHGEO["Bevel"])*Math.tan(Pa)-cos(Pa)/(1-Math.sin(Pa))*TOOTHGEO["Bevel"]};N=TOOTHGEO["Resolution"];pts=[];normals=[];ist=0;if(args.fradius){ist=1}for(i=ist;i<2*N;i++){y=(A["y1"]-A["y0"])*i/(2*N-1)+A["y0"];pts.push([X["Bottom"],y]);normals.push([-1,-0])}xc=X["Ded"];yc=A["y1"];Aw=Math.PI/2-Pa;for(i=0;i<N;i++){th=Aw*(i+1)/N+Math.PI;pts.push([xc+TOOTHGEO["Fillet"]*Math.cos(th),yc+TOOTHGEO["Fillet"]*Math.sin(th)]);normals.push([Math.cos(th),Math.sin(th)])}Xded=X["Ded"]-TOOTHGEO["Fillet"]*Math.sin(Pa);for(i=0;i<4*N;i++){x=(X["Bevel"]-Xded)*(i+1)/(4*N)+Xded;pts.push([x,yA1-Math.tan(Pa)*x]);normals.push([-Math.sin(Pa),-Math.cos(Pa)])}rA=TOOTHGEO["Bevel"]/(1-Math.sin(Pa));xc=X["Add"]-rA;yc=A["y4"];for(i=0;i<N;i++){th=(-Math.PI/2+Pa)*(i+1)/N+Math.PI/2-Pa;pts.push([xc+rA*Math.cos(th),yc+rA*Math.sin(th)]);normals.push([-Math.cos(th),-Math.sin(th)])}for(i=0;i<N;i++){y=-A["y4"]*(i+1)/N+A["y4"];pts.push([X["Add"],y]);normals.push([-1,0])}N=pts.length;for(i=0;i<N-1;i++){P=pts[N-2-i];pts.push([P[0],-P[1]]);V=normals[N-2-i];normals.push([V[0],-V[1]])}return pts};shape_object.prototype.gear=function gear(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.n===undefined)args.n=20;if(args.radius===undefined)args.radius=1;if(args.phi===undefined)args.phi=20;if(args.addendum===undefined)args.addendum=.08*args.radius;if(args.dedendum===undefined)args.dedendum=.1*args.radius;if(args.fradius===undefined)args.fradius=.02*args.radius;if(args.rotate===undefined)args.rotate=0;if(args.scale===undefined)args.scale=1;if(args.res===undefined)args.res=1;var bevel=0;if(args.bevel!==undefined)bevel=args.bevel;var itooth,px,py,rad,driro,ir,ro,ix,iy,p,tooth,rotan,rtooth,rx,ry,x,y,i,gear,outer;var lastx=1e4,lasty=1e4;args.bevel=0;tooth=this.ToothOutline(args);args.bevel=bevel;gear=[];for(i=0;i<args.n;i++){rotan=-i*2*Math.PI/args.n;rtooth=[];for(var j=0;j<tooth.length;j++){p=tooth[j];x=p[0];y=p[1];rx=x*Math.cos(rotan)-y*Math.sin(rotan)+args.pos[0];ry=x*Math.sin(rotan)+y*Math.cos(rotan)+args.pos[1];rtooth.push([rx,ry])}gear=gear.concat(rtooth)}if(args.scale!==1)gear=this.scale(gear,args.scale,args.scale);if(args.rotate!==0)gear=this.rotatecp(gear,args.pos,args.rotate);var pts=[];var g1,g2,g3;for(var i=0;i<gear.length;i++){g1=gear[i];pts.push(g1);if(i==gear.length-1)break;g2=gear[i+1];if(i<gear.length-2){g3=gear[i+2];if(Math.abs(g3[0]-g1[0])<.001*args.radius&&Math.abs(g3[1]-g1[1])<.001*args.radius)i+=2;g2=gear[i];if(g1[0]===g2[0]&&g1[1]===g2[1])i++;continue}if(g1[0]===g2[0]&&g1[1]===g2[1]){i++;continue}}return pts};shape_object.prototype.rackgear=function rackgear(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.n===undefined)args.n=30;if(args.radius===undefined)args.radius=5;if(args.phi===undefined)args.phi=20;if(args.addendum===undefined)args.addendum=.08*args.radius;if(args.dedendum===undefined)args.dedendum=.1*args.radius;if(args.fradius===undefined)args.fradius=.02*args.radius;if(args.rotate===undefined)args.rotate=0;if(args.scale===undefined)args.scale=1;if(args.length===undefined)args.length=10*Math.PI;if(args.res===undefined)args.res=1;if(args.bevel===undefined)args.bevel=.05;if(args.depth===undefined)args.depth=.4+.6+.1;var tooth,toothl,nt,flength,gear,ntooth,nx,ny,i;var x,y,left,right,bottom,top,g,center,dx,dy,gear2,p;var lastx=1e4,lasty=1e4;tooth=this.RackOutline(args);toothl=tooth[0][1]-tooth[tooth.length-1][1];nt=Math.floor(args.length/toothl);flength=nt*toothl;gear=[];for(i=0;i<nt;i++){ntooth=[];for(var j=0;j<tooth.length;j++){p=tooth[j];x=p[0];y=p[1];if(x==lastx||y==lasty)continue;nx=x+args.pos[0];ny=-i*toothl+y+args.pos[1];ntooth.push([nx,ny]);lastx=x;lasty=y}gear=gear.concat(ntooth)}gear.push([gear[gear.length-1][0]-args.depth,gear[gear.length-1][1]]);gear.push([gear[0][0]-args.depth,gear[0][1]]);gear.push(gear[0]);left=1e3;right=-1e3;bottom=1e3;top=-1e3;for(i=0;i<gear.length;i++){g=gear[i];x=g[0];y=g[1];if(x<left)left=x;if(x>right)right=x;if(y<bottom)bottom=y;if(y>top)top=y}center=[(left+right)/2,(bottom+top)/2];dx=args.pos[0]-center[0];dy=args.pos[1]-center[1];gear2=[];for(i=0;i<gear.length;i++){
  g=gear[i];gear2.push([g[0]+dx,g[1]+dy])}if(args.scale!==1)gear2=this.scale(gear2,args.scale,args.scale);if(args.rotate!==0)gear2=this.rotate(gear2,args.pos,args.rotate);return gear2};function path_object(){}path_object.prototype.convert=function convert(args){args=args||{};if(args.pos===undefined)args.pos=vec(0,0,0);if(args.up===undefined)args.up=vec(0,1,0);if(args.pts===undefined)args.pts=null;if(args.closed===undefined)args.closed=true;var up0,angle,reorient,axis,p,newpt,pt,i;args.up=norm(args.up);up0=vec(0,1,0);angle=Math.acos(args.up.dot(up0));reorient=angle>0;axis=up0.cross(args.up);p=[];for(i=0;i<args.pts.length;i++){pt=args.pts[i];newpt=vec(pt[0],0,0-pt[1]);if(reorient)newpt=newpt.rotate({angle:angle,axis:axis});p.push(args.pos.add(newpt))}if(closed&&!p[p.length-1].equals(p[0])){p.push(pts[0])}return p};path_object.prototype.setuppath=function setuppath(args){args.path=true;var pos;if(args.pos===undefined){pos=vec(0,0,0)}else{pos=args.pos;if(pos.x===undefined)throw new Error("The pos attribute of a path must be a vector.");delete args.pos}return pos};path_object.prototype.rectangle=function rectangle(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in a rectangular path");var pos=this.setuppath(args);var c=shapes.rectangle(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.cross=function cross(args){args=args||{};var pos=this.setuppath(args);var c=shapes.cross(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.trapezoid=function trapezoid(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in a trapezoid path");var pos=this.setuppath(args);var c=shapes.trapezoid(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.circle=function circle(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in a circle path");var pos=this.setuppath(args);var c=shapes.circle(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.line=function line(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in a line path");if(args.np===undefined)args.np=2;if(args.rotate===undefined)args.rotate=0;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.start===undefined)args.start=vec(0,0,0);if(args.end===undefined)args.end=vec(0,0,-.1);var v,vline,i;var cp=[args.start];v=args.end.sub(args.start);vline=v.divide(Math.floor(args.np-1));for(i=1;i<args.np;i++){cp.push(args.start.add(vline));vline=vline.add(vline)}return cp};path_object.prototype.arc=function arc(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in an arc path");args.path=true;var pos=this.setuppath(args);var c=shapes.arc(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.ellipse=function ellipse(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in an ellipse path");var pos=this.setuppath(args);var c=shapes.ellipse(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.ngon=function ngon(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in an ngon path");var pos=this.setuppath(args);var c=shapes.ngon(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.triangle=function triangle(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in a pentagon path");var pos=this.setuppath(args);var c=shapes.triangle(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.pentagon=function pentagon(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in a triangle path");var pos=this.setuppath(args);var c=shapes.pentagon(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.hexagon=function hexagon(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in a hexagon path");var pos=this.setuppath(args);var c=shapes.hexagon(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.octagon=function octagon(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in an octagon path");var pos=this.setuppath(args);var c=shapes.octagon(args);return this.convert({pos:pos,up:args.up,pts:c})};path_object.prototype.star=function star(args){args=args||{};if(args.thickness!==undefined)throw Error("Thickness is not allowed in a star path");var pos=this.setuppath(args);var c=shapes.star(args);return this.convert({pos:pos,up:args.up,pts:c})};var paths=new path_object;var shapes=new shape_object;var exports={paths:paths,shapes:shapes};Export(exports)})();(function(){window.__adjustupaxis=true;function subclass(sub,base){sub.prototype=new base({visible:false,canvas:null});sub.prototype.constructor=sub}function id_to_falsecolor(N){var R=0,G=0,B=0;if(N>=16777216){R=Math.floor(N/16777216);N-=R*16777216}if(N>=65536){G=Math.floor(N/65536);N-=G*65536}if(N>=256){B=Math.floor(N/256);N-=B*256}return[R/255,G/255,B/255,N/255]}function init(obj,args){if(window.__GSlang=="vpython"&&args.display!==undefined){args.canvas=args.display;delete args.display}if(args.canvas!==undefined){obj.canvas=args.canvas;delete args.canvas}else{obj.canvas=canvas.selected}if(obj.canvas){obj.canvas.__activate();obj.__model=obj.__get_model()}if(args.__obj){obj.__obj=args.__obj;delete args.__obj}if(args.radius!==undefined){obj.radius=args.radius;delete args.radius}if(args.size_units!==undefined){obj.size_units=args.size_units;delete args.size_units}if(args.axis!==undefined){if(args.axis.mag2===0)obj.__oldaxis=vec(1,0,0);obj.axis=args.axis;delete args.axis}if(args.size!==undefined){obj.size=args.size;delete args.size}if(args.up!==undefined){if(args.up.mag2===0)obj.__oldup=vec(0,1,0);obj.up=args.up;delete args.up}if(args.color!==undefined){obj.color=args.color;delete args.color}obj.__interval=-1;if(obj.constructor!=curve&&obj.constructor!=points&&args.make_trail!==undefined){obj.__make_trail=args.make_trail;delete args.make_trail;obj.__trail_type="curve";if(args.trail_type!==undefined){if(args.trail_type!="curve"&&args.trail_type!="points"&&args.trail_type!="spheres")throw new Error("trail_type = "+args.trail_type+" but must be 'curve' or 'points' (or 'spheres').");obj.__trail_type=args.trail_type;delete args.trail_type}if(args.interval!==undefined){obj.__interval=args.interval;delete args.interval}else if(obj.__trail_type!="curve"){obj.__interval=1}if(args.retain!==undefined){obj.__retain=args.retain;delete args.retain}else obj.__retain=-1;obj.__trail_color=color.white;if(obj.color!==undefined)obj.__trail_color=obj.color;if(args.trail_color!==undefined){obj.__trail_color=args.trail_color;delete args.trail_color}obj.__trail_radius=0;if(args.trail_radius!==undefined){obj.__trail_radius=args.trail_radius;delete args.trail_radius}else{if(obj.__trail_type=="points")obj.__trail_radius=.1*obj.__size.y}obj.__pps=0;if(args.pps!==undefined){if(obj.__interval>0){if(obj.__trail_type!="curve")throw new Error("pps cannot be used with a "+obj.__trail_type+"-type trail");else throw new Error("pps cannot be used with interval > 0")}obj.__pps=args.pps;delete args.pps}obj.__trail_object=attach_trail(obj,{type:obj.__trail_type,color:obj.__trail_color,radius:obj.__trail_radius,pps:obj.__pps,retain:obj.__retain});if(args.pos!==undefined&&obj.__make_trail)obj.__trail_object.__trail.push(args.pos);if(!obj.__make_trail)obj.__trail_object.stop();obj.__ninterval=0}obj._pos_set=args.pos!==undefined;for(var id in args)obj[id]=args[id];if(args.visible===undefined&&obj.canvas!==null)obj.visible=true}function initObject(obj,constructor,args){if(!(obj instanceof constructor))return new constructor(args);args=args||{};obj.__tex={file:null,bumpmap:null,texture_ref:{reference:null},bumpmap_ref:{reference:null},left:false,right:false,sides:false,flipx:false,flipy:false,turn:0,flags:0};if(constructor!=curve&&constructor!=points){if(args.pos===undefined)obj.pos=obj.pos}if(args.color===undefined)obj.color=obj.color;if(constructor==curve)obj.origin=obj.origin;if(constructor!=points&&constructor!=text){if(constructor==arrow){if(args.axis!==undefined)throw new Error("arrow does not have axis; replace with axis_and_length");else if(args.axis_and_length===undefined)obj.axis_and_length=obj.axis_and_length}else if(constructor==vp_arrow&&args.axis_and_length!==undefined){throw new Error("VPython arrow does not have axis_and_length; replace with axis")}else if(args.axis===undefined)obj.axis=obj.axis;if(args.up===undefined)obj.up=obj.up;if(args.size===undefined)obj.size=obj.size}obj.__sizing=false;if(window.__GSlang=="vpython"&&!(constructor==vp_sphere||constructor==vp_ring))obj.__sizing=true;if(args.opacity===undefined)obj.__opacity=1;if(args.make_trail===undefined)obj.__make_trail=false;obj.__opacity_change=true;init(obj,args)}var nextVisibleId=1;var textures={flower:":flower_texture.jpg",granite:":granite_texture.jpg",gravel:":gravel_texture.jpg",earth:":earth_texture.jpg",metal:":metal_texture.jpg",rock:":rock_texture.jpg",rough:":rough_texture.jpg",rug:":rug_texture.jpg",stones:":stones_texture.jpg",stucco:":stucco_texture.jpg",wood:":wood_texture.jpg",wood_old:":wood_old_texture.jpg"};var bumpmaps={gravel:":gravel_bumpmap.jpg",rock:":rock_bumpmap.jpg",stones:":stones_bumpmap.jpg",stucco:":stucco_bumpmap.jpg",wood_old:":wood_old_bumpmap.jpg"};function setup_texture(name,obj,isbump){if(name.slice(0,1)==":"){var jv=window.Jupyter_VPython;if(jv!==undefined){name=jv+name.slice(1)}else{if(navigator.onLine)name="https://s3.amazonaws.com/glowscript/textures/"+name.slice(1);else name="../lib/FilesInAWS/"+name.slice(1)}}obj.canvas.__renderer.initTexture(name,obj,isbump)}function Primitive(){}property.declare(Primitive.prototype,{__id:null,__hasPosAtCenter:false,__deleted:false,__zx_camera:null,__zy_camera:null,__xmin:null,__ymin:null,__zmin:null,__xmax:null,__ymax:null,__zmax:null,pos:new attributeVectorPos(null,0,0,0),color:new attributeVector(null,1,1,1),axis:new attributeVectorAxis(null,1,0,0),size:new attributeVector(null,1,1,1),up:new attributeVectorUp(null,0,1,0),opacity:{get:function(){return this.__opacity},set:function(value){if(value==this.__opacity)return;if(this.__opacity<1&&value==1||this.__opacity==1&&value<1){this.__opacity_change=true}this.__opacity=value;this.__change()}},x:{get:function(){throw new Error('"object.x" is not supported; perhaps you meant "object.pos.x"')},set:function(value){throw new Error('"object.x" is not supported; perhaps you meant "object.pos.x"')}},y:{get:function(){throw new Error('"object.y" is not supported; perhaps you meant "object.pos.y"')},set:function(value){throw new Error('"object.y" is not supported; perhaps you meant "object.pos.y"')}},z:{get:function(){throw new Error('"object.z" is not supported; perhaps you meant "object.pos.z"')},set:function(value){throw new Error('"object.z" is not supported; perhaps you meant "object.pos.z"')}},__opacity_change:false,__prev_opacity:null,shininess:{value:.6,onchanged:function(){this.__change()}},emissive:{value:false,onchanged:function(){this.__change()}},pickable:{value:true,onchanged:function(){this.__change()}},ready:{get:function(){return this.__tex.file===null||this.__tex.texture_ref.reference!==null&&this.__tex.bumpmap===null||this.__tex.bumpmap_ref.reference!==null}},make_trail:{get:function(){return this.__make_trail},set:function(value){if(this.__make_trail!==value){if(value){this.__trail_object.start();this.__trail_object.__trail.push(this.__pos)}else this.__trail_object.stop();this.__make_trail=value}}},retain:{get:function(){return this.__retain},set:function(value){this.__retain=value;if(this.__trail_object!==undefined)this.__trail_object.retain=value}},trail_type:{get:function(){if(this.__trail_type=="curve")return"curve";else if(this.__trail_type=="spheres")return"points";else return this.__trail_type},set:function(value){throw new Error('"trail_type" cannot be changed.')}},trail_color:{get:function(){return this.__color},set:function(value){this.__trail_color=value;if(this.__trail_object!==undefined)this.__trail_object.color=value}},trail_radius:{get:function(){return this.__radius},set:function(value){this.__trail_radius=value;if(this.__trail_object!==undefined)this.__trail_object.radius=value}},pps:{get:function(){return this.__pps},set:function(value){this.__pps=value;if(this.__trail_object!==undefined)this.__trail_object.pps=value}},clear_trail:function(){if(this.__trail_object!==undefined)this.__trail_object.clear()},__update_trail:function(v){if(!this.__trail_object.__run||!this.visible)return;if(this.__interval===-1)return;this.__ninterval++;var update=false;if(this.__ninterval>=this.__interval){this.__ninterval=0;update=true}else if(this.__ninterval==1&&this.__trail_object.__trail.__points.length===0)update=true;if(update){if(this.__retain==-1)this.__trail_object.__trail.push({pos:v,color:this.__trail_color,radius:this.__trail_radius});else this.__trail_object.__trail.push({pos:v,color:this.__trail_color,radius:this.__trail_radius,retain:this.__retain})}},texture:{get:function(){return{file:this.__tex.file,bumpmap:this.__tex.bumpmap,left:this.__tex.left,right:this.__tex.right,sides:this.__tex.sides,flipx:this.__tex.flipx,flipy:this.__tex.flipy,turn:this.__tex.turn}},set:function(args){this.__tex={file:null,bumpmap:null,texture_ref:{reference:null},bumpmap_ref:{reference:null},left:false,right:false,sides:false,flipx:false,flipy:false,turn:0,flags:0};if(args===null){}else if(typeof args==="string"){this.__tex.left=this.__tex.right=this.__tex.sides=true;setup_texture(args,this,false)}else{if(args.file!==undefined&&typeof args.file==="string"){setup_texture(args.file,this,false)}else throw new Error("You must specify a file name for a texture.");if(args.bumpmap!==undefined){if(args.bumpmap!==null){if(typeof args.bumpmap!=="string")throw new Error("You must specify a file name for a bumpmap.");setup_texture(args.bumpmap,this,true)}}if(args.flipx!==undefined)this.__tex.flipx=args.flipx;if(args.flipy!==undefined)this.__tex.flipy=args.flipy;if(args.turn!==undefined)this.__tex.turn=Math.round(args.turn);if(args.place!==undefined){if(typeof args.place==="string")args.place=[args.place];for(var i=0;i<args.place.length;i++){switch(args.place[i]){case"left":this.__tex.left=true;break;case"right":this.__tex.right=true;break;case"sides":this.__tex.sides=true;break;case"ends":this.__tex.left=this.__tex.right=true;break;case"all":this.__tex.left=this.__tex.right=this.__tex.sides=true;break}}}else this.__tex.left=this.__tex.right=this.__tex.sides=true}this.__tex.flags=0;if(this.__tex.file!==null)this.__tex.flags+=1;if(this.__tex.bumpmap!==null)this.__tex.flags+=2;if(this.__tex.left)this.__tex.flags+=4;if(this.__tex.right)this.__tex.flags+=8;if(this.__tex.sides)this.__tex.flags+=16;if(this.__tex.flipx)this.__tex.flags+=32;if(this.__tex.flipy)this.__tex.flags+=64;var turns=this.__tex.turn%4;if(turns<0)turns+=4;this.__tex.flags+=128*turns;this.__change()}},visible:{get:function(){if(this.__obj)return this.__obj.__id!=null;if(this instanceof text)return this.__comp.__id!=null;else return this.__id!=null},set:function(value){if(this.__obj)return;var obj=this;if(value==(obj.__id!=null))return;if(obj.__deleted)return;if(obj.__curve)obj.__curve.visible=value;if(value){if(obj.constructor==vp_arrow||obj.constructor==arrow){if(!obj.__components)obj.__update();obj.__id=nextVisibleId;var fc;nextVisibleId++;for(var i=0;i<obj.__components.length;i++){var c=obj.__components[i];c.__id=nextVisibleId;if(i===0)fc=id_to_falsecolor(nextVisibleId);c.__falsecolor=fc;obj.canvas.__visiblePrimitives[nextVisibleId]=c;obj.canvas.__changed[nextVisibleId]=c;nextVisibleId++}}else{obj.__id=nextVisibleId;obj.__falsecolor=id_to_falsecolor(nextVisibleId);obj.canvas.__visiblePrimitives[nextVisibleId]=obj;obj.canvas.__changed[nextVisibleId]=obj;nextVisibleId++}if(obj instanceof extrusion){obj.__vis=value}}else{if(obj.constructor==vp_arrow||obj.constructor==arrow){for(var i=0;i<obj.__components.length;i++){var c=obj.__components[i];delete obj.canvas.__visiblePrimitives[c.__id];delete obj.canvas.__changed[c.__id];if(c.__model)delete c.__model.id_object[c.__id]}}else{delete obj.canvas.__visiblePrimitives[obj.__id];delete obj.canvas.__changed[obj.__id];if(obj.__model)delete obj.__model.id_object[obj.__id]}if(obj instanceof extrusion){obj.__vis=value}obj.__id=null}}},clone:function(args){if(this instanceof triangle||this instanceof quad)throw new Error("Cannot clone a "+this.constructor.name+" object.");if(args.up===undefined)args.up=this.__up;if(this instanceof text){var comp=this.__comp.clone();var bill=this.__billboard;if(args.billboard!==undefined){bill=args.billboard;delete args.billboard}var newargs={__pos:this.__pos,__offset:this.__offset,canvas:this.canvas,__comp:comp,__color:this.__color,__opacity:this.__opacity,__size:this.__size,__axis:this.__axis,__text:this.__text,__height:this.__height,__depth:this.__depth,__font:this.__font,__align:this.__align,__billboard:bill,__show_start_face:this.__show_start_face,__show_end_face:this.__show_end_face,__start_face_color:this.__start_face_color,__end_face_color:this.__end_face_color,__descender:this.__descender,__shininess:this.__shininess,__emissive:this.__emissive,__pickable:this.__pickable};var newtext=new text(newargs);for(var attr in args)newtext[attr]=args[attr];newtext.__update();return newtext}else if(this instanceof curve){var newargs={origin:this.__origin,pos:this.pos,color:this.__color,radius:this.__radius,size:this.__size,axis:this.__axis,shininess:this.__shininess,emissive:this.__emissive,visible:true,pickable:this.__pickable}}else if(this instanceof helix){var newargs={pos:this.pos,color:this.__color,thickness:this.__thickness,coils:this.__coils,size:this.__size,axis:this.__axis,shininess:this.__shininess,emissive:this.__emissive,visible:true,pickable:this.__pickable}}else{var newargs={pos:this.__pos,color:this.__color,opacity:this.__opacity,size:this.__size,axis:this.__axis,__tex:this.__tex,shininess:this.__shininess,emissive:this.__emissive,visible:true,pickable:this.__pickable};if(this instanceof arrow||this instanceof vp_arrow){newargs.shaftwidth=this.__shaftwidth;newargs.headwidth=this.__headwidth;newargs.headlength=this.__headlength}}var ret=new this.constructor(newargs);for(var attr in args)ret[attr]=args[attr];return ret},__change:function(){if(this.__id)this.canvas.__changed[this.__id]=this},__get_extent:function(ext){Autoscale.find_extent(this,ext)},__get_model:function(){return this.canvas.__renderer.models[this.constructor.name]},__update:function(){if(this.__id===null)return;var pos=this.__pos;var size=this.__size;var color=this.__color;var axis=this.__axis;var up=this.__up;var data=this.__data;if(!data)this.__data=data=new Float32Array(20);this.__model.id_object[this.__id]=this;data[0]=pos.__x;data[1]=pos.__y;data[2]=pos.__z;data[3]=this.__shininess;data[4]=axis.__x;data[5]=axis.__y;data[6]=axis.__z,data[7]=this.__emissive?1:0;data[8]=up.__x;data[9]=up.__y;data[10]=up.__z;data[11]=this.__tex.flags;data[12]=size.__x;data[13]=size.__y;data[14]=size.__z;data[16]=color.__x;data[17]=color.__y;data[18]=color.__z;data[19]=this.__opacity},rotate:function(args){var obj=this;var iscurve=obj.constructor==curve;var isarrow=obj.constructor==arrow;var origin=iscurve?obj.origin:obj.pos;if(args.origin!==undefined)origin=args.origin;if(args===undefined||args.angle===undefined){throw new Error("object.rotate() requires an angle.")}var angle=args.angle;if(angle===0)return;var rotaxis;if(args.axis===undefined)rotaxis=obj.__axis;else rotaxis=args.axis;if(obj instanceof text)obj=obj.__comp;if(iscurve)obj.origin=origin.add(obj.__origin.sub(origin).rotate({angle:angle,axis:rotaxis}));else if(!origin.equals(obj.pos))obj.pos=origin.add(obj.__pos.sub(origin).rotate({angle:angle,axis:rotaxis}));window.__adjustupaxis=false;if(diff_angle(obj.__axis,rotaxis)>1e-6){if(isarrow)obj.axis_and_length=obj.axis_and_length.rotate({angle:angle,axis:rotaxis});else obj.axis=obj.__axis.rotate({angle:angle,axis:rotaxis});obj.up=obj.up.rotate({angle:angle,axis:rotaxis})}else{obj.up=obj.__up.rotate({angle:angle,axis:rotaxis})}window.__adjustupaxis=true},getTransformedMesh:function(){var X=this.__axis.norm();var Y=this.__up.norm();var Z=X.cross(Y);var T=this.__pos;if(this instanceof ring||this instanceof vp_ring){var m=Mesh.makeRing_compound(this.__size);var matrix=[X.x,X.y,X.z,0,Y.x,Y.y,Y.z,0,Z.x,Z.y,Z.z,0,T.x,T.y,T.z,1];return m.transformed(matrix)}else{X=X.multiply(this.__size.x);Y=Y.multiply(this.__size.y);Z=Z.multiply(this.__size.z);var matrix=[X.x,X.y,X.z,0,Y.x,Y.y,Y.z,0,Z.x,Z.y,Z.z,0,T.x,T.y,T.z,1];return this.__model.mesh.transformed(matrix)}}});function box(args){return initObject(this,box,args)}subclass(box,Primitive);box.prototype.__hasPosAtCenter=true;function cylinder(args){return initObject(this,cylinder,args)}subclass(cylinder,Primitive);function cone(args){return initObject(this,cone,args)}subclass(cone,cylinder);function pyramid(args){return initObject(this,pyramid,args)}subclass(pyramid,box);function sphere(args){return initObject(this,sphere,args)}subclass(sphere,Primitive);sphere.prototype.__hasPosAtCenter=true;function vp_box(args){return initObject(this,vp_box,args)}subclass(vp_box,box);property.declare(vp_box.prototype,{size:new attributeVectorSize(null,1,1,1),length:{get:function(){return this.__size.__x},set:function(value){this.axis=this.__axis.norm().multiply(value);this.__change()}},height:{get:function(){return this.__size.__y},set:function(value){this.__size.__y=value;this.__change()}},width:{get:function(){return this.__size.__z},set:function(value){this.__size.__z=value;this.__change()}},red:{get:function(){return this.__color.__x},set:function(value){this.__color.__x=value;this.__change()}},green:{get:function(){return this.__color.__y},set:function(value){this.__color.__y=value;this.__change()}},blue:{get:function(){return this.__color.__z},set:function(value){this.__color.__z=value;this.__change()}}});function vp_pyramid(args){return initObject(this,vp_pyramid,args)}subclass(vp_pyramid,vp_box);function vp_sphere(args){return initObject(this,vp_sphere,args)}subclass(vp_sphere,vp_box);property.declare(vp_sphere.prototype,{axis:new attributeVectorAxis(null,1,0,0),size:new attributeVector(null,2,2,2),radius:{get:function(){return this.__size.__y/2},set:function(value){this.size=vec(2*value,2*value,2*value);this.__change()}}});function vp_ellipsoid(args){return initObject(this,vp_ellipsoid,args)}subclass(vp_ellipsoid,vp_box);property.declare(vp_ellipsoid.prototype,{radius:{get:function(){throw new Error("An ellipsoid does not have a radius attribute.")},set:function(value){throw new Error("An ellipsoid does not have a radius attribute.")}}});function vp_cylinder(args){return initObject(this,vp_cylinder,args)}subclass(vp_cylinder,vp_box);property.declare(vp_cylinder.prototype,{size:new attributeVectorSize(null,1,2,2),radius:{get:function(){return this.__size.__y/2},set:function(value){this.__size.__y=this.__size.__z=2*value;this.__change()}}});function vp_cone(args){return initObject(this,vp_cone,args)}subclass(vp_cone,vp_cylinder);function arrow_update(obj,vp){var pos=obj.__pos;var color=obj.__color;var axis;if(vp)axis=obj.__axis;else axis=obj.__axis_and_length;var L=mag(axis);var A=axis.norm();var sw=obj.__shaftwidth||L*.1;var hw=obj.__headwidth||sw*2;var hl=obj.__headlength||sw*3;if(sw<L*.02){var scale=L*.02/sw;if(!obj.__shaftwidth)sw*=scale;if(!obj.__headwidth)hw*=scale;if(!obj.__headlength)hl*=scale}if(hl>L*.5){var scale=L*.5/hl;if(!obj.__shaftwidth)sw*=scale;if(!obj.__headwidth)hw*=scale;if(!obj.__headlength)hl*=scale}var components=obj.__components;if(!components){if(vp)components=obj.__components=[vp_box({canvas:obj.canvas,__obj:obj}),vp_pyramid({canvas:obj.canvas,__obj:obj})];else components=obj.__components=[box({canvas:obj.canvas,__obj:obj}),pyramid({canvas:obj.canvas,__obj:obj})]}var shaft=components[0];var tip=components[1];shaft.pos=pos.add(A.multiply(.5*(L-hl)));tip.pos=pos.add(A.multiply(L-hl));shaft.axis=tip.axis=axis;shaft.size=vec(L-hl,sw,sw);tip.size=vec(hl,hw,hw);shaft.color=tip.color=obj.color;shaft.opacity=tip.opacity=obj.opacity;shaft.pickable=tip.pickable=obj.pickable;obj.size=vec(L,hw,hw);shaft.__update();tip.__update()}function arrow(args){if(!(this instanceof arrow))return new arrow(args);this.__shaftwidth=0;this.__headwidth=0;this.__headlength=0;return initObject(this,arrow,args)}subclass(arrow,box);property.declare(arrow.prototype,{__primitiveCount:2,shaftwidth:{get:function(){return this.__shaftwidth},set:function(value){this.__shaftwidth=value;this.__change()}},headwidth:{get:function(){return this.__headwidth},set:function(value){this.__headwidth=value;this.__change()}},headlength:{get:function(){return this.__headlength},set:function(value){this.__headlength=value;this.__change()}},axis_and_length:new attributeVectorAxis(null,1,0,0),axis:{get:function(){new Error("arrow has an axis_and_length attribute but no axis attribute")},set:function(value){new Error("arrow has an axis_and_length attribute but no axis attribute")}},__change:function(){if(this.__components){this.__components[0].__change();this.__components[1].__change()}},__update:function(){arrow_update(this,false)},__get_extent:function(ext){if(!this.__components)this.__update();Autoscale.find_extent(this.__components[0],ext);Autoscale.find_extent(this.__components[1],ext)}});function vp_arrow(args){if(!(this instanceof vp_arrow))return new vp_arrow(args);this.__shaftwidth=0;this.__headwidth=0;this.__headlength=0;return initObject(this,vp_arrow,args)}subclass(vp_arrow,arrow);property.declare(vp_arrow.prototype,{axis:new attributeVectorAxis(null,1,0,0),axis_and_length:{get:function(){new Error("arrow has an axis attribute but no axis_and_length attribute")},set:function(value){new Error("arrow has an axis attribute but no axis_and_length attribute")}},length:{get:function(){return mag(this.__axis)},set:function(val){this.axis=this.__axis.norm().multiply(val)}},__update:function(){arrow_update(this,true)}});function text(args){if(!(this instanceof text))return new text(args);if(args.canvas===null)return;args=args||{};this.__constructing=true;var pos=vec(0,0,0);if(args.pos!==undefined)pos=args["pos"];args["pos"]=vec(0,0,0);if(args.__comp===undefined){var ret=text3D(args);this.__id=nextVisibleId;nextVisibleId++;this.__comp=ret[0];args=ret[1];this.__offset=this.__comp.__pos;this.__color=this.__comp.__color;for(var attr in args)this[attr]=args[attr];this.pos=pos}else{for(var attr in args)this[attr]=args[attr];args={}}if(this.__billboard){this.canvas.update_billboards=true;this.canvas.billboards.push(this)}initObject(this,text,args);this.__update()}subclass(text,Primitive);property.declare(text.prototype,{__update:function(){var pos=this.__pos.add(this.__offset);this.__comp.pos=pos;this.__constructing=false},visible:{get:function(){return this.__comp.visible},set:function(value){this.__comp.visible=value}},texture:{get:function(){throw new Error("Cannot currently apply a texture to a text obect")},set:function(value){throw new Error("Cannot currently apply a texture to a text obect")}},length:{get:function(){return this.__comp.__size.x},set:function(value){var m=value/this.__comp.__size.x;this.__comp.__size.x*=m;this.__offset.x*=m;this.__change()}},height:{get:function(){return this.__height},set:function(value){if(value===this.__height)return;var m=value/this.__height;this.__comp.__size.y*=m;this.__offset.y*=m;this.__descender*=m;this.__height=value;this.__change()}},depth:{get:function(){return this.__depth},set:function(value){if(Math.abs(value)<.01*this.__height){if(value<0)value=-.01*this.__height;else value=.01*this.__height}this.__comp.__size.z*=Math.abs(value);this.__comp.__pos.z=value/2;this.__offset.z=value/2;this.__depth=value;this.__comp.__change()}},axis:{get:function(){return this.__comp.__axis},set:function(value){var axis=this.__comp.__axis;var zaxis=cross(axis,value);var angle=diff_angle(axis,value);if(angle>0)this.__comp.rotate({angle:angle,axis:zaxis,origin:this.__pos})}},size:{get:function(){return this.__comp.__size},set:function(value){var m=value.y/this.__comp.__size.y;this.length=value.x;this.height*=m;if(this.depth>=0)this.depth=value.z;else this.depth=-value.z}},up:{get:function(){return this.__comp.__up},set:function(value){this.__comp.up=value}},color:{get:function(){return this.__color},set:function(value){if(!this.__constructing){this.__comp.color=this.__color=value}this.__constructing=false}},text:{get:function(){return this.__text},set:function(value){throw new Error("text is read-only")}},font:{get:function(){return this.__font},set:function(value){throw new Error("font is read-only")}},align:{get:function(){return this.__align},set:function(value){throw new Error("align is read-only")}},billboard:{get:function(){return this.__billboard},set:function(value){throw new Error("billboard is read-only")}},opacity:{get:function(){return this.__opacity},set:function(value){this.__comp.opacity=this.__opacity=value}},shininess:{get:function(){return this.__shininess},set:function(value){this.__shininess=this.__comp.shininess=value}},emissive:{get:function(){return this.__emissive},set:function(value){this.__comp.emissive=this.__emissive=value}},show_start_face:{get:function(){return this.__show_start_face},set:function(value){throw new Error("show_start_face is read-only")}},show_end_face:{get:function(){return this.__show_end_face},set:function(value){throw new Error("show_end_face is read-only")}},start_face_color:{get:function(){return this.__start_face_color},set:function(value){throw new Error("start_face_color is read-only")}},end_face_color:{get:function(){return this.__end_face_color},set:function(value){throw new Error("end_face_color is read-only")}},start:{get:function(){return this.upper_left.sub(this.up.norm().multiply(this.height))},set:function(value){throw new Error("start is read-only")}},end:{get:function(){return this.upper_right.sub(this.up.norm().multiply(this.height))},set:function(value){throw new Error("end is read-only")}},descender:{get:function(){return this.__descender},set:function(value){throw new Error("descender is read-only")}},vertical_spacing:{get:function(){return 1.5*this.height},set:function(value){throw new Error("vertical_spacing is read-only")}},upper_left:{get:function(){var dx=0;if(this.__align=="right")dx=-this.length;else if(this.__align=="center")dx=-this.length/2;return this.pos.add(this.up.norm().multiply(this.height)).add(this.axis.norm().multiply(dx))},set:function(value){throw new Error("upper_left is read-only")}},upper_right:{get:function(){return this.upper_left.add(this.axis.norm().multiply(this.length))},set:function(value){throw new Error("upper_right is read-only")}},lower_left:{get:function(){return this.upper_left.add(this.up.norm().multiply(-this.height-this.descender-1.5*this.height*(this.__lines-1)))},set:function(value){throw new Error("lower_left is read-only")}},lower_right:{get:function(){return this.lower_left.add(this.axis.norm().multiply(this.length))},set:function(value){throw new Error("lower_right is read-only")}}});function vertex(args){if(!(this instanceof vertex)){return new vertex(args)}args=args||{};if(args.canvas!==undefined){this.canvas=args.canvas}else if(args.display!==undefined){this.canvas=args.display}else{this.canvas=canvas.selected}for(var attr in args){if(attr=="canvas"||attr=="display")continue;this[attr]=args[attr]}if(this.opacity===undefined)this.opacity=1;if(this.__texpos.z!==0)throw new Error("In a vertex the z component of texpos must be zero.");if(this.canvas.vertex_id>=65536)throw new Error("Currently the number of vertices is limited to 65536.");var lengths={pos:3,normal:3,color:3,opacity:1,shininess:1,emissive:1,texpos:2,bumpaxis:3};this.__id=this.canvas.__vertices.available.pop();
  if(this.__id===undefined){this.__id=this.canvas.vertex_id;var c=this.canvas.__vertices;if(this.canvas.vertex_id%c.Nalloc===0){var temp;var L=this.canvas.vertex_id+c.Nalloc;for(var t in lengths){temp=new Float32Array(lengths[t]*L);temp.set(c[t],0);c[t]=temp}}this.canvas.vertex_id++}this.canvas.__vertices.object_info[this.__id]={};this.__change()}property.declare(vertex.prototype,{__id:null,__hasPosAtCenter:true,pos:new attributeVector(null,0,0,0),normal:new attributeVector(null,0,0,1),color:new attributeVector(null,1,1,1),opacity:{get:function(){return this.__opacity},set:function(value){if(value==this.__opacity)return;if(this.__opacity<1&&value==1||this.__opacity==1&&value<1){var users=this.canvas.__vertices.object_info[this.__id];for(var u in users){users[u].__change();users[u].__opacity_change=true}}this.__opacity=value;this.canvas.__vertex_changed[this.__id]=this}},texpos:new attributeVector(null,0,0,0),bumpaxis:new attributeVector(null,1,0,0),shininess:{value:.6,onchanged:function(){this.__change()}},emissive:{value:false,onchanged:function(){this.__change()}},__change:function(){if(this.__id){this.canvas.__vertex_changed[this.__id]=this;if(this.canvas.__autoscale){var users=this.canvas.__vertices.object_info[this.__id];for(var u in users)users[u].__change()}}},rotate:function(args){if(args.angle===undefined){throw new Error("vertex.rotate() requires angle:...")}var angle=args.angle;if(args.axis===undefined){throw new Error("vertex.rotate() requires axis:...")}var axis=args.axis.norm();var origin;if(args.origin===undefined){origin=vec(0,0,0)}else origin=args.origin;this.pos=origin.add(this.__pos.sub(origin).rotate({angle:angle,axis:axis}));this.__change()}});function tri_quad_error(object_type,attribute){throw new Error("A "+object_type+" has no "+attribute+" attribute.")}function triangle(args){if(!(this instanceof triangle))return new triangle(args);args=args||{};var vnames=["v0","v1","v2"];if(args.vs===undefined){for(var i=0;i<3;i++)if(args[vnames[i]]===undefined)throw new Error("A triangle must have a vertex "+vnames[i]+".")}this.__tex={file:null,bumpmap:null,texture_ref:{reference:null},bumpmap_ref:{reference:null},left:false,right:false,sides:false,flipx:false,flipy:false,turn:0,flags:0};init(this,args);var vtemp=this.vs;for(var i=0;i<3;i++)this.canvas.__vertices.object_info[vtemp[i].__id][this.__id]=this}subclass(triangle,box);property.declare(triangle.prototype,{v0:{get:function(){return this.__v0},set:function(value){if(!(value instanceof vertex))throw new Error("v0 must be a vertex object.");this.__v0=value;this.__change()}},v1:{get:function(){return this.__v1},set:function(value){if(!(value instanceof vertex))throw new Error("v1 must be a vertex object.");this.__v1=value;this.__change()}},v2:{get:function(){return this.__v2},set:function(value){if(!(value instanceof vertex))throw new Error("v2 must be a vertex object.");this.__v2=value;this.__change()}},vs:{get:function(){return[this.__v0,this.__v1,this.__v2]},set:function(value){if(toType(value)!="array"||value.length!=3)throw new Error("triangle.vs must be a list of 3 vertex objects.");for(var i=0;i<3;i++)if(!(value[i]instanceof vertex))throw new Error("triangle.vs must contain vertex objects.");this.__v0=value[0];this.__v1=value[1];this.__v2=value[2];this.__change()}},pos:{get:function(){tri_quad_error("triangle","pos")},set:function(value){tri_quad_error("triangle","pos")}},color:{get:function(){tri_quad_error("triangle","color")},set:function(value){tri_quad_error("triangle","color")}},size:{get:function(){tri_quad_error("triangle","size")},set:function(value){tri_quad_error("triangle","size")}},axis:{get:function(){tri_quad_error("triangle","axis")},set:function(value){tri_quad_error("triangle","axis")}},up:{get:function(){tri_quad_error("triangle","up")},set:function(value){tri_quad_error("triangle","up")}},opacity:{get:function(){tri_quad_error("triangle","opacity")},set:function(value){tri_quad_error("triangle","opacity")}},shininess:{get:function(){tri_quad_error("triangle","shininess")},set:function(value){tri_quad_error("triangle","shininess")}},emissive:{get:function(){tri_quad_error("triangle","emissive")},set:function(value){tri_quad_error("triangle","emissive")}},__prev_texture:null,__prev_bumpmap:null,__update:function(){this.__model.id_object[this.__id]=this},__get_extent:function(ext){var vnames=["__v0","__v1","__v2"];for(var i=0;i<3;i++)ext.point_extent(this,this[vnames[i]].pos)},rotate:function(args){throw new Error("A triangle has no rotate method; rotate the vertices instead.")}});function quad(args){if(!(this instanceof quad))return new quad(args);args=args||{};var vnames=["v0","v1","v2","v3"];if(args.vs===undefined){for(var i=0;i<4;i++)if(args[vnames[i]]===undefined)throw new Error("A quad must have a vertex "+vnames[i]+".")}this.__tex={file:null,bumpmap:null,texture_ref:{reference:null},bumpmap_ref:{reference:null},left:false,right:false,sides:false,flipx:false,flipy:false,turn:0,flags:0};init(this,args);var vtemp=this.vs;for(var i=0;i<4;i++)this.canvas.__vertices.object_info[vtemp[i].__id][this.__id]=this}subclass(quad,box);property.declare(quad.prototype,{v0:{get:function(){return this.__v0},set:function(value){if(!(value instanceof vertex))throw new Error("v0 must be a vertex object.");this.__v0=value;this.__change()}},v1:{get:function(){return this.__v1},set:function(value){if(!(value instanceof vertex))throw new Error("v1 must be a vertex object.");this.__v1=value;this.__change()}},v2:{get:function(){return this.__v2},set:function(value){if(!(value instanceof vertex))throw new Error("v2 must be a vertex object.");this.__v2=value;this.__change()}},v3:{get:function(){return this.__v3},set:function(value){if(!(value instanceof vertex))throw new Error("v3 must be a vertex object.");this.__v3=value;this.__change()}},vs:{get:function(){return[this.__v0,this.__v1,this.__v2,this.__v3]},set:function(value){if(toType(value)!="array"||value.length!=4)throw new Error("quad.vs must be a list of 4 vertex objects.");for(var i=0;i<4;i++)if(!(value[i]instanceof vertex))throw new Error("quad.vs must contain vertex objects.");this.__v0=value[0];this.__v1=value[1];this.__v2=value[2];this.__v3=value[3];this.__change()}},pos:{get:function(){tri_quad_error("quad","pos")},set:function(value){tri_quad_error("quad","pos")}},color:{get:function(){tri_quad_error("quad","color")},set:function(value){tri_quad_error("quad","color")}},size:{get:function(){tri_quad_error("quad","size")},set:function(value){tri_quad_error("quad","size")}},axis:{get:function(){tri_quad_error("quad","axis")},set:function(value){tri_quad_error("quad","axis")}},up:{get:function(){tri_quad_error("quad","up")},set:function(value){tri_quad_error("quad","up")}},opacity:{get:function(){tri_quad_error("quad","opacity")},set:function(value){tri_quad_error("quad","opacity")}},shininess:{get:function(){tri_quad_error("quad","shininess")},set:function(value){tri_quad_error("quad","shininess")}},__prev_texture:null,__prev_bumpmap:null,__update:function(){this.__model.id_object[this.__id]=this},__get_extent:function(ext){var vnames=["__v0","__v1","__v2","__v3"];for(var i=0;i<4;i++)ext.point_extent(this,this[vnames[i]].pos)},rotate:function(args){throw new Error("A quad has no rotate method; rotate the vertices instead.")}});var compound_id=0;function make_compound(objects,parameters){function update_extent(c,extent){if(extent.__xmin===null)return;for(var ext in extent){var value=extent[ext];if(ext.slice(-3)=="min"){if(c[ext]===null||value<c[ext])c[ext]=value}else{if(c[ext]===null||value>c[ext])c[ext]=value}}}var self=parameters.self;delete parameters.self;var mesh=new Mesh;var release=[];for(var i=0;i<objects.length;i++){var o=objects[i];if(o instanceof curve)throw new Error("Currently cannot include a curve in a compound.");else if(o instanceof helix)throw new Error("Currently cannot include a helix in a compound.");else if(o instanceof label)throw new Error("Currently cannot include a label in a compound.");if(o.__tex.file!==null)throw new Error("Currently objects in a compound cannot have their own texture.");if(o.__tex.bumpmap!==null)throw new Error("Currently objects in a compound cannot have their own bumpmap.");if(o instanceof triangle||o instanceof quad){var q=o.vs;var N=3;if(o instanceof quad)N=4;for(var k=0;k<N;k++){if(k==3){update_extent(self,mesh.merge(o.v0,o.v0,-3));update_extent(self,mesh.merge(o.v2,o.v2,-1));update_extent(self,mesh.merge(o.v3,o.v3,0))}else{update_extent(self,mesh.merge(q[k],q[k],0))}if(self.canvas.__vertices.object_info[q[k].__id][o.__id]!==undefined){delete self.canvas.__vertices.object_info[q[k].__id][o.__id]}if(Object.keys(self.canvas.__vertices.object_info[q[k].__id]).length===0){if(release.indexOf(q[k].__id)<0)release.push(q[k].__id)}}}else if(o instanceof text){var comp=o.__comp;update_extent(self,mesh.merge(comp.getTransformedMesh(),comp,0))}else if(o.__components!==undefined){var c=o.__components;for(var ci=0;ci<c.length;ci++){var comp=c[ci];update_extent(self,mesh.merge(comp.getTransformedMesh(),comp,0))}}else{update_extent(self,mesh.merge(o.getTransformedMesh(),o,0))}o.visible=false;o.__deleted=true}for(var k=0;k<release.length;k++)self.canvas.__vertices.available.push(release[k]);self.pos=vec((self.__xmin+self.__xmax)/2,(self.__ymin+self.__ymax)/2,(self.__zmin+self.__zmax)/2);var size=self.size=vec(self.__xmax-self.__xmin,self.__ymax-self.__ymin,self.__zmax-self.__zmin);if(window.__GSlang=="vpython")self.axis=norm(self.axis).multiply(size.x);if(Math.min(size.x,size.y,size.z)===0){var max=Math.max(size.x,size.y,size.z);if(size.x===0)self.size.__x=.001*max;if(size.y===0)self.size.__y=.001*max;if(size.z===0)self.size.__z=.001*max}if(mag(self.axis)===0)self.axis.__x=self.size.__x;mesh.adjust(self.pos,self.size);compound_id++;mesh.__mesh_id="compound"+compound_id;self.canvas.__renderer.add_model(mesh,false);self.__mesh=mesh;self.__model=self.canvas.__renderer.models[mesh.__mesh_id];var attrs=["axis","size","up"];for(var attr in attrs){var a=attrs[attr];if(parameters[a]!==undefined){self[a]=parameters[a];delete parameters[a]}}for(var attr in parameters)self[attr]=parameters[attr]}function compound(objects,parameters){if(!(this instanceof compound))return new compound(objects,parameters);if(objects.length===undefined&&objects.canvas===null)return;parameters=parameters||{};if(objects.length===undefined)throw new Error("compound takes a list of objects");initObject(this,compound,{});var cloning=false;if(parameters.__cloning){cloning=true;var mesh=parameters.__cloning;delete parameters.__cloning}var visible=true;if(parameters.visible!==undefined){visible=parameters.visible;delete parameters.visible}if(!cloning){parameters.self=this;make_compound(objects,parameters)}else{this.__mesh=mesh;this.__model=this.canvas.__renderer.models[mesh.__mesh_id];for(var attr in parameters)this[attr]=parameters[attr]}this.visible=visible}subclass(compound,box);property.declare(compound.prototype,{clone:function(args){var newargs={pos:this.__pos,color:this.__color,opacity:this.__opacity,size:this.__size,axis:this.__axis,up:this.__up,shininess:this.__shininess,emissive:this.__emissive,visible:true,pickable:this.__pickable,__center:this.__center,__pseudosize:this.__pseudosize};if(this.texture.file!==null)newargs.texture=this.texture;for(var attr in args)newargs[attr]=args[attr];newargs.__cloning=this.__mesh;return new this.constructor([],newargs)},_world_zaxis:function(){return this.__axis.cross(this.__up).norm()},world_to_compound:function(v){var axis=this.__axis;var z_axis=this._world_zaxis();var y_axis=this.__up;var x_axis=axis.norm();var v=v.sub(this.__pos);return vec(v.dot(x_axis),v.dot(y_axis),v.dot(z_axis))},compound_to_world:function(v){var axis=this.__axis;var z_axis=this._world_zaxis();var y_axis=this.__up;var x_axis=axis.norm();return this.__pos.add(x_axis.multiply(v.x)).add(y_axis.multiply(v.y)).add(z_axis.multiply(v.z))},__get_model:function(){return this.__model}});function vp_compound(objects,parameters){if(!(this instanceof vp_compound))return new vp_compound(objects,parameters);if(objects.length===undefined&&objects.canvas===null)return;parameters=parameters||{};if(objects.length===undefined)throw new Error("compound takes a list of objects");initObject(this,compound,{});var cloning=false;if(parameters.__cloning){cloning=true;var mesh=parameters.__cloning;delete parameters.__cloning}var visible=true;if(parameters.visible!==undefined){visible=parameters.visible;delete parameters.visible}if(!cloning){parameters.self=this;make_compound(objects,parameters)}else{this.__mesh=mesh;this.__model=this.canvas.__renderer.models[mesh.__mesh_id];for(var attr in parameters)this[attr]=parameters[attr]}this.visible=visible}subclass(vp_compound,compound);property.declare(vp_compound.prototype,{size:new attributeVectorSize(null,1,1,1),length:{get:function(){return this.__size.__x},set:function(value){this.axis=this.__axis.norm().multiply(value);this.__change()}},height:{get:function(){return this.__size.__y},set:function(value){this.__size.__y=value;this.__change()}},width:{get:function(){return this.__size.__z},set:function(value){this.__size.__z=value;this.__change()}},red:{get:function(){return this.__color.__x},set:function(value){this.__color.__x=value;this.__change()}},green:{get:function(){return this.__color.__y},set:function(value){this.__color.__y=value;this.__change()}},blue:{get:function(){return this.__color.__z},set:function(value){this.__color.__z=value;this.__change()}}});var toType=function(obj){return{}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()};function curve(args){if(!(this instanceof curve)){return new curve(arguments)}args=args||{};if(args.canvas!==null){var iargs=[];if(arguments.length!==undefined)for(var i=0;i<args.length;i++)iargs.push(args[i]);else for(var i=0;i<arguments.length;i++)iargs.push(arguments[i]);this.__color=vec(1,1,1);this.__radius=0;this.__retain=-1;this.pickable=true;this.__points=[];if(iargs.length==1&&toType(iargs[0])=="object"){var obj=iargs[0];if(obj["texture"]!==undefined)throw new Error("Textures are not available for curve objects.");if(obj["opacity"]!==undefined)throw new Error("Opacity is not available for curve objects.");var haspos=false;if(obj["pos"]!==undefined){haspos=true;this.__pos=obj.pos;delete obj.pos}initObject(this,curve,obj);if(haspos)this.push(this.__pos)}else{initObject(this,curve,{});if(toType(iargs)=="array"&&toType(iargs[0])=="array")this.push(iargs[0]);else this.push(iargs)}}}subclass(curve,Primitive);property.declare(curve.prototype,{origin:new attributeVectorPos(null,0,0,0),pos:{get:function(){throw new Error("Use methods to read curve or points pos attribute.")},set:function(value){throw new Error("Use methods to change curve or points pos attribute.")}},radius:{get:function(){return this.__radius},set:function(value){this.__radius=value;this.__change()}},retain:{get:function(){return this.__retain},set:function(value){this.__retain=value;this.__change()}},npoints:{get:function(){return this.__points.length},set:function(value){throw new Error("Cannot change curve or points npoints.")}},__no_autoscale:false,__get_extent:function(ext){if(this.__no_autoscale)return;var xmin=null,ymin=null,zmin=null,xmax=null,ymax=null,zmax=null;var length=this.__points.length;var pnt=this.__points;var p;for(var i=0;i<length;i++){p=pnt[i].__pos;if(xmin===null||p.x<xmin)xmin=p.x;if(ymin===null||p.y<ymin)ymin=p.y;if(zmin===null||p.z<zmin)zmin=p.z;if(xmax===null||p.x>xmax)xmax=p.x;if(ymax===null||p.y>ymax)ymax=p.y;if(zmax===null||p.z>zmax)zmax=p.z}var center=vec((xmin+xmax)/2,(ymin+ymax)/2,(zmin+zmax)/2);var pseudosize=vec(xmax-xmin,ymax-ymin,zmax-zmin);var savepos=this.__pos,savesize=this.__size;this.__pos=center;this.__size=pseudosize;this.__hasPosAtCenter=true;ext.xmin=xmin;ext.xmax=xmax;ext.ymin=ymin;ext.ymax=ymax;ext.zmin=zmin;ext.zmax=zmax;Autoscale.find_extent(this,ext);this.__pos=savepos;this.__size=savesize},push:function(pts){var args=[];var pos;if(pts.length!==undefined){if(pts.length==1)args=pts[0];else args=pts}else for(var i=0;i<arguments.length;i++)args.push(arguments[i]);var pointarg={};var attrs=["color","radius","retain","visible"];for(var a in attrs){var attr=attrs[a];if(attr=="radius"&&attr in args&&this.constructor==points)throw new Error("In a points object, you cannot specify the radius of an individual point.");if(attr in args)pointarg[attr]=args[attr]}var argtype=toType(args);var objects=false;if(args instanceof vec)args=[{pos:args}];else if(argtype=="array"){if(args[0]instanceof vec)args=[{pos:args}];else if(toType(args[0])=="object")objects=true}else if(argtype=="object")args=[args];for(var i=0;i<args.length;i++){var obj=args[i];pos=obj;if("pos"in obj){pos=obj.pos}if(toType(pos)!="array")pos=[pos];for(var j=0;j<pos.length;j++){var p=pos[j];if(toType(p)=="array")p=vec(p[0],p[1],p[2]);var setup;if(objects){setup=obj;setup.pos=p}else{setup={pos:p};for(var a in pointarg){setup[a]=pointarg[a]}}if(this.constructor==curve){var pt=point(setup);var retain=this.__retain;if(setup.retain!==undefined)retain=setup.retain;if(retain>-1&&this.__points.length>=retain){var N=this.__points.length-retain;for(var d=0;d<N;d++){var first=this.__points.shift();first.visible=false}var prev=this.__points[this.__points.length-1];var pt=this.__points.shift();for(var a in setup)pt[a]=setup[a];this.__points.push(pt);var s=pt.__prevsegment=prev.__nextsegment=new Float32Array(16);s[11]=s[15]=1;prev.__change();pt.__change()}else{pt.__curve=this;pt.__id=nextVisibleId++;this.canvas.__visiblePrimitives[pt.__id]=pt;pt.__falsecolor=id_to_falsecolor(pt.__id);if(this.__points.length){var prev=this.__points[this.__points.length-1];var s=pt.__prevsegment=prev.__nextsegment=new Float32Array(16);s[11]=s[15]=1;prev.__change()}this.__points.push(pt);pt.__change()}}else{var retain=this.__retain;if(setup.retain!==undefined)retain=setup.retain;if(retain>-1&&this.__points.length>=retain){var N=this.__points.length-retain;for(var d=0;d<N;d++){var first=this.__points.shift();first.visible=false}var prev=this.__points[this.__points.length-1];var pt=this.__points.shift();for(var a in setup)pt[a]=setup[a];this.__points.push(pt);pt.__change()}else{var D=2*this.__radius;var c=setup.color===undefined?this.__color:setup.color;if(this.__points.length>0&&this.__last_range!=-1&&this.__last_range===this.canvas.__range){D=this.__points[0].__size.x}else{D=0;this.__last_range=-1}if(window.__GSlang=="vpython"){this.__points.push(vp_sphere({pos:setup.pos,size:vec(D,D,D),color:c,pickable:false}))}else{this.__points.push(sphere({pos:setup.pos,size:vec(D,D,D),color:c,pickable:false}))}}}}}this.__change()},append:function(pts){var args=[];if(pts.length!==undefined)args=pts;else for(var i=0;i<arguments.length;i++)args.push(arguments[i]);this.push(args)},pop:function(){var p=this.__points.pop();p.visible=false;this.__change();return{pos:p.pos,color:p.color,radius:p.radius,visible:p.visible}},point:function(N){var p=this.__points.slice(N,N+1)[0];return{pos:p.pos,color:p.color,radius:p.radius,visible:p.visible}},clear:function(){this.splice(0,this.__points.length);this.__points=[];this.__change()},shift:function(){var p=this.__points.shift();p.visible=false;this.__change();return{pos:p.pos,color:p.color,radius:p.radius,visible:p.visible}},unshift:function(args){var pts=[];if(args.length!==undefined)pts=args;else for(var i=0;i<arguments.length;i++)pts.push(arguments[i]);this.splice(0,0,pts);this.__change()},splice:function(args){var index=arguments[0];var howmany=arguments[1];var pts=[];for(var i=2;i<arguments.length;i++)pts.push(arguments[i]);if(pts.length==1&&pts[0].length!==undefined)pts=pts[0];var s=this.__points.slice(index+howmany);var t=[];for(var i=0;i<s.length;i++)t.push({pos:s[i].pos,color:s[i].color,radius:s[i].radius,visible:s[i].visible});for(var i=index;i<this.__points.length;i++)this.__points[i].visible=false;this.__points.splice(index);this.push(pts);this.push(t);this.__change()},modify:function(N,args){if(N<0)N+=this.__points.length;if(args instanceof vec)args={pos:args};for(var attr in args){if(attr=="x")this.__points[N].pos.x=args[attr];else if(attr=="y")this.__points[N].pos.y=args[attr];else if(attr=="z")this.__points[N].pos.z=args[attr];else this.__points[N][attr]=args[attr]}this.__points[N].__change();this.__change()},slice:function(start,end){if(start<0)start+=this.__points.length;if(end<0)end+=this.__points.length;var s=this.__points.slice(start,end);var t=[];for(var i=0;i<s.length;i++)t.push({pos:s[i].pos,color:s[i].color,radius:s[i].radius,visible:s[i].visible});return t},__update:function(){var origin=this.__origin;var size=this.__size;var color=this.__color;var axis=this.__axis;var up=this.__up;var data=this.__data;if(!data)this.__data=data=new Float32Array(20);this.__model.id_object[this.__id]=this;data[0]=origin.__x;data[1]=origin.__y;data[2]=origin.__z;data[3]=this.__shininess;data[4]=axis.__x;data[5]=axis.__y;data[6]=axis.__z,data[7]=this.__emissive?1:0;data[8]=up.__x;data[9]=up.__y;data[10]=up.__z;data[12]=size.__x;data[13]=size.__y;data[14]=size.__z;data[15]=this.__radius;data[16]=color.__x;data[17]=color.__y;data[18]=color.__z;data[19]=this.__opacity}});function point(args){if(!(this instanceof point))return new point(args);if(args instanceof vec)args={pos:args};for(var id in args)this[id]=args[id];if(this.pos===undefined)throw new Error("Must specify pos for a point on a curve")}property.declare(point.prototype,{__curve:null,pos:new attributeVector(null,0,0,0),color:new attributeVector(null,-1,-1,-1),pickable:{value:true,onchanged:function(){this.__change()}},visible:{value:true,onchanged:function(){this.__change()}},__change:function(){if(this.__id){this.__curve.canvas.__changed[this.__id]=this;this.__curve.canvas.__changed[this.__curve.__id]=this.__curve}},__update:function(){var pos=this.__pos;var radius=this.radius||-1;var color=this.color||vec(-1,-1,-1);var s=this.__prevsegment;if(s){s[4]=pos.x;s[5]=pos.y;s[6]=pos.z;s[7]=radius;s[12]=color.x;s[13]=color.y;s[14]=color.z}s=this.__nextsegment;if(s){s[0]=pos.x;s[1]=pos.y;s[2]=pos.z;s[3]=radius;s[8]=color.x;s[9]=color.y;s[10]=color.z}}});function points(iargs){if(!(this instanceof points)){return new points(arguments)}iargs=iargs||{};if(iargs.canvas!==null){if(iargs["texture"]!==undefined)throw new Error("Textures are not available for points objects.");if(iargs["opacity"]!==undefined)throw new Error("Opacity is not available for points objects.");var saveargs=[];if(arguments.length!==undefined)for(var i=0;i<iargs.length;i++)saveargs.push(iargs[i]);else for(var i=0;i<arguments.length;i++)saveargs.push(arguments[i]);this.__color=vec(1,1,1);this.__radius=0;this.__retain=-1;this.__pixels=true;this.__points=[];this.pickable=false;if(toType(saveargs)=="array"&&saveargs.length==1&&toType(saveargs[0])=="object"){var obj=saveargs[0];if(obj["texture"]!==undefined)throw new Error("Textures are not available for points objects.");if(obj["opacity"]!==undefined)throw new Error("Opacity is not available for points objects.");var haspos=false;if(obj["pos"]!==undefined){haspos=true;this.__pos=obj.pos;delete obj.pos}if(obj.size_units!==undefined){if(obj.size_units=="world")this.__pixels=false;delete obj.size_units}initObject(this,points,obj);if(haspos)this.push(this.__pos)}else{initObject(this,points,{});if(toType(saveargs)=="array"&&toType(saveargs[0])=="array")this.push(saveargs[0]);else this.push(saveargs)}this.__last_range=-1;this.canvas.__points_objects.push(this)}}subclass(points,curve);property.declare(points.prototype,{origin:{get:function(){throw new Error("The points object has no origin attribute.")},set:function(value){throw new Error("The points object has no origin attribute.")}},axis:{get:function(){throw new Error("The points object has no axis attribute.")},set:function(value){throw new Error("The points object has no axis attribute.")}},up:{get:function(){throw new Error("The points object has no up attribute.")},set:function(value){throw new Error("The points object has no up attribute.")}},size:{get:function(){throw new Error("The points object has no size attribute.")},set:function(value){throw new Error("The points object has no size attribute.")}},size_units:{get:function(){return this.__pixels?"pixels":"world"},set:function(value){if(value=="pixels")this.__pixels=true;else if(value=="world")this.__pixels=false;else throw new Error("The points object ")}},rotate:{get:function(args){throw new Error("The points object has no rotate method.")}},shape:{get:function(){return"round"},set:function(value){if(value!="round")throw new Error('The points object only supports shape = "round".')}},visible:{get:function(){return this.__visible},set:function(value){for(var p in this.__points){this.__points[p].visible=value}this.__visible=value}},__update:function(){}});function helix(args){return initObject(this,helix,args)}subclass(helix,cylinder);property.declare(helix.prototype,{__initialize:true,thickness:{value:0,onchanged:function(){this.__change()}},coils:{value:5,onchanged:function(){this.__initialize=true;this.__change()}},__update:function(){var NCHORDS=20;if(this.__initialize){if(this.__curve!==undefined){this.__curve.clear()}else{this.__curve=curve({canvas:this.canvas,__no_autoscale:true})}}var c=this.__curve;c.origin=this.__pos;c.axis=this.__axis;c.up=this.__up;c.size=this.__size;c.color=this.__color;c.radius=this.__thickness?this.__thickness/2:this.__size.y/40;if(!this.__initialize)return;var X=vec(1,0,0);var Y=vec(0,1,0);var Z=vec(0,0,1);var r=.5;var count=this.__coils*NCHORDS;var dx=1/count;var ds=Math.sin(2*Math.PI/NCHORDS),dc=Math.cos(2*Math.PI/NCHORDS);var x=0,y=0,z=r;var znew;for(var i=0;i<count+1;i++){c.push(vec(x,y,z));x+=dx;znew=z*dc-y*ds;y=y*dc+z*ds;z=znew}this.__initialize=false}});function vp_helix(args){return initObject(this,vp_helix,args)}subclass(vp_helix,helix);property.declare(vp_helix.prototype,{size:new attributeVectorSize(null,1,2,2),radius:{get:function(){return this.__size.__y/2},set:function(value){this.__size.__y=this.__size.__z=2*value;this.__change()}},length:{get:function(){return this.__size.__x},set:function(value){this.__size.__x=value;this.__change()}},height:{get:function(){return this.__size.__y},set:function(value){this.__size.__y=value;this.__change()}},width:{get:function(){return this.__size.__z},set:function(value){this.__size.__z=value;this.__change()}}});function arrayequals(a,b){var La=a.length;var Lb=b.length;if(La!==Lb)return false;for(var i=0;i<La;i++)if(a[i]!==b[i])return false;return true}function ring(args){return initObject(this,ring,args)}subclass(ring,box);property.declare(ring.prototype,{size:new attributeVector(null,.1,1,1)});function vp_ring(args){return initObject(this,vp_ring,args)}subclass(vp_ring,vp_box);property.declare(vp_ring.prototype,{size:new attributeVector(null,.2,2.2,2.2),thickness:{get:function(){return this.__size.__x/2},set:function(value){var R1=this.radius;this.__thickness=value;this.__size.x=2*value;this.__size.y=this.__size.z=2*(value+R1);this.__change()}},radius:{get:function(){return(this.__size.y-this.__size.x)/2},set:function(value){var R2=this.thickness;this.__radius=value;this.__size.y=this.__size.z=2*(value+R2);this.__change()}}});function distant_light(args){if(!(this instanceof distant_light))return new distant_light(args);if(args.direction===undefined)throw new Error("Must specify the distant_light, direction:..");init(this,args);this.canvas.lights.push(this)}property.declare(distant_light.prototype,{direction:new attributeVector(null,0,0,1),color:new attributeVector(null,1,1,1),__get_model:function(){return this.canvas.__renderer.models[this.constructor.name]},__change:function(){}});function local_light(args){if(!(this instanceof local_light))return new local_light(args);if(args.pos===undefined)throw new Error("Must specify the local_light position, pos:..");init(this,args);this.canvas.lights.push(this)}property.declare(local_light.prototype,{pos:new attributeVector(null,0,0,0),color:new attributeVector(null,1,1,1),__get_model:function(){return this.canvas.__renderer.models[this.constructor.name]},__change:function(){}});function draw(args){if(!(this instanceof draw))return new draw(args);args=args||{};this.points=[];init(this,args);this.canvas.__overlay_objects.objects.push(this)}property.declare(draw.prototype,{color:{value:null,type:property.nullable_attributeVector},fillcolor:{value:null,type:property.nullable_attributeVector},linewidth:{value:1,onchanged:function(){this.__change()}},opacity:{value:.66,onchanged:function(){this.__change()}},visible:{value:false,onchanged:function(){this.__change()}},__get_model:function(){return this.canvas.__renderer.models[this.constructor.name]},__update:function(ctx,camera){var pts=this.points.length;if(pts<2)return;if(this.fillcolor!=null){ctx.lineWidth=1;ctx.fillStyle=color.to_html_rgba(this.fillcolor,this.opacity);ctx.beginPath();for(var i=0;i<pts;i++){if(i==0)ctx.moveTo(this.points[i].x,this.points[i].y);else ctx.lineTo(this.points[i].x,this.points[i].y)}ctx.fill()}if(this.color!=null){ctx.lineWidth=this.linewidth;ctx.strokeStyle=color.to_html_rgba(this.color,this.opacity);ctx.beginPath();for(var i=0;i<pts;i++){if(i==0)ctx.moveTo(this.points[i].x,this.points[i].y);else if(i==pts-1&&this.points[i].equals(this.points[0]))ctx.closePath();else ctx.lineTo(this.points[i].x,this.points[i].y)}ctx.stroke()}},__change:function(){this.canvas.__overlay_objects.__changed=true}});function label(args){if(!(this instanceof label))return new label(args);args=args||{};this.pos=this.pos;this.color=this.color;init(this,args);this.canvas.__overlay_objects.objects.push(this)}property.declare(label.prototype,{pos:new attributeVector(null,0,0,0),color:{value:null,type:property.nullable_attributeVector},line:{value:true,onchanged:function(){this.__change()}},linecolor:{value:null,type:property.nullable_attributeVector},background:{value:null,type:property.nullable_attributeVector},opacity:{value:.66,onchanged:function(){this.__change()}},text:{value:"",onchanged:function(){this.__change()}},font:{value:"Arial",onchanged:function(){this.__change()}},height:{value:15,onchanged:function(){this.__change()}},visible:{value:false,onchanged:function(){this.__change()}},align:{value:null,onchanged:function(){this.__change()}},box:{value:true,onchanged:function(){this.__change()}},border:{value:5,onchanged:function(){this.__change()}},linewidth:{value:1,onchanged:function(){this.__change()}},xoffset:{value:0,onchanged:function(){this.__change()}},yoffset:{value:0,onchanged:function(){this.__change()}},space:{value:0,onchanged:function(){this.__change()}},pixel_pos:{value:false,onchanged:function(){this.__change()}},__get_model:function(){return null},__update:function(ctx,camera){var xoffset=this.__xoffset,yoffset=this.__yoffset;var posx,posy;if(this.__pixel_pos){posx=this.__pos.x;posy=this.canvas.__height-this.__pos.y;yoffset=-yoffset}else{if(this.canvas.__width>=this.canvas.__height)var factor=2*this.canvas.__range/this.canvas.__height;else var factor=2*this.canvas.__range/this.canvas.__width;var viewMatrix=mat4.lookAt(camera.pos,camera.target,camera.up);var vnew=mat4.multiplyVec3(viewMatrix,vec3.create([this.pos.x,this.pos.y,this.pos.z]));if(vnew[2]>-camera.zNear||vnew[2]<-camera.zFar)return;var d=camera.distance;var k=-d/(vnew[2]*factor);posx=Math.round(k*vnew[0]+this.canvas.__width/2);posy=Math.round(-k*vnew[1]+this.canvas.__height/2)}var h=this.__height;var f=this.__font;if(this.__font=="Verdana")h*=13/15;else if(this.__font=="sans")f="Arial";else if(this.__font=="serif")f="Georgia";ctx.font=h+"px "+f;ctx.textAlign="left";ctx.textBaseline="middle";ctx.lineWidth=this.__linewidth;var default_color=vec(1,1,1);if(this.canvas.__background.equals(vec(1,1,1)))default_color=vec(0,0,0);ctx.strokeStyle=color.to_html(this.__linecolor||this.__color||default_color);var lines,nlines;var dh=1.2*this.__height;var upperchar=.4*this.__height;if(typeof this.__text==="string")lines=this.__text.split("\n");else lines=[print_to_string(this.__text)];nlines=lines.length;
  var height=this.__height+(nlines-1)*dh;var width=0;var linewidths=[];for(var nth=0;nth<nlines;nth++){var w=Math.ceil(ctx.measureText(lines[nth]).width);linewidths.push(w);if(w>width)width=w}var tstart=[];for(var nth=0;nth<nlines;nth++){switch(this.__align){case null:if(xoffset===0&&yoffset===0)tstart.push((width-linewidths[nth])/2);else{if(Math.abs(yoffset)>Math.abs(xoffset)){tstart.push((width-linewidths[nth])/2)}else{if(xoffset>0){tstart.push(0)}else if(xoffset<0){tstart.push(width-linewidths[nth])}}}break;case"center":tstart.push((width-linewidths[nth])/2);break;case"right":tstart.push(width-linewidths[nth]);break;case"left":tstart.push(0);break;default:throw new Error('Label align must be "center" or "left" or "right".')}}var xbase;var ybase;var border=this.__border;if(xoffset||yoffset){if(Math.abs(yoffset)>Math.abs(xoffset)){if(yoffset>0){xbase=posx+xoffset-width/2;ybase=posy-yoffset-height-border+upperchar}else{xbase=posx+xoffset-width/2;ybase=posy-yoffset+border+upperchar}}else if(Math.abs(xoffset)>0){ybase=posy-yoffset-height/2+upperchar;if(xoffset>0){xbase=posx+xoffset+border}else if(xoffset<0){xbase=posx+xoffset-width-border}}}else{ybase=posy;switch(this.__align){case null:case"center":xbase=posx-width/2;break;case"right":xbase=posx-width;break;case"left":xbase=posx;break}}var bcolor;if(this.__background==null)bcolor=this.canvas.__background;else bcolor=this.__background;ctx.fillStyle=color.to_html_rgba(bcolor,this.__opacity);ctx.fillRect(xbase-border,ybase-upperchar-border,width+2*border,height+2*border);if((xoffset||yoffset)&&this.__line){ctx.beginPath();if(this.space>0){var v=vec(xoffset,-yoffset,0).norm().multiply(this.space);v=v.add(vec(posx,posy,0));ctx.moveTo(v.x,v.y)}else ctx.moveTo(posx,posy);ctx.lineTo(posx+xoffset,posy-yoffset);ctx.stroke()}if(this.__box){ctx.beginPath();ctx.moveTo(xbase-border,ybase-upperchar-border);ctx.lineTo(xbase+width+border,ybase-upperchar-border);ctx.lineTo(xbase+width+border,ybase-upperchar+height+border);ctx.lineTo(xbase-border,ybase-upperchar+height+border);ctx.closePath();ctx.stroke()}ctx.fillStyle=color.to_html(this.__color||default_color);for(var nth=0;nth<nlines;nth++){var x=xbase+tstart[nth];var y=ybase+dh*nth;ctx.fillText(lines[nth],x,y)}},__change:function(){if(this.canvas!==undefined)this.canvas.__overlay_objects.__changed=true}});function attach_trail(objectOrFunction,options){if(!(this instanceof attach_trail))return new attach_trail(objectOrFunction,options);if(options===undefined)options={};this.__options={};this.__obj=objectOrFunction;if(options.canvas!==undefined)this.canvas=options.canvas;else this.canvas=canvas.selected;var radius=0;if(options.type===undefined){this.type="curve"}else{switch(options.type){case"curve":this.type=options.type;break;case"spheres":case"points":this.type="points";this.__options["size_units"]="world";break;default:throw new Error("attach_trail type must be 'curve' or 'points' (or 'spheres')")}}if(typeof objectOrFunction!=="function"&&typeof objectOrFunction!=="string"){this.canvas=objectOrFunction.canvas;this.__options["color"]=objectOrFunction.color;if(options.radius===undefined){if(this.type=="points")radius=.1*objectOrFunction.size.y}else radius=options.radius}else{if(options.radius!==undefined)radius=options.radius}this.__options["radius"]=this.__radius=radius;this.__options["canvas"]=this.canvas;if(options.color!==undefined){this.__options["color"]=options.color}else this.__options["color"]=vec(1,1,1);this.__options["retain"]=-1;if(options.retain!==undefined){this.__options["retain"]=options.retain}this.pps=0;if(options.pps!==undefined){this.pps=options.pps}this.__options["pickable"]=false;var send={};for(var a in this.__options)send[a]=this.__options[a];if(this.type=="curve")this.__trail=curve(send);else this.__trail=points(send);this.__trails=[this.__trail];this.canvas.trails.push(this);this.__last_pos=null;this.__last_time=null;this.__run=true;this.__elements=0}property.declare(attach_trail.prototype,{color:{get:function(){return this.__options.color},set:function(value){this.__options.color=value}},radius:{get:function(){return this.__options.radius},set:function(value){this.__options.radius=value}},retain:{get:function(){return this.__options.retain},set:function(value){this.__options.retain=value}},start:function(){this.__run=true;var send={};for(var a in this.__options)send[a]=this.__options[a];if(this.type==="curve")this.__trail=curve(send);else this.__trail=points(send);this.__trails.push(this.__trail)},stop:function(){this.__run=false},clear:function(){this.__last_pos=null;this.__last_time=null;this.__elements=0;for(var i=0;i<this.__trails.length;i++)this.__trails[i].clear();if(typeof this.__obj!=="function")this.__obj.__ninterval=0}});function attach_arrow(obj,attr,options){if(!(this instanceof attach_arrow))return new attach_arrow(obj,attr,options);if(options===undefined)options={};if(options.canvas===undefined)options.canvas=obj.canvas;this.obj=obj;this.attr=attr;this.scale=1;if(options.scale!==undefined){this.scale=options.scale;delete options.scale}if(options.color===undefined)options.color=obj.color;this.options=options;var thiscanvas=options.canvas;if(window.__GSlang=="vpython")this.arrow=vp_arrow(this.options);else this.arrow=arrow(this.options);this.arrow.visible=false;this.arrow.pickable=false;this.last_pos=null;this.run=true;this.shaftwidth=this.arrow.shaftwidth;this.color=this.arrow.color;thiscanvas.arrows.push(this);this.start=function(){this.arrow.visible=this.run=true};this.stop=function(){this.arrow.visible=this.run=false}}function rgb_to_css(c){var r=Math.floor(255*c.x).toString();var g=Math.floor(255*c.y).toString();var b=Math.floor(255*c.z).toString();return"rgb("+r+","+g+","+b+")"}var widgetid=0;function radio(args){if(!(this instanceof radio))return new radio(args);var cvs=canvas.get_selected();var attrs={pos:cvs.caption_anchor,checked:false,text:""};if(args.bind!==undefined){attrs.bind=args.bind;delete args.bind}else throw new Error("A radio button must have a bind attribute.");for(a in attrs){if(args[a]!==undefined){attrs[a]=args[a];delete args[a]}}attrs.jradio=$('<input type="radio"/>').css({width:"16px",height:"16px"}).appendTo(attrs.pos).click(function(){attrs.checked=!attrs.checked;$(attrs.jradio).prop("checked",attrs.checked);attrs.bind(cradio)});widgetid++;attrs._id=widgetid.toString();$("<span id="+attrs._id+"> "+attrs.text+"</span>").appendTo(attrs.pos);var cradio={get checked(){return attrs.checked},set checked(value){attrs.checked=value;$(attrs.jradio).prop("checked",value)},get text(){return attrs.text},set text(value){attrs.text=value;$("#"+attrs.id).text(" "+value)}};for(var a in args){cradio[a]=args[a]}cradio.checked=attrs.checked;return cradio}function checkbox(args){if(!(this instanceof checkbox))return new checkbox(args);var cvs=canvas.get_selected();var attrs={pos:cvs.caption_anchor,checked:false,text:""};if(args.bind!==undefined){attrs.bind=args.bind;delete args.bind}else throw new Error("A checkbox must have a bind attribute.");for(a in attrs){if(args[a]!==undefined){attrs[a]=args[a];delete args[a]}}attrs.jcheckbox=$('<input type="checkbox"/>').css({width:"16px",height:"16px"}).appendTo(attrs.pos).click(function(){attrs.checked=!attrs.checked;$(attrs.jcheckbox).prop("checked",attrs.checked);attrs.bind(ccheckbox)});widgetid++;attrs._id=widgetid.toString();$("<span id="+attrs._id+"> "+attrs.text+"</span>").appendTo(attrs.pos);var ccheckbox={get checked(){return attrs.checked},set checked(value){attrs.checked=value;$(attrs.jcheckbox).prop("checked",value)},get text(){return attrs.text},set text(value){attrs.text=value;$("#"+attrs.id).text(" "+value)}};for(var a in args){ccheckbox[a]=args[a]}ccheckbox.checked=attrs.checked;return ccheckbox}function button(args){if(!(this instanceof button))return new button(args);var cvs=canvas.get_selected();var attrs={pos:cvs.caption_anchor,text:" ",textcolor:vec(0,0,0),background:vec(1,1,1),disabled:false};if(args.bind!==undefined){attrs.bind=args.bind;delete args.bind}else throw new Error("A button must have a bind attribute.");for(a in attrs){if(args[a]!==undefined){attrs[a]=args[a];delete args[a]}}attrs.jbutton=$("<button/>").html(attrs.text).appendTo(attrs.pos).css({color:rgb_to_css(attrs.textcolor),backgroundColor:rgb_to_css(attrs.background),"font-size":"15px"}).click(function(){attrs.bind(cbutton)});$(attrs.pos).append(" ");var cbutton={get disabled(){return attrs.disabled},set disabled(value){if(value===0)value=false;else if(value==1)value=true;attrs.disabled=value;$(attrs.jbutton).attr("disabled",attrs.disabled);if(attrs.disabled)$(attrs.jbutton).css({color:rgb_to_css(vec(.7,.7,.7)),backgroundColor:rgb_to_css(vec(1,1,1))});else $(attrs.jbutton).css({color:rgb_to_css(attrs.textcolor),backgroundColor:rgb_to_css(attrs.background)})},get text(){return attrs.text},set text(value){attrs.text=value;$(attrs.jbutton).html(attrs.text)},get textcolor(){return attrs.textcolor},set textcolor(value){attrs.textcolor=value;$(attrs.jbutton).css({color:rgb_to_css(attrs.textcolor)})},get background(){return attrs.background},set background(value){attrs.background=value;$(attrs.jbutton).css({backgroundColor:rgb_to_css(attrs.background)})}};for(var a in args){cbutton[a]=args[a]}cbutton.disabled=attrs.disabled;return cbutton}var slider_id=0;function slider(args){if(!(this instanceof slider))return new slider(args);var cvs=canvas.get_selected();var attrs={pos:cvs.caption_anchor,length:400,width:10,vertical:false,min:0,max:1,align:"left",left:0,right:0,top:0,bottom:0};if(args.bind!==undefined){attrs.bind=args.bind;delete args.bind}else throw new Error("A slider must have a bind attribute.");for(a in attrs){if(args[a]!==undefined){attrs[a]=args[a];delete args[a]}}attrs.step=.001*(attrs.max-attrs.min);if(args.step!==undefined){attrs.step=args.step;delete args.step}attrs.value=attrs.min;if(args.value!==undefined){attrs.value=args.value;delete args.value}attrs._id="s"+slider_id;slider_id+=1;var m=attrs.top+"px "+attrs.right+"px "+attrs.bottom+"px "+attrs.left+"px";var o="horizontal";var w=attrs.length;var h=attrs.width;if(attrs.vertical){o="vertical";w=attrs.width;h=attrs.length}$("<span id="+attrs._id+"></span>").css({width:w,height:h,float:attrs.align,margin:m}).appendTo(attrs.pos);attrs.jslider=$("#"+attrs._id).slider({orientation:o,range:"min",min:attrs.min,max:attrs.max,value:attrs.value,step:attrs.step,change:function(evt){if(evt.originalEvent!==undefined)attrs.bind(cslider)},slide:function(evt){if(evt.originalEvent!==undefined)attrs.bind(cslider)}});var cslider={get min(){return attrs.min},set min(value){throw new Error("Cannot change the min of an existing slider.")},get max(){return attrs.max},set max(value){throw new Error("Cannot change the max of an existing slider.")},get value(){return $(attrs.jslider).slider("value")},set value(val){$(attrs.jslider).slider("value",val)},get width(){return attrs.width},set width(value){throw new Error("Cannot change the width of an existing slider.")},get length(){return attrs.length},set length(value){throw new Error("Cannot change the length of an existing slider.")}};for(var a in args){cslider[a]=args[a]}return cslider}function menu(args){if(!(this instanceof menu))return new menu(args);var cvs=canvas.get_selected();var attrs={pos:cvs.caption_anchor,selected:null};if(args.bind!==undefined){attrs.bind=args.bind;delete args.bind}else throw new Error("A menu must have a bind attribute.");if(args.pos!==undefined){attrs.pos=args.pos;delete args.pos}if(args.choices!==undefined){attrs.choices=args.choices;delete args.choices}else throw new Error("A menu must have a a list of choices.");if(args.selected!==undefined){attrs.selected=args.selected;delete args.selected}var s="";for(var i=0;i<attrs.choices.length;i++){var cc=attrs.choices[i];if(cc===attrs.selected)s+='<option selected="selected">'+cc+"</option>\n";else s+="<option>"+cc+"</option>\n"}attrs.jmenu=$("<select>"+s+"</select>").css("font-size","15px").change(function(){attrs.bind(cmenu)}).appendTo(attrs.pos);$(attrs.pos).append(" ");var cmenu={get selected(){return $(attrs.jmenu).val()},set selected(value){$(attrs.jmenu).val(value)},get choices(){return attrs.choices},set choices(value){throw new Error("The list of choices cannot be changed after creating a menu.")},get index(){return attrs.choices.indexOf($(attrs.jmenu).val())},set index(value){$(attrs.jmenu).val(attrs.choices[value])}};for(var a in args){cmenu[a]=args[a]}return cmenu}eval("0");var exports={box:box,vp_box:vp_box,cylinder:cylinder,vp_cylinder:vp_cylinder,cone:cone,vp_cone:vp_cone,pyramid:pyramid,vp_pyramid:vp_pyramid,sphere:sphere,vp_sphere:vp_sphere,vp_ellipsoid:vp_ellipsoid,arrow:arrow,vp_arrow:vp_arrow,curve:curve,points:points,paths:paths,shapes:shapes,helix:helix,vp_helix:vp_helix,ring:ring,vp_ring:vp_ring,compound:compound,vp_compound:vp_compound,vertex:vertex,triangle:triangle,quad:quad,draw:draw,label:label,distant_light:distant_light,local_light:local_light,attach_trail:attach_trail,attach_arrow:attach_arrow,textures:textures,bumpmaps:bumpmaps,text:text,radio:radio,checkbox:checkbox,button:button,slider:slider,menu:menu};Export(exports)})();(function(){"use strict";function get_library(URL,cb){var tries=0;if(cb===undefined)throw new Error("get_display(URL, wait) called without wait");var done=false;var t1=msclock();$.getScript(URL).done(function(script,textStatus){done=true}).fail(function(jqxhr,settings,exception){alert("Could not access the library\n  "+URL);cb();return});function require_wait(){if(done){cb();return}var t2=msclock();if(t2-t1>6e3){var yes=confirm("Timed out trying to access the library\n  "+URL+"\nTry again?");if(yes){t1=msclock()}else{cb();return}}sleep(.05,require_wait)}require_wait()}function read_local_file(place,cb){var info;if(arguments.length===0){throw new Error("read_local_file(place, wait) called with no arguments")}else if(arguments.length==1){cb=place;if(toType(cb)!=="function")throw new Error("Should be 'read_local_file(wait)'");place=$("body")}else{if(arguments.length>2||toType(cb)!=="function")throw new Error("Should be 'read_local_file(place, wait)'")}place.append('<input type="file" id="read_local_file"/>');var contents=null;function readSingleFile(evt){var f,reader;f=evt.target.files[0];if(f){reader=new FileReader;reader.onload=function(e){contents=e.target.result;var moddate=f.lastModifiedDate?f.lastModifiedDate.toLocaleDateString():"";info={name:f.name,text:contents,size:f.size,type:f.type,date:moddate};$("#read_local_file").remove()};return reader.readAsText(f)}else{alert("Failed to load file");return}}document.getElementById("read_local_file").addEventListener("change",readSingleFile,false);function read_file_wait(){if(contents!==null){cb(null,info);return}sleep(.05,read_file_wait)}read_file_wait()}function update(cb){sleep(0,cb)}function sleep(dt,cb){dt=1e3*dt;function wrapCB(){cb()}if(dt>5)setTimeout(wrapCB,dt-5);else setTimeout(wrapCB,0)}function waitforfonts(cb){function wrapCB(){if(window.__font_sans!==undefined&&window.__font_serif!==undefined)cb();else setTimeout(wrapCB,15)}wrapCB()}function fontloading(){if(window.__font_sans===undefined){var fsans;if(navigator.onLine)fsans="https://s3.amazonaws.com/glowscript/fonts/Roboto-Medium.ttf";else fsans="../lib/FilesInAWS/Roboto-Medium.ttf";opentype_load(fsans,function(err,fontrefsans){if(err)throw new Error("Font "+fsans+" could not be loaded: "+err);window.__font_sans=fontrefsans})}if(window.__font_serif===undefined){var fserif;if(navigator.onLine)fserif="https://s3.amazonaws.com/glowscript/fonts/NimbusRomNo9L-Med.otf";else fserif="../lib/FilesInAWS/NimbusRomNo9L-Med.otf";opentype_load(fserif,function(err,fontrefserif){if(err)throw new Error("Font "+fserif+" could not be loaded: "+err);window.__font_serif=fontrefserif})}}var toType=function(obj){return{}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()};function convert(arg){if(arg instanceof vec){arg=arg.toString()}else if(arg===null){arg="null"}else if(arg===undefined){arg="undefined"}else if(toType(arg)=="object"){var s="{";for(var a in arg)s+=a+":"+arg[a]+", ";arg=s.slice(0,-2)+"}"}else if(toType(arg)=="number"){arg=arg.toPrecision(6);if(arg.match(/e/)){arg=arg.replace(/0*e/,"e");arg=arg.replace(/\.e/,"e")}else if(arg.match(/\./))arg=arg.replace(/0*$/,"");arg=arg.replace(/\.$/,"")}else arg=arg.toString();return arg}var printarea=null;var poptions={width:640,height:100,readonly:true,pos:"bottom"};function modify_printarea(){var w=poptions.width===undefined?640:poptions.width;var h=poptions.height===undefined?100:poptions.height;var readonly=poptions.readonly===undefined?true:poptions.readonly;if(poptions.pos=="right")canvas.container.css({float:"left"});else if(poptions.pos=="bottom")canvas.container.css({clear:"both"});printarea.css("width",w).css("height",h);if(readonly)printarea.attr("readonly","readonly");else printarea.attr("readonly",null)}function print_to_string(args){var s="";var L=arguments.length;for(var i=0;i<L;i++){var arg=arguments[i];if(toType(arg)=="array"){arg=arg.toString()}else if(arg===null){arg="null"}else{arg=convert(arg)}if(s.length===0)s+=arg;else s+=" "+arg}return s}var print_container=$("<div/>");function print(args){if(printarea===null){var container=print_container;container.appendTo($("body"));window.__context.print_container=container;printarea=$('<textarea id=print spellcheck="false"/>').appendTo(container).css("font-family","Verdana","Sans-Serif").css("font-size","100%");modify_printarea()}var sep=" ";var end="\n";var L=arguments.length;var arg=arguments[L-1];if(arg!=null&&arg!==undefined){var isobject=false;if(arg.sep!==undefined){sep=arg.sep;isobject=true}if(arg.end!==undefined){end=arg.end;isobject=true}if(isobject)L--}var s="";for(var i=0;i<L;i++){var arg=arguments[i];if(toType(arg)=="array"){arg=arg.toString()}else if(arg===null){arg="null"}else{arg=convert(arg)}if(s.length===0)s+=arg;else s+=sep+arg}s+=end;printarea.val(printarea.val()+s);printarea.scrollTop(printarea.scrollTop()+1e4)}function print_options(args){var contents="";for(var a in args){poptions[a]=args[a]}if(printarea!==null){if(args.clear!==undefined&&args.clear)printarea.val("");modify_printarea();if(args.contents!==undefined&&args.contents)contents=printarea.val();if(args.delete!==undefined&&args.delete||args.remove!==undefined&&args.remove){printarea.remove();printarea=null}}return contents}window.performance=window.performance||{};function msclock(){if(performance.now)return performance.now();else return(new Date).getTime()}function clock(){return.001*msclock()}function factorial(x){if(x<=0){if(x===0)return 1;else throw new Error("Cannot take factorial of negative number "+x)}var fact=1;var nn=2;while(nn<=x){fact*=nn;nn++}if(nn!=x+1)throw new Error("Argument of factorial must be an integer, not "+x);return fact}function combin(x,y){var z=x-y;var num=1;if(y>z){var temp=y;y=z;z=temp}var nn=z+1;var ny=1;while(nn<=x){num*=nn/ny;nn++;ny++}if(nn!=x+1)throw new Error("Illegal arguments ("+x+","+y+") for combin function");return num}function pa(L){var s="[";for(var i=0;i<L.length;i++){var a=L[i];if(a===undefined)s+="undefined, ";else if(a===null)s+="null ";else if(toType(a)=="array")s+=pa(a);else if(toType(a)=="string")s+=a+", ";else s+=a.toString()+", "}if(s.slice(-2)==", ")s=s.slice(0,-2);return s+"], "}function parsearray(L){if(L===undefined)return"undefined";if(L===null)return"null";return pa(L).slice(0,-2)}Array.prototype.toString=function(){return parsearray(this)};String.prototype.format=function(args){function format_item(arg,op,first,second){function pad(s,first){var p="";for(var i=0;i<first-s.length;i++)p+=" ";return p+s}var formats={b:function(){return pad(arg.toString(2),first)},c:function(){return pad(String.fromCharCode(arg),first)},d:function(){return pad(Math.floor(Math.round(arg)).toString(),first)},e:function(){var v=pad(arg.toExponential(second||6),first);var eloc=v.search("e");var exponent=v.slice(eloc);v=v.slice(0,eloc);if(exponent.length==3)exponent=exponent.slice(0,2)+"0"+exponent.slice(-1);return v+exponent},E:function(){return formats.e()},f:function(){if(second==0)second=6;else if(second==-1)second=0;return pad(arg.toFixed(second),first)},F:function(){return formats.f()},g:function(){if(arg==0)return"0";if(second==0)second=6;var a=Math.abs(arg);var v;if(1e-4<=a&&a<Math.pow(10,second)){if(a<.1){var etype=arg.toExponential(second);etype=etype.replace(".","");var eloc=etype.search("e");var exponent=etype.slice(eloc+2);var val=etype.slice(0,eloc);var length=val.length;if(arg<0){length++;second++}if(length>second)val=val.slice(0,second);var sign="";if(val.slice(0,1)=="-"){sign="-";val=val.slice(1)}v=val.slice(0,second);while(v.slice(-1)=="0")v=v.slice(0,-1);if(exponent==2)return sign+"0.0"+v;else if(exponent==3)return sign+"0.00"+v;else return sign+"0.000"+v}else{if(a>=1)second--;v=formats.e();var eloc=v.search("e");var exponent=Number(v.slice(eloc+1));var val=Number(v.slice(0,eloc));arg=val*pow(10,exponent);v=formats.f();while(v.slice(-1)=="0")v=v.slice(0,-1);if(v.slice(-1)==".")v=v.slice(0,-1);return v}}else{second--;v=formats.e();var eloc=v.search("e");var exponent=v.slice(eloc);v=v.slice(0,eloc);while(v.slice(-1)=="0")v=v.slice(0,-1);if(v.slice(-1)==".")v=v.slice(0,-1);return v+exponent}},G:function(){return formats.g().toUpperCase()},n:function(){return formats.g()},o:function(){return pad(arg.toString(8),first)},s:function(){var t=arg.slice(0,second);for(var i=0;i<first-second;i++)t+=" ";return t},x:function(){return pad(arg.toString(16),first)},X:function(){return formats.x().toUpperCase()},"%":function(){arg*=100;return formats.f()+"%"}};return formats[op]()}var s=this;var values=Array.prototype.slice.call(arguments);var substrings=[];var formats=[];var braces=/(\{[^\}]*\})/g;var start=0;while(true){var m=braces.exec(s);if(m===null){substrings.push(s.slice(start));break}var format=s.slice(m.index+1,braces.lastIndex-1);formats.push(format.replace(/\s*/g,""));substrings.push(s.slice(start,m.index));start=braces.lastIndex}var t="";for(var i=0;i<substrings.length;i++){t+=substrings[i];if(i>=formats.length)break;var f=formats[i];var findex=i;var colon=f.search(":");if(colon<0){if(f.length>0&&f.slice(-1).match(/[a-z]/)!==null)throw new Error('Format error: missing ":" in "{'+f+'}"');if(f.match(/\./)!==null)throw new Error('Format error: should not have "." in "{'+f+'}"');if(f.length>0)findex=Number(f);t+=values[findex].toString()}else{var op=f.slice(-1);if(op.match(/[a-z]/)===null)throw new Error('Format error: final character in "{'+f+'}" must be a letter.');if(colon>0)findex=Number(f.slice(0,colon));f=f.slice(colon+1);var period=f.search(/\./);var first,second;if(period>=0){first=f.slice(0,period);if(first=="")first=0;else first=Number(first);second=Number(f.slice(period+1,-1));if(second===0)second=-1}else{first=f.length>=2?Number(f.slice(0,-1)):0;second=0}t+=format_item(values[findex],op,first,second)}}return t};var exports={sqrt:Math.sqrt,pi:Math.PI,abs:Math.abs,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,exp:Math.exp,log:Math.log,pow:Math.pow,ceil:Math.ceil,floor:Math.floor,max:Math.max,min:Math.min,random:Math.random,round:Math.round,factorial:factorial,combin:combin,radians:function radians(deg){return deg*Math.PI/180},degrees:function degrees(rad){return rad*180/Math.PI},sleep:sleep,waitforfonts:waitforfonts,fontloading:fontloading,update:update,print:print,GSprint:print,print_to_string:print_to_string,print_options:print_options,clock:clock,msclock:msclock,get_library:get_library,read_local_file:read_local_file};Export(exports)})();(function(){"use strict";var font;var otf;var textobj={};var vert={};var Hheights={};var Hheight;var length;var smooth=.95;var meshes;function text3D(a){if(a.text==""||a.text==undefined)throw new Error("A text object needs non-empty text");textobj.canvas=a.canvas===undefined?canvas.selected:a.canvas;textobj.text=a.text;textobj.align=a.align===undefined?"left":a.align;textobj.height=a.height===undefined?1:a.height;textobj.depth=a.depth===undefined?.2*textobj.height:a.depth;if(Math.abs(textobj.depth)<.01*textobj.height)textobj.depth=.01*textobj.height;textobj.pos=a.pos===undefined?vec(0,0,0):a.pos;textobj.font=a.font===undefined?"sans":a.font;textobj.billboard=a.billboard===undefined?false:a.billboard;textobj.color=a.color===undefined?vec(1,1,1):a.color;textobj.opacity=a.opacity===undefined?1:a.opacity;textobj.shininess=a.shininess===undefined?.6:a.shininess;textobj.emissive=a.emissive==undefined?false:a.emissive;textobj.show_start_face=a.show_start_face===undefined?true:a.show_start_face;textobj.show_end_face=a.show_end_face===undefined?true:a.show_end_face;textobj.start_face_color=a.start_face_color===undefined?textobj.color:a.start_face_color;textobj.end_face_color=a.end_face_color===undefined?textobj.color:a.end_face_color;vert.color=textobj.color;vert.emissive=textobj.emissive;meshes=[];otf=false;if(textobj.font=="sans")font=window.__font_sans;else if(textobj.font=="serif"){otf=true;font=window.__font_serif}else throw new Error('The text font must be either "sans" or "serif".');if(font===undefined)throw new Error("Font not available for text object.");var fullName=font.names.fullName.en;if(Hheights[fullName]===undefined){var h=processOneLine("h",0,true);var d=processOneLine("y",0,true);Hheights[fullName]=[h,h-d]}Hheight=Hheights[fullName][0];var descent=Hheights[fullName][1];var lines=textobj.text.split("\n");var liney=0;var maxlength=0;for(var i=0;i<lines.length;i++){liney=-i*1.5*Hheight;processOneLine(lines[i],liney,false);if(length>maxlength)maxlength=length}var compattrs={canvas:textobj.canvas};if(a.length!==undefined)compattrs.length=a.length;var comp;if(window.__GSlang=="vpython")comp=vp_compound(meshes,compattrs);else comp=compound(meshes,compattrs);var args={canvas:textobj.canvas,__text:textobj.text,__align:textobj.align,__height:textobj.height,__depth:textobj.depth,__font:textobj.font,__billboard:textobj.billboard,__color:textobj.color,__shininess:textobj.shininess,__emissive:textobj.emissive,__show_start_face:textobj.show_start_face,__show_end_face:textobj.show_end_face,__start_face_color:textobj.start_face_color,__end_face_color:textobj.end_face_color,__length:maxlength,__descender:descent*textobj.height,__lines:lines.length};delete a.text;delete a.align;delete a.height;delete a.depth;delete a.pos;delete a.font;delete a.billboard;delete a.show_start_face;delete a.show_end_face;delete a.start_face_color;delete a.end_face_color;for(var attr in a)args[attr]=a[attr];return[comp,args]}function processOneLine(line,liney,returnymax){length=0;var ymax=0;var textPath=font.getPath(line,0,-liney,1);var commands=textPath.commands;var set;if(otf)set=fontInspect(line);var contoursT=[];var contoursF=[];var contours=[];var contour=[];var CW=[];for(var i=0;i<commands.length;i++){var cmd=commands[i];switch(cmd.type){case"M":if(contour.length>0){var c0=contour[0];var c=contour[contour.length-1];if(Point.equals(c0,c))contour.pop();contours.push(contour);CW.push(isCW(contour))}contour=[];case"L":contour.push(new Point(cmd.x,cmd.y));if(cmd.x>length)length=cmd.x;if(cmd.y<ymax)ymax=cmd.y;break;case"C":var points=[contour.pop()];points.push(new Point(cmd.x1,cmd.y1));if(cmd.x1>length)length=cmd.x1;if(cmd.y1<ymax)ymax=cmd.y1;if(otf){points.push(new Point(cmd.x2,cmd.y2));points.push(new Point(cmd.x,cmd.y));if(cmd.x>length)length=cmd.x;if(cmd.y<ymax)ymax=cmd.y}else{points.push(new Point(cmd.x,cmd.y));points.push(new Point(cmd.x2,cmd.y2));if(cmd.x2>length)length=cmd.x2;if(cmd.y2<ymax)ymax=cmd.y2}var Bpoints=addBezier(3,points,8);contour=contour.concat(Bpoints);break;case"Q":var points=[contour.pop()];points.push(new Point(cmd.x1,cmd.y1));points.push(new Point(cmd.x,cmd.y));if(cmd.x>length)length=cmd.x;if(cmd.x1>length)length=cmd.x1;if(cmd.y<ymax)ymax=cmd.y;if(cmd.y1<ymax)ymax=cmd.y1;var Bpoints=addBezier(2,points,8);contour=contour.concat(Bpoints);break;case"Z":var c0=contour[0];var c=contour[contour.length-1];if(Point.equals(c0,c))contour.pop();if(otf){if(isCW(contour)){contoursT.push(contour);CW.push(true)}else{contoursF.push(contour);CW.push(false)}}else{contours.push(contour);CW.push(isCW(contour))}contour=[];break}}if(returnymax)return-ymax;length*=textobj.height/Hheight;if(otf){var expConts=[];for(var ci=0;ci<line.length;ci++){var c=line[ci];var clst=set[c];var sum=clst.reduce(function(a,b){return a+b},0);if(clst.length>1&&sum/clst.length<=.51){clst=clst.sort();clst=clst.reverse();expConts.push(clst)}else if(sum/clst.length<.8){var ccharPath=font.getPath(c,100,300,288);var ccommands=ccharPath["commands"];var ccontoursT=[];var ccontoursF=[];var ccontour=[];for(var cmdi=0;cmdi<commands.length;cmdi++){var cmd=commands[cmdi];if(cmd.type=="M"){ccontour=[];ccontour.push(new Point(cmd.x,cmd.y))}else if(cmd.type==="L"||cmd.type==="C"||cmd.type==="Q"){ccontour.push(new Point(cmd.x,cmd.y))}else if(cmd.type==="Z"){ccontour.push(ccontour[0]);if(isCW(ccontour))ccontoursT.push(ccontour);else ccontoursF.push(ccontour)}}for(var i=0;i<ccontoursT.length;i++){pp=[true];for(var j=0;j<ccontoursF.length;j++){if(pinPoly(ccontoursT[i],ccontoursF[j][0]))pp.push(false)}expConts.push(pp)}}else if(sum==clst.length){for(var ppi=0;ppi<clst.length;ppi++){var pp=clst[ppi];expConts.push([pp])}}}for(var i=0;i<expConts.length;i++){var chContour=[];for(var j=0;j<expConts[i].length;j++){if(expConts[i][j])chContour.push(contoursT.shift());else chContour.push(contoursF.shift())}contours.push(chContour)}return getContours(contours,CW,expConts)}else{return getContours(contours,CW,null)}function fontInspect(inputText){var set={};for(var i=0;i<inputText.length;i++)set[inputText[i]]=true;var keys=Object.keys(set);for(var chari=0;chari<keys.length;chari++){var char=keys[chari];var charPath=font.getPath(char,100,300,288);var commands=charPath["commands"];set[char]=[];for(var cmdi=0;cmdi<commands.length;cmdi++){var cmd=commands[cmdi];if(cmd.type=="M"){contour=[];contour.push(new Point(cmd.x,cmd.y))}else if(cmd.type==="L"||cmd.type==="C"||cmd.type==="Q"){contour.push(new Point(cmd.x,cmd.y))}else if(cmd.type==="Z"){contour.push(contour[0]);set[char].push(isCW(contour))}}}return set}}function Bezier2(t,w){var t2=t*t;var mt=1-t;var mt2=mt*mt;return new Point(w[0].x*mt2+w[1].x*2*mt*t+w[2].x*t2,w[0].y*mt2+w[1].y*2*mt*t+w[2].y*t2)}function Bezier3(t,w){var t2=t*t;var t3=t2*t;var mt=1-t;var mt2=mt*mt;var mt3=mt2*mt;return new Point(w[0].x*mt3+3*w[1].x*mt2*t+3*w[2].x*mt*t2+w[3].x*t3,w[0].y*mt3+3*w[1].y*mt2*t+3*w[2].y*mt*t2+w[3].y*t3)}function addBezier(nb,points,nt){var newpoints=[];for(var i=0;i<nt+1;i++){var t=i/nt;if(nb==2)var np=Bezier2(t,points);else if(nb==3)var np=Bezier3(t,points);newpoints.push(np)}return newpoints}function isCW(contour){var area=0;var i=0;while(i<contour.length){var j=(i+1)%contour.length;area+=contour[i].x*contour[j].y;area-=contour[j].x*contour[i].y;i+=1}return area<0}function getContours(contours,CW,expConts){var dx=0;if(textobj.align=="right")dx=-length;else if(textobj.align=="center")dx=-length/2;var dz=textobj.depth;if(otf){for(var i=0;i<contours.length;i++){var chContour=contours[i];if(Point.equals(chContour[0][0],chContour[0][chContour[0].length-1]))chContour[0].pop();if(dz!==0)meshes=meshes.concat(makeQuads(chContour[0],false,dx,dz));var swctx=new SweepContext(chContour[0]);for(j=1;j<chContour.length;j++){if(!expConts[i][j]){if(dz!==0)meshes=meshes.concat(makeQuads(chContour[j],false,dx,dz));if(Point.equals(chContour[j][0],chContour[j][chContour[j].length-1]))chContour[j].pop();swctx.addHole(chContour[j])}}swctx.triangulate();var triangles=swctx.getTriangles();meshes=meshes.concat(makeTriangles(triangles,dx,dz))}}else{var conhole=[];var con=[];var i=0;while(i<contours.length){var contour=contours[i];if(!isCW(contour)){if(con.length>0)conhole.push(con);con=[i]}else{con.push(i)}i+=1}conhole.push(con);for(var i=0;i<conhole.length;i++){var con=conhole[i];if(dz!==0)meshes=meshes.concat(makeQuads(contours[con[0]],false,dx,dz));var swctx=new SweepContext(contours[con[0]]);for(var j=1;j<con.length;j++){swctx.addHole(contours[con[j]]);
  meshes=meshes.concat(makeQuads(contours[con[j]],CW[j],dx,dz))}swctx.triangulate();var triangles=swctx.getTriangles();meshes=meshes.concat(makeTriangles(triangles,dx,dz))}}}function f(p){var val=1e3;var ret=(Math.floor(p.x*val)/val).toString()+","+(Math.floor(p.y*val)/val).toString()+"   ";return ret}function getShapeInfo(slist,inner){var shapeinfo=[];if(!Point.equals(slist[slist.length-1],slist[0]))slist.push(slist[0]);var L=slist.length;var previous=Point.sub(slist[0],slist[L-2]);var v;for(var i=0;i<L;i++){if(i==L-1)v=Point.sub(slist[1],slist[0]);else v=Point.sub(slist[i+1],slist[i]);var a=new Point(previous.y,-previous.x);var b=new Point(v.y,-v.x);a.normalize();b.normalize();previous.normalize();v.normalize();if(inner){a.negate();b.negate()}var c=Point.dot(v,previous);var v1=slist[i];if(c<=smooth){if(i===0){shapeinfo.push({pos:vec(v1.x,v1.y,0),normal:vec(b.x,-b.y,0),smooth:false})}else{shapeinfo.push({pos:vec(v1.x,v1.y,0),normal:vec(a.x,-a.y,0),smooth:false});if(i!=L-1)shapeinfo.push({pos:vec(v1.x,v1.y,0),normal:vec(b.x,-b.y,0),smooth:false})}}else{var n=Point.add(a,b);n.normalize();shapeinfo.push({pos:vec(v1.x,v1.y,0),normal:vec(n.x,-n.y,0),smooth:true})}previous=v}if(Point.equals(slist[slist.length-1],slist[0]))slist.pop();var s=shapeinfo;return shapeinfo}function makeQuads(contour,inner,dx,dz){var shape=getShapeInfo(contour,inner);var K=textobj.height/Hheight;var p0,p1,p2,p3,v0,v1,v2,v3,N0,N2;var Qlist=[];var z1=0;var z2=dz;if(dz<0){z1=dz;z2=0}var lastsmooth=false;for(var i=0;i<shape.length;i++){var s=shape[i];if(!lastsmooth){vert.pos=vec(K*s.pos.x+dx,-K*s.pos.y,z2);vert.normal=s.normal;v0=vertex(vert);vert.pos.z=z1;v1=vertex(vert);lastsmooth=true;continue}vert.pos=vec(K*s.pos.x+dx,-K*s.pos.y,z1);vert.normal=s.normal;v2=vertex(vert);vert.pos.z=z2;v3=vertex(vert);var vs=[v0,v1,v2,v3];Qlist.push(quad({vs:[v0,v1,v2,v3]}));if(s.smooth){v0=v3;v1=v2;lastsmooth=true}else lastsmooth=false}return Qlist}function makeTriangles(tris,dx,dz){var K=textobj.height/Hheight;var Tlist=[];var z,t,p0,p1,p2,v0,v1,v2;for(var ti=0;ti<tris.length;ti++){t=tris[ti];p0=t.getPoint(0);p1=t.getPoint(1);p2=t.getPoint(2);z=dz;if(dz>=0)z=0;if(textobj.show_start_face){vert.color=textobj.start_face_color;if(dz>=0){vert.normal=vec(0,0,-1)}else{vert.normal=vec(0,0,1);z=0}vert.pos=vec(K*p0.x+dx,-K*p0.y,z);v0=vertex(vert);vert.pos=vec(K*p1.x+dx,-K*p1.y,z);v1=vertex(vert);vert.pos=vec(K*p2.x+dx,-K*p2.y,z);v2=vertex(vert);Tlist.push(triangle({vs:[v0,v1,v2]}))}if(dz!==0&&textobj.show_end_face){z=dz;vert.color=textobj.end_face_color;if(dz>0){vert.normal=vec(0,0,1)}else{vert.normal=vec(0,0,-1)}vert.pos=vec(K*p0.x+dx,-K*p0.y,z);var v0=vertex(vert);vert.pos=vec(K*p1.x+dx,-K*p1.y,z);var v1=vertex(vert);vert.pos=vec(K*p2.x+dx,-K*p2.y,z);var v2=vertex(vert);Tlist.push(triangle({vs:[v0,v1,v2]}))}}vert.color=textobj.color;return Tlist}function pinPoly(contour,testp){var i=0;var j=0;var c=0;var nvert=contour.length;for(i=0,j=nvert-1;i<nvert;j=i++){if(contour[i].y>testp.y!=contour[j].y>testp.y&&testp.x<(contour[j].x-contour[i].x)*(testp.y-contour[i].y)/(contour[j].y-contour[i].y)+contour[i].x){c=!c}}return c}function extrusion(args){if(args.canvas!==undefined)args.canvas=args.canvas;else args.canvas=canvas.get_selected();if(args.path===undefined)throw new Error("An extrusion object needs a path attribute.");if(args.shape===undefined)throw new Error("An extrusion object needs a shape attribute.");args.pos=args.pos===undefined?null:args.pos;args.axis=args.axis===undefined?null:args.axis;args.size=args.size===undefined?null:args.size;args.up=args.up===undefined?vec(0,1,0):norm(args.up);args.color=args.color===undefined?color.white:args.color;args.opacity=args.opacity===undefined?1:args.opacity;args.shininess=args.shininess===undefined?.6:args.shininess;args.emissive=args.emissive===undefined?false:args.emissive;args.show_start_face=args.show_start_face===undefined?true:args.show_start_face;args.show_end_face=args.show_end_face===undefined?true:args.show_end_face;args.start_face_color=args.start_face_color===undefined?args.color:args.start_face_color;args.end_face_color=args.end_face_color===undefined?args.color:args.end_face_color;args.smooth=args.smooth===undefined?.95:args.smooth;var vertices=[];var shapeinfo=[];var quads=[];var path_closed=args.path[args.path.length-1].equals(args.path[0]);var sharps=[];var smoothangle=Math.acos(args.smooth);var joints=[];var L=args.path.length;var p=[args.path[0]];for(var i=1;i<L;i++){if(args.path[i].equals(p[p.length-1]))continue;else p.push(args.path[i])}L=args.path.length;var x,y,ipath;var A1,A2,sharp,xaxis,yaxis,xaxis2,yaxis2;var ltex=0;var perp;var alpha;var theta;if(L<2)throw new Error("An extrusion pos must contain more than one distinct point.");if(L==2){A1=norm(p[1].sub(p[0]));yaxis=args.up;xaxis=A1.cross(yaxis);if(xaxis.dot(xaxis)<1e-10){xaxis=yaxis.cross(vec(1,0,0));if(xaxis.dot(xaxis)<1e-10)xaxis=yaxis.cross(vec(0,1,0))}xaxis=norm(xaxis);yaxis=xaxis.cross(A1);joints.push([A1,A1,true,p[0],xaxis,yaxis,xaxis,yaxis,xaxis,yaxis,0]);joints.push([A1,A1,true,p[1],xaxis,yaxis,xaxis,yaxis,xaxis,yaxis,1])}else{for(ipath=0;ipath<L;ipath++){if(ipath===0){A1=p[1].sub(p[0]);yaxis=args.up;xaxis=A1.cross(yaxis);if(xaxis.dot(xaxis)<1e-10){xaxis=yaxis.cross(vec(1,0,0));if(xaxis.dot(xaxis)<1e-10)xaxis=yaxis.cross(vec(0,1,0))}xaxis=norm(xaxis);yaxis=norm(xaxis.cross(A1));joints.push([A1,A1,true,p[ipath],xaxis,yaxis,xaxis,yaxis,xaxis,yaxis,0]);if(!path_closed){sharps.push(0);continue}}else if(ipath==L-1){A1=p[ipath].sub(p[ipath-1]);ltex+=mag(A1);if(path_closed){theta=A1.diff_angle(joints[0][0]);sharp=theta>=smoothangle;if(sharp)sharps.push(ipath);var jcopy=[];for(var j=0;j<joints[0].length;j++)jcopy.push(joints[0][j]);joints.push(jcopy);joints[joints.length-1][10]=ltex}else{x=xaxis;sharps.push(ipath);joints.push([A1,A1,true,p[ipath],x,yaxis,xaxis,yaxis,xaxis,yaxis,ltex])}continue}if(ipath===0){A1=p[0].sub(p[L-2]);A2=p[1].sub(p[0])}else{A1=p[ipath].sub(p[ipath-1]);A2=p[ipath+1].sub(p[ipath])}theta=A2.diff_angle(A1);sharp=theta>=smoothangle;if(ipath>0)ltex+=mag(A1);y=norm(A1.cross(A2));perp=norm(norm(A1).add(norm(A2)));alpha=theta/2;x=norm(y.cross(perp));xaxis2=xaxis.rotate({angle:theta,axis:y});yaxis2=norm(xaxis2.cross(A2));if(ipath===0){var jnt=joints[0];jnt[0]=A1;jnt[1]=A2;jnt[2]=sharp;jnt[4]=x;jnt[5]=y;jnt[6]=xaxis.rotate({angle:-theta,axis:y});jnt[7]=yaxis;jnt[10]=0;continue}joints.push([A1,A2,sharp,p[ipath],x,y,xaxis,yaxis,xaxis2,yaxis2,ltex]);if(sharp){sharps.push(joints.length-1);joints.push([A1,A2,sharp,p[ipath],x,y,xaxis,yaxis,xaxis2,yaxis2,ltex])}xaxis=xaxis2;yaxis=yaxis2}var i,j,starti,start,endi,end,L;if(sharps.length===0){if(path_closed){for(j=1;j<joints.length;j++){if(Math.abs(joints[j][10]-ltex/2)<.001*ltex)break;if(joints[j][10]>ltex/2){j-=1;break}}end=joints[j][10];for(i=0;i<=j;i++)joints[i][10]/=end;L=ltex-end;for(i=j+1;i<joints.length;i++){joints[i][10]=1-(joints[i][10]-end)/L}}else{for(i=0;i<joints.length;i++)joints[i][10]/=ltex}}else{j=0;start=0;starti=0;while(j<sharps.length){endi=sharps[j];end=joints[endi][10];L=end-start;for(var k=starti;k<=endi;k++)joints[k][10]=(joints[k][10]-start)/L;start=end;starti=endi+1;j++;if(j==sharps.length&&path_closed){L=joints[0][10]-start;for(var k=starti;k<joints.length;k++)joints[k][10]=(joints[k][10]-start)/L}}}}var contours=args.shape;var n=level(contours);var xmin,xmax,ymin,ymax;if(n==1)bounding_box([contours]);else if(n==2)bounding_box([contours[0]]);else{var shs=[];for(var nn=0;nn<contours.length;nn++)shs.push(contours[nn][0]);bounding_box(shs)}if(n==1){contours=[contours];make_quads(contours[0],true);endfaces(contours)}else if(n==2){for(var nc=0;nc<contours.length;nc++){make_quads(contours[nc],nc===0)}endfaces(contours)}else{for(var nn=0;nn<contours.length;nn++){var c=contours[nn];for(var nc=0;nc<c.length;nc++){make_quads(c[nc],nc===0)}endfaces(c)}}delete args.path;delete args.shape;delete args.start_face_color;delete args.end_face_color;delete args.show_start_face;delete args.show_end_face;delete args.color;delete args.smooth;delete args.up;if(args.pos===null)delete args.pos;if(args.axis===null)delete args.axis;if(args.size===null)delete args.size;if(window.__GSlang=="vpython")return vp_compound(quads,args);else return compound(quads,args);function level(a){if(a.length===undefined)throw new Error("A shape must be a list of [x,y] elements.");if(typeof a[0]=="number")throw new Error("A shape must be a list of [x,y] elements.");if(typeof a[0][0]=="number")return 1;if(typeof a[0][0][0]=="number")return 2;if(typeof a[0][0][0][0]=="number")return 3;throw new Error("A shape must be a list of lists of [x,y] elements.")}function bounding_box(shs){for(var i=0;i<shs.length;i++){var ystart=null;var shapemin=null;for(var j=0;j<shs[i].length-1;j++){var p=shs[i][j];var x=p[0];var y=p[1];xmin=xmin===undefined?x:Math.min(x,xmin);xmax=xmax===undefined?x:Math.max(x,xmax);ymin=ymin===undefined?y:Math.min(y,ymin);ymax=ymax===undefined?y:Math.max(y,ymax)}}}function find_shape_info(contour,outside){var slist=[];for(var i=0;i<contour.length;i++)slist.push(vec(contour[i][0],contour[i][1],0));var shape_closed=slist[slist.length-1].equals(slist[0]);if(!shape_closed)new Error("An extrusion shape must be a closed curve.");shapeinfo=[];var out=vec(0,0,1);var L=slist.length;var firstsharp=null;var totallength=0;var vs=[],lengths=[],i,v;var miny,minyi;for(i=0;i<L-1;i++){v=slist[i+1].sub(slist[i]);if(miny===undefined||slist[i].y<miny){miny=slist[i].y;minyi=i}var magv=mag(v);totallength+=magv;vs.push(v);lengths.push(magv)}var texval=[];for(i=0;i<lengths.length;i++){lengths[i]/=totallength;texval.push(0)}var d=0;var np=0;for(i=0;i<lengths.length;i++){var j=(minyi+i)%lengths.length;d+=lengths[j];if(d>.5){d-=lengths[j];break}np+=1}var d2=0;for(i=0;i<np;i++){var k=(minyi+i+1)%lengths.length;d2+=lengths[k];texval[k]=d2/d}d2=0;for(i=0;i<lengths.length-np;i++){var k=(j+i+1)%lengths.length;d2+=lengths[k];texval[k]=1-d2/(1-d)}var previous=vs[vs.length-1];var second=false;for(i=0;i<L-1;i++){v=vs[i];var len=lengths[i];var a=previous.cross(out).norm();var b=v.cross(out).norm();if(!outside){a=a.multiply(-1);b=b.multiply(-1)}var c=norm(v).dot(norm(previous));var v1=slist[i];if(c<=args.smooth){if(i===0)firstsharp={pos:v1,normal:a,smooth:false,length:texval[i]};else shapeinfo.push({pos:v1,normal:a,smooth:false,length:texval[i]});shapeinfo.push({pos:v1,normal:b,smooth:false,length:texval[i]})}else{var n=norm(a.add(b));shapeinfo.push({pos:v1,normal:n,smooth:true,length:texval[i]})}previous=v}if(firstsharp!==null)shapeinfo.push(firstsharp)}function generate_vertices(p,x,y,nx,ny,nx2,ny2,sharp,makequads,ltex){for(i=0;i<2;i++){if(i==1){nx=nx2;ny=ny2}var c1=dot(y,ny);var c2=dot(y,nx);var c3=dot(x,ny);var c4=dot(x,nx);var d=c1*c4-c2*c3;var info,v,n,N,a,b,aa,bb,xmin,xmax,ymin,ymax,y;var V=shapeinfo.length;for(var k=0;k<V;k++){info=shapeinfo[k];a=info.pos.x;b=info.pos.y;aa=(a*c1-b*c2)/d;bb=(b*c4-a*c3)/d;v=p.add(x.multiply(aa).add(y.multiply(bb)));n=info.normal;N=norm(nx.multiply(n.x).add(ny.multiply(n.y)));if(i===0){vertices.push(vertex({pos:v,normal:N,color:args.color,texpos:vec(ltex,info.length,0)}))}else{vertices[vertices.length-V+k].normal=norm(vertices[vertices.length-V+k].normal.add(N))}}if(sharp)break}if(makequads){var start=vertices.length-2*V;for(var k=start;k<start+V;k++){if(k==start+V-1){quads.push(quad({v0:vertices[k],v1:vertices[k+V],v2:vertices[start+V],v3:vertices[start]}))}else{quads.push(quad({v0:vertices[k],v1:vertices[k+V],v2:vertices[k+V+1],v3:vertices[k+1]}));if(!shapeinfo[k-start+1].smooth)k++}}}}function make_quads(contour,outside){if(outside||!path_closed){find_shape_info(contour,outside)}else return;var pp,pos;L=joints.length;for(ipath=0;ipath<L;ipath++){pp=joints[ipath];A1=pp[0];A2=pp[1];sharp=pp[2];pos=pp[3];x=pp[4];y=pp[5];xaxis=pp[6];yaxis=pp[7];xaxis2=pp[8];yaxis2=pp[9];ltex=pp[10];if(ipath===0){if(sharp)generate_vertices(pos,x,y,xaxis2,yaxis2,xaxis2,yaxis2,sharp,false,0);else generate_vertices(pos,x,y,xaxis,yaxis,xaxis2,yaxis2,sharp,false,0)}else if(ipath==L-1){if(path_closed){pp=joints[0];sharp=pp[2];pos=pp[3];x=pp[4];y=pp[5];xaxis=pp[6];yaxis=pp[7];xaxis2=pp[8];yaxis2=pp[9];ltex=pp[10];generate_vertices(pos,x,y,xaxis,yaxis,xaxis2,yaxis2,sharp,true,ltex)}else generate_vertices(pos,x,y,xaxis,yaxis,xaxis2,yaxis2,sharp,true,ltex)}else if(sharp){if(ipath>0)generate_vertices(pos,x,y,xaxis,yaxis,xaxis2,yaxis2,true,true,1);if(ipath<L-1)generate_vertices(pos,x,y,xaxis2,yaxis2,xaxis2,yaxis2,true,false,0)}else{generate_vertices(pos,x,y,xaxis,yaxis,xaxis2,yaxis2,false,ipath>0,ltex)}}}function tessellate(contours){var i,j;var c=contours[0];if(c[0][0]===c[c.length-1][0]&&c[0][1]===c[c.length-1][1])c.pop();var pts=[];for(i=0;i<c.length;i++)pts.push(new Point(c[i][0],c[i][1]));var swctx=new SweepContext(pts);for(j=1;j<contours.length;j++){c=contours[j];if(c[0][0]===c[c.length-1][0]&&c[0][1]===c[c.length-1][1])c.pop();pts=[];for(i=0;i<contours[j].length;i++)pts.push(new Point(c[i][0],c[i][1]));swctx.addHole(pts)}function texpos(p){var x=p.x,y=p.y;return vec((x-xmin)/(xmax-xmin),(y-ymin)/(ymax-ymin),0)}swctx.triangulate();var tris=swctx.getTriangles();var p0,p1,p2,t;var N=vec(0,0,1);var tri_indices=[];for(i=0;i<tris.length;i++){t=tris[i];p0=t.getPoint(0);p1=t.getPoint(1);p2=t.getPoint(2);vertices.push(vertex({pos:vec(p0.x,p0.y,0),normal:N,texpos:texpos(p0)}));vertices.push(vertex({pos:vec(p1.x,p1.y,0),normal:N,texpos:texpos(p1)}));vertices.push(vertex({pos:vec(p2.x,p2.y,0),normal:N,texpos:texpos(p2)}));tri_indices.push([3*i,3*i+1,3*i+2])}return tri_indices}function endfaces(contours){if(!path_closed&&(args.show_start_face||args.show_end_face)){var T,js,start=vertices.length;T=tessellate(contours);var faces=[];var L=vertices.length-start;if(args.show_start_face&&!path_closed){var jnt=joints[0];var p=jnt[3];var N=jnt[0];N=N.multiply(-1);var x=jnt[4];var y=jnt[5];for(var k=0;k<L;k++){var vert=vertices[start+k];faces.push([vert.pos.x,vert.pos.y]);var v=p.add(x.multiply(vert.pos.x).add(y.multiply(vert.pos.y)));vertices[start+k].pos=v;vertices[start+k].normal=N;vertices[start+k].color=args.start_face_color}for(var vi=0;vi<T.length;vi++){var vs=T[vi];quads.push(triangle({vs:[vertices[start+vs[0]],vertices[start+vs[1]],vertices[start+vs[2]]]}))}}if(args.show_end_face&&!path_closed){var jnt=joints[joints.length-1];var p=jnt[3];var N=jnt[0];var x=jnt[4];var y=jnt[5];for(var k=0;k<L;k++){if(!args.show_start_face){var vert=vertices[start+k];vert.color=args.end_face_color;var v=p.add(x.multiply(vert.pos.x).add(y.multiply(vert.pos.y)));vertices[start+k].pos=v;vertices[start+k].normal=N}else{var vert=faces[k];var v=p.add(x.multiply(vert[0]).add(y.multiply(vert[1])));vertices.push(vertex({pos:v,normal:N,color:args.end_face_color,texpos:vertices[start+k].texpos}))}}if(args.show_start_face)start+=L;for(var vi=0;vi<T.length;vi++){var vs=T[vi];quads.push(triangle({vs:[vertices[start+vs[0]],vertices[start+vs[1]],vertices[start+vs[2]]]}))}}}}}var exports={text3D:text3D,extrusion:extrusion};Export(exports)})();Export({shaders:{curve_peel_depth_vertex:'// Vertex shader for rendering curve segments, parameterized by\n// pos1, pos2, radius, color\n\n#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec4 pos;       // pos.w is 0 at the beginning of the segment and 1 at the end; \n                          // pos.xyz are relative to that end in a normal basis with x pointing along the segment and scaled by radius\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectShininess objectData[0].w\n#define objectAxis objectData[1].xyz\n#define objectEmissive objectData[1].w\n#define objectUp objectData[2].xyz\n#define flags objectData[2].w\n#define objectScale objectData[3].xyz\n#define objectRadius objectData[3].w\n#define objectColor objectData[4].rgb\n\nuniform vec4 segmentData[4];\n#define segmentPosR(i) segmentData[i]\n#define segmentColor(i) segmentData[2+i]\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nvec4 start;\nvec4 end;\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nmat3 getSegmentRotation() {\n  // Construct the segment rotation matrix.\n    vec3 v = end.xyz - start.xyz;\n    float vmax = max( max( abs(v.x), abs(v.y) ), abs(v.z) );\n    vec3 X = normalize(v/vmax);\n    vec3 Z = cross(X,normalize(vec3(0,1,0)));\n    if ( dot(Z,Z) < 1e-10 ) {\n        Z = cross(X, vec3(1,0,0));\n        if (dot(Z,Z) < 1e-10 ) {\n            Z = cross(X, vec3(0,1,0));\n        }\n    }\n    Z = normalize(Z);\n    return mat3( X, normalize(cross(Z,X)), Z );\n}\n\nvoid main(void) {\n    \n    // The following code looks very clumsy, but all other more sensible schemes \n    // failed due to what might be bugs in shader compiling or execution.\n    // Specifically, trying to set start.w or end.w inside the if statement fails\n    // if the curve radius is less than about 1e-7. After setting the value\n    // inside the if, it\'s zero upon exit from the if. !!?!\n    float sw = 0.0;\n    if (segmentPosR(0).w < 0.0) { // -1 means use the curve global radius\n        sw = 1.0;\n    }\n    start = vec4(segmentPosR(0).xyz, sw*objectRadius + (1.0-sw)*segmentPosR(0).w);\n    sw = 0.0;\n    if (segmentPosR(1).w < 0.0) {\n        sw = 1.0;\n    }\n    end = vec4(segmentPosR(1).xyz, sw*objectRadius + (1.0-sw)*segmentPosR(1).w);\n    \n    mat3 rotObject = getObjectRotation();\n    start.xyz = rotObject*(objectScale*start.xyz) + objectPos;\n    end.xyz = rotObject*(objectScale*end.xyz) + objectPos;\n\n    // A rotation matrix with x pointed along the segment\n    mat3 rot = getSegmentRotation();\n    \n    // The position and radius of "this" end of the segment in world space\n    vec4 ws_segmentEnd = start * (1.-pos.w) + end * pos.w;\n    \n    // The position of this vertex in world space\n    vec3 ws_pos = ws_segmentEnd.xyz + rot * (ws_segmentEnd.w*pos.xyz);\n    \n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    \n    gl_Position = projMatrix * pos4;\n}',curve_pick_vertex:'#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec4 pos;       // pos.w is 0 at the beginning of the segment and 1 at the end; \n                          // pos.xyz are relative to that end in an normal basis with x pointing along the segment and scaled by radius\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectShininess objectData[0].w\n#define objectAxis objectData[1].xyz\n#define objectEmissive objectData[1].w\n#define objectUp objectData[2].xyz\n#define flags objectData[2].w\n#define objectScale objectData[3].xyz\n#define objectRadius objectData[3].w\n#define objectColor objectData[4].rgb\n\nuniform vec4 segmentData[4];\n#define segmentPosR(i) segmentData[i]\n#define segmentColor(i) segmentData[2+i]\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nvarying vec4 vcolor;\n\nvec4 start;\nvec4 end;\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nmat3 getSegmentRotation() {\n    // Construct the object rotation matrix.\n    vec3 v = end.xyz - start.xyz;\n    float vmax = max( max( abs(v.x), abs(v.y) ), abs(v.z) );\n    vec3 X = normalize(v/vmax);\n    vec3 Z = cross(X,normalize(objectUp));\n    if ( dot(Z,Z) < 1e-10 ) {\n        Z = cross(X, vec3(1,0,0));\n        if (dot(Z,Z) < 1e-10 ) {\n            Z = cross(X, vec3(0,1,0));\n        }\n    }\n    Z = normalize(Z);\n    return mat3( X, normalize(cross(Z,X)), Z );\n}\n\nvoid main(void) {\n    vec4 start_color = segmentColor(0);\n    vec4 end_color = segmentColor(1);\n    if (start_color.r < 0.0) start_color.rgb = objectColor;\n    if (end_color.r < 0.0) end_color.rgb = objectColor.rgb;\n    \n    // The following code looks very clumsy, but all other more sensible schemes \n    // failed due to what might be bugs in shader compiling or execution.\n    // Specifically, trying to set start or end inside the if statement fails\n    // if the curve radius is less than about 1e-7 !!??\n    float sw = 0.0;\n    if (segmentPosR(0).w < 0.0) {\n        sw = 1.0;\n    }\n    start = vec4(segmentPosR(0).xyz, sw*objectRadius + (1.0-sw)*segmentPosR(0).w);\n    sw = 0.0;\n    if (segmentPosR(1).w < 0.0) {\n        sw = 1.0;\n    }\n    end = vec4(segmentPosR(1).xyz, sw*objectRadius + (1.0-sw)*segmentPosR(1).w);\n    \n    mat3 rotObject = getObjectRotation();\n    start.xyz = rotObject*(objectScale*start.xyz) + objectPos;\n    end.xyz = rotObject*(objectScale*end.xyz) + objectPos;\n\n    // A rotation matrix with x pointed along the segment\n    mat3 rot = getSegmentRotation();\n\n    // The position and radius of "this" end of the segment in world space\n    vec4 ws_segmentEnd = start * (1.-pos.w) + end * pos.w;\n\n    // The position of this vertex in world space\n    vec3 ws_pos = ws_segmentEnd.xyz + rot * (ws_segmentEnd.w*pos.xyz);\n\n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    vcolor = start_color * (1.-pos.w) + end_color * pos.w;\n    gl_Position = projMatrix * pos4;\n}\n',curve_render_vertex:'// Vertex shader for rendering curve segments, parameterized by\n// pos1, pos2, radius, color\n\n#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec4 pos;       // pos.w is 0 at the beginning of the segment and 1 at the end; \n                          // pos.xyz are relative to that end in a normal basis with x pointing along the segment and scaled by radius\nattribute vec3 normal;\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectShininess objectData[0].w\n#define objectAxis objectData[1].xyz\n#define objectEmissive objectData[1].w\n#define objectUp objectData[2].xyz\n#define flags objectData[2].w\n#define objectScale objectData[3].xyz\n#define objectRadius objectData[3].w\n#define objectColor objectData[4].rgb\n\nuniform vec4 segmentData[4];\n#define segmentPosR(i) segmentData[i]\n#define segmentColor(i) segmentData[2+i]\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump, flipx, flipy, turn\n\nvec4 start;\nvec4 end;\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nmat3 getSegmentRotation() {\n  // Construct the segment rotation matrix.\n    vec3 v = end.xyz - start.xyz;\n    float vmax = max( max( abs(v.x), abs(v.y) ), abs(v.z) );\n    vec3 X = normalize(v/vmax);\n    vec3 Z = cross(X,normalize(vec3(0,1,0)));\n    if ( dot(Z,Z) < 1e-10 ) {\n        Z = cross(X, vec3(1,0,0));\n        if (dot(Z,Z) < 1e-10 ) {\n            Z = cross(X, vec3(0,1,0));\n        }\n    }\n    Z = normalize(Z);\n    return mat3( X, normalize(cross(Z,X)), Z );\n}\n\nvoid main(void) {\n    vec4 start_color = segmentColor(0);\n    vec4 end_color = segmentColor(1);\n    if (start_color.r < 0.0) start_color.rgb = objectColor;\n    if (end_color.r < 0.0) end_color.rgb = objectColor.rgb;\n    \n    // The following code looks very clumsy, but all other more sensible schemes \n    // failed due to what might be bugs in shader compiling or execution.\n    // Specifically, trying to set start.w or end.w inside the if statement fails\n    // if the curve radius is less than about 1e-7. After setting the value\n    // inside the if, it\'s zero upon exit from the if. !!?!\n    float sw = 0.0;\n    if (segmentPosR(0).w < 0.0) { // -1 means use the curve global radius\n        sw = 1.0;\n    }\n    start = vec4(segmentPosR(0).xyz, sw*objectRadius + (1.0-sw)*segmentPosR(0).w);\n    sw = 0.0;\n    if (segmentPosR(1).w < 0.0) {\n        sw = 1.0;\n    }\n    end = vec4(segmentPosR(1).xyz, sw*objectRadius + (1.0-sw)*segmentPosR(1).w);\n    \n    mat3 rotObject = getObjectRotation();\n    start.xyz = rotObject*(objectScale*start.xyz) + objectPos;\n    end.xyz = rotObject*(objectScale*end.xyz) + objectPos;\n\n    // A rotation matrix with x pointed along the segment\n    mat3 rot = getSegmentRotation();\n\n    // The position and radius of "this" end of the segment in world space\n    vec4 ws_segmentEnd = start * (1.-pos.w) + end * pos.w;\n\n    // The position of this vertex in world space\n    vec3 ws_pos = ws_segmentEnd.xyz + rot * (ws_segmentEnd.w*pos.xyz);\n\n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    es_position = pos4.xyz;\n    es_normal = (viewMatrix * vec4(rot * (normal/objectScale), 0.0)).xyz;\n    \n    // no texture or bump map yet for curve object:\n    parameters = vec4(objectShininess, objectEmissive, 0.0, 0.0);\n    mat_pos = vec2(0.0, 0.0);\n    bumpX = vec3(1.0, 0.0, 0.0);\n    \n    vcolor = start_color * (1.-pos.w) + end_color * pos.w;\n    gl_Position = projMatrix * pos4;\n}',extent_vertex:"// Vertex shader for rendering standard 'objects' parameterized by\n// pos, axis, up, scale, color\n\n#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\nattribute vec3 normal;\nattribute vec3 color;\nattribute float opacity;\nattribute vec2 texpos;\nattribute vec3 bumpaxis;\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectShininess objectData[0].w\n#define objectAxis objectData[1].xyz\n#define objectEmissive objectData[1].w\n#define objectUp objectData[2].xyz\n#define flags objectData[2].w\n#define objectScale objectData[3].xyz\n#define objectColor objectData[4].rgba\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\nuniform vec3 center;\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump, flipx, flipy, turn\n\nvec3 encode_float(float k) { // assumes k is >= 0\n    if (k <= 0.0) return vec3(0.0, 0.0, 0.0);\n    float logk = log(k);\n    if (logk < 0.0) {\n        logk = -logk + 128.0;\n    }\n    return vec3(\n        floor(logk)/255.0,\n        floor(256.0*fract(logk))/255.0,\n        floor(256.0*fract(256.0*logk))/255.0);\n}\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nvoid main(void) {\n    mat3 rot = getObjectRotation();\n    // The position of this vertex in world space\n    vec3 ws_pos = rot*(objectScale*position) + objectPos;\n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    es_position = pos4.xyz;\n    es_normal = (viewMatrix * vec4(rot*(normal/objectScale), 0.0)).xyz;\n    //gl_Position = posp;\n    bumpX = (viewMatrix * vec4(rot*bumpaxis, 0.0)).xyz;\n    mat_pos = texpos;\n    float extent = abs(ws_pos.x-center.x);\n    extent = max(abs(ws_pos.y-center.y), extent);\n    extent = max(abs(ws_pos.z-center.z), extent);\n    mat_color = vec4(encode_float(extent), 1.0);\n    // Setting gl_Position.xy to (-1.0, -1.0) should store into pixel (0, 0), but doesn't work:\n    gl_Position = vec4(-1.0, -1.0, 1e-20*extent, 1.0);\n\n    parameters = vec4(objectShininess, objectEmissive, 0.0, 0.0);\n}\n",merge_fragment:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nuniform sampler2D C0; // TEXTURE2 - opaque color map (minormode 4)\nuniform sampler2D C1; // TEXTURE4 - color map for transparency render 1 (minormode 6)\nuniform sampler2D C2; // TEXTURE6 - color map for transparency render 2 (minormode 8)\nuniform sampler2D C3; // TEXTURE8 - color map for transparency render 3 (minormode 10)\nuniform sampler2D C4; // TEXTURE10 - color map for transparency render 4 (minormode 12)\nuniform vec2 canvas_size;\n\nvoid main(void) {\n    // need to combine colors from C0, C1, C2, C3, C4\n    vec2 loc = vec2( gl_FragCoord.x/canvas_size.x, gl_FragCoord.y/canvas_size.y);\n    vec4 c0 = texture2D(C0, loc);\n    vec4 c1 = texture2D(C1, loc);\n    vec4 c2 = texture2D(C2, loc);\n    vec4 c3 = texture2D(C3, loc);\n    vec4 c4 = texture2D(C4, loc);\n    \n    vec3 mcolor = c1.rgb*c1.a + \n                 (1.0-c1.a)*(c2.rgb*c2.a +\n                 (1.0-c2.a)*(c3.rgb*c3.a +\n                 (1.0-c3.a)*(c4.rgb*c4.a + \n                 (1.0-c4.a)*c0.rgb)));\n    gl_FragColor = vec4 (mcolor, 1.0);\n}\n",merge_fragment2:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nuniform sampler2D C0; // TEXTURE2 - opaque color map (minormode 4)\nuniform sampler2D C1; // TEXTURE4 - color map for transparency render 1 (minormode 6)\nuniform vec2 canvas_size;\n\nvoid main(void) {\n    // need to combine colors from C0 and C1\n    // This is used with mobile devices that have few texture image units.\n    vec2 loc = vec2( gl_FragCoord.x/canvas_size.x, gl_FragCoord.y/canvas_size.y);\n    vec4 c0 = texture2D(C0, loc);\n    vec4 c1 = texture2D(C1, loc);    \n    \n    vec3 mcolor = c1.rgb*c1.a + (1.0-c1.a)*c0.rgb;\n    gl_FragColor = vec4 (mcolor, 1.0);\n}\n",merge_vertex:"// Vertex shader for rendering standard 'objects' parameterized by\n// pos, axis, up, size, color\n\n#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\n\nvoid main(void) {\n    gl_Position = vec4(pos, 1.0);\n}\n",opaque_render_fragment:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nuniform int light_count;\nuniform vec4 light_pos[8];\nuniform vec3 light_color[8];\nuniform vec3 light_ambient;\n#define LP(i) light_pos[i]\n#define LC(i) light_color[i]\nuniform vec2 canvas_size;\n\nuniform sampler2D texmap;  // TEXTURE0 - user texture\nuniform sampler2D bumpmap; // TEXTURE1 - user bumpmap\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump\n#define shininess parameters[0]\n#define emissive parameters[1]\n#define hasTexture parameters[2]\n#define hasBump parameters[3]\n\nvec3 normal;\nvec3 pos;\nvec3 diffuse_color;\nvec3 specular_color;\nvec3 color;\n\nvoid calc_color(vec4 lpos, vec3 lcolor)\n{\n    vec3 L = lpos.xyz - pos*lpos.w; // w == 0 for distant_light\n    L = normalize(L);\n    float N = max(dot(normal,L), 0.0);\n    color += (lcolor * N)*diffuse_color;\n    if (shininess > 0.0) {\n        vec3 R = reflect(L,normal);\n        color += specular_color * lcolor * pow(max(dot(R,normalize(pos)),0.0),100.0*shininess);\n    }\n}\n\n// Return lit surface color based on the given surface properties and the lights\n//   specified by the light_* uniforms.\nvoid lightAt()\n{    \n    if (hasTexture != 0.0) {\n        diffuse_color = diffuse_color * texture2D(texmap, mat_pos).xyz;\n    }\n    if (hasBump != 0.0) {\n        vec3 Y = cross(normal, bumpX);\n        vec3 Nb = texture2D(bumpmap, mat_pos).xyz;\n        Nb = 2.0*Nb - 1.0;\n        normal = normalize(Nb.x*bumpX + Nb.y*Y + Nb.z*normal);\n    }\n    if (emissive != 0.0) {\n        // From VPython materials.emissive:\n        float d = dot(normalize(-pos), normal);\n        d = pow(d * 1.5, 0.4) * 1.1;\n        if (d > 1.0) d = 1.0;\n        color = diffuse_color * d;\n        return;\n    }\n    \n    color = light_ambient * diffuse_color;\n    \n    // It was necessary to restructure this shader completely in order to\n    // run on the Samsung Galaxy S3 smartphone. Apparently its compiler\n    // does not handle for loops correctly. An Asus Android tablet was ok.\n    if (light_count == 0) return;\n    calc_color(LP(0), LC(0));\n    if (light_count == 1) return;\n    calc_color(LP(1), LC(1));\n    if (light_count == 2) return;\n    calc_color(LP(2), LC(2));\n    if (light_count == 3) return;\n    calc_color(LP(3), LC(3));\n    if (light_count == 4) return;\n    calc_color(LP(4), LC(4));\n    if (light_count == 5) return;\n    calc_color(LP(5), LC(5));\n    if (light_count == 6) return;\n    calc_color(LP(6), LC(6));\n    if (light_count == 7) return;\n    calc_color(LP(7), LC(7));\n}\n\nvoid main(void) {\n    normal = normalize(es_normal);\n    pos = es_position;\n    diffuse_color = vcolor.rgb;\n    specular_color = vec3(.8,.8,.8);\n    lightAt(); // determine color from lighting\n    gl_FragColor = vec4( color, 1.0 );\n}\n",
  peel_color_fragmentC1:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nuniform int light_count;\nuniform vec4 light_pos[8];\nuniform vec3 light_color[8];\nuniform vec3 light_ambient;\n#define LP(i) light_pos[i]\n#define LC(i) light_color[i]\nuniform vec2 canvas_size;\n\nuniform sampler2D texmap;  // TEXTURE0 - user texture\nuniform sampler2D bumpmap; // TEXTURE1 - user bumpmap\nuniform sampler2D D0; // TEXTURE3 - opaque depth map (minormode 5)\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump\n#define shininess parameters[0]\n#define emissive parameters[1]\n#define hasTexture parameters[2]\n#define hasBump parameters[3]\n\nvec3 normal;\nvec3 pos;\nvec3 diffuse_color;\nvec3 specular_color;\nvec3 color;\n\nvoid calc_color(vec4 lpos, vec3 lcolor)\n{\n    vec3 L = lpos.xyz - pos*lpos.w; // w == 0 for distant_light\n    L = normalize(L);\n    float N = max(dot(normal,L), 0.0);\n    color += (lcolor * N)*diffuse_color;\n    if (shininess > 0.0) {\n        vec3 R = reflect(L,normal);\n        color += specular_color * LC(0) * pow(max(dot(R,normalize(pos)),0.0),100.0*shininess);\n    }\n}\n\n// Return lit surface color based on the given surface properties and the lights\n//   specified by the light_* uniforms.\nvoid lightAt()\n{    \n    if (hasTexture != 0.0) {\n        diffuse_color = diffuse_color * texture2D(texmap, mat_pos).xyz;\n    }\n    if (hasBump != 0.0) {\n        vec3 Y = cross(normal, bumpX);\n        vec3 Nb = texture2D(bumpmap, mat_pos).xyz;\n        Nb = 2.0*Nb - 1.0;\n        normal = normalize(Nb.x*bumpX + Nb.y*Y + Nb.z*normal);\n    }\n    if (emissive != 0.0) {\n        // From VPython materials.emissive:\n        float d = dot(normalize(-pos), normal);\n        d = pow(d * 1.5, 0.4) * 1.1;\n        if (d > 1.0) d = 1.0;\n        color = diffuse_color * d;\n        return;\n    }\n    \n    color = light_ambient * diffuse_color;\n    \n    // It was necessary to restructure this shader completely in order to\n    // run on the Samsung Galaxy S3 smartphone. Apparently its compiler\n    // does not handle for loops correctly. An Asus Android tablet was ok.\n    if (light_count == 0) return;\n    calc_color(LP(0), LC(0));\n    if (light_count == 1) return;\n    calc_color(LP(1), LC(1));\n    if (light_count == 2) return;\n    calc_color(LP(2), LC(2));\n    if (light_count == 3) return;\n    calc_color(LP(3), LC(3));\n    if (light_count == 4) return;\n    calc_color(LP(4), LC(4));\n    if (light_count == 5) return;\n    calc_color(LP(5), LC(5));\n    if (light_count == 6) return;\n    calc_color(LP(6), LC(6));\n    if (light_count == 7) return;\n    calc_color(LP(7), LC(7));\n}\n\nivec4 encode(float k) { // assumes k is >= 0\n    if (k <= 0.0) return ivec4(0, 0, 0, 0);\n    k = 3.0*128.0*k;\n    int b1 = int(k);\n    int b2 = int(256.0*fract(k));\n    return ivec4(\n    \tb1,\n    \tb2,\n    \t0,\n    \t0);\n}\n\nint decode(ivec4 d) {\n    return int(256*d[0] + d[1]);\n}\n\nint fdecode(vec4 d) {\n    return int(255.0*(256.0*d[0] + d[1]));\n}\n\nvoid main(void) {\n    // create transparency color map - C1 (minormode 6), C2 (8), C3 (19), C4 (12)\n    ivec4 c = encode(1.0 - gl_FragCoord.z);\n    int z = decode(c);\n    vec2 loc = vec2(gl_FragCoord.x/canvas_size.x, gl_FragCoord.y/canvas_size.y);\n    int zmin = fdecode(texture2D(D0, loc));\n\n    normal = normalize(es_normal);\n    pos = es_position;\n    diffuse_color = vcolor.rgb;\n    specular_color = vec3(.8,.8,.8);\n    lightAt(); // determine color from lighting\n\t\n\tif (zmin < z) {\n        gl_FragColor = vec4( color, vcolor.a );\n    } else {\n    \tdiscard;\n    }\n}\n",peel_color_fragmentC2:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nuniform int light_count;\nuniform vec4 light_pos[8];\nuniform vec3 light_color[8];\nuniform vec3 light_ambient;\n#define LP(i) light_pos[i]\n#define LC(i) light_color[i]\nuniform vec2 canvas_size;\n\nuniform sampler2D texmap;  // TEXTURE0 - user texture\nuniform sampler2D bumpmap; // TEXTURE1 - user bumpmap\nuniform sampler2D D0; // TEXTURE3 - opaque depth map (minormode 5)\nuniform sampler2D D1; // TEXTURE5 - depth map (minormode 7)\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump\n#define shininess parameters[0]\n#define emissive parameters[1]\n#define hasTexture parameters[2]\n#define hasBump parameters[3]\n\nvec3 normal;\nvec3 pos;\nvec3 diffuse_color;\nvec3 specular_color;\nvec3 color;\n\n\nvoid calc_color(vec4 lpos, vec3 lcolor)\n{\n    vec3 L = lpos.xyz - pos*lpos.w; // w == 0 for distant_light\n    L = normalize(L);\n    float N = max(dot(normal,L), 0.0);\n    color += (lcolor * N)*diffuse_color;\n    if (shininess > 0.0) {\n        vec3 R = reflect(L,normal);\n        color += specular_color * LC(0) * pow(max(dot(R,normalize(pos)),0.0),100.0*shininess);\n    }\n}\n\n// Return lit surface color based on the given surface properties and the lights\n//   specified by the light_* uniforms.\nvoid lightAt()\n{    \n    if (hasTexture != 0.0) {\n        diffuse_color = diffuse_color * texture2D(texmap, mat_pos).xyz;\n    }\n    if (hasBump != 0.0) {\n        vec3 Y = cross(normal, bumpX);\n        vec3 Nb = texture2D(bumpmap, mat_pos).xyz;\n        Nb = 2.0*Nb - 1.0;\n        normal = normalize(Nb.x*bumpX + Nb.y*Y + Nb.z*normal);\n    }\n    if (emissive != 0.0) {\n        // From VPython materials.emissive:\n        float d = dot(normalize(-pos), normal);\n        d = pow(d * 1.5, 0.4) * 1.1;\n        if (d > 1.0) d = 1.0;\n        color = diffuse_color * d;\n        return;\n    }\n    \n    color = light_ambient * diffuse_color;\n    \n    // It was necessary to restructure this shader completely in order to\n    // run on the Samsung Galaxy S3 smartphone. Apparently its compiler\n    // does not handle for loops correctly. An Asus Android tablet was ok.\n    if (light_count == 0) return;\n    calc_color(LP(0), LC(0));\n    if (light_count == 1) return;\n    calc_color(LP(1), LC(1));\n    if (light_count == 2) return;\n    calc_color(LP(2), LC(2));\n    if (light_count == 3) return;\n    calc_color(LP(3), LC(3));\n    if (light_count == 4) return;\n    calc_color(LP(4), LC(4));\n    if (light_count == 5) return;\n    calc_color(LP(5), LC(5));\n    if (light_count == 6) return;\n    calc_color(LP(6), LC(6));\n    if (light_count == 7) return;\n    calc_color(LP(7), LC(7));\n}\n\nivec4 encode(float k) { // assumes k is >= 0\n    if (k <= 0.0) return ivec4(0, 0, 0, 0);\n    k = 3.0*128.0*k;\n    int b1 = int(k);\n    int b2 = int(256.0*fract(k));\n    return ivec4(\n    \tb1,\n    \tb2,\n    \t0,\n    \t0);\n}\n\nint decode(ivec4 d) {\n    return int(256*d[0] + d[1]);\n}\n\nint fdecode(vec4 d) {\n    return int(255.0*(256.0*d[0] + d[1]));\n}\n\nvoid main(void) {\n    // create transparency color map - C1 (minormode 6), C2 (8), C3 (19), C4 (12)\n    ivec4 c = encode(1.0 - gl_FragCoord.z);\n    int z = decode(c);\n    vec2 loc = vec2(gl_FragCoord.x/canvas_size.x, gl_FragCoord.y/canvas_size.y);\n    int zmin = fdecode(texture2D(D0, loc));\n    int zmax = fdecode(texture2D(D1, loc));\n    \n    normal = normalize(es_normal);\n    pos = es_position;\n    diffuse_color = vcolor.rgb;\n    specular_color = vec3(.8,.8,.8);\n    lightAt(); // determine color from lighting\n    \n    if (zmin < z && z < zmax) {\n        gl_FragColor = vec4( color, vcolor.a );\n    } else {\n        discard;\n    }\n}\n",peel_color_fragmentC3:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nuniform int light_count;\nuniform vec4 light_pos[8];\nuniform vec3 light_color[8];\nuniform vec3 light_ambient;\n#define LP(i) light_pos[i]\n#define LC(i) light_color[i]\nuniform vec2 canvas_size;\n\nuniform sampler2D texmap;  // TEXTURE0 - user texture\nuniform sampler2D bumpmap; // TEXTURE1 - user bumpmap\nuniform sampler2D D0; // TEXTURE3 - opaque depth map (minormode 5)\nuniform sampler2D D2; // TEXTURE7 - depth map (minormode 9)\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump\n#define shininess parameters[0]\n#define emissive parameters[1]\n#define hasTexture parameters[2]\n#define hasBump parameters[3]\n\nvec3 normal;\nvec3 pos;\nvec3 diffuse_color;\nvec3 specular_color;\nvec3 color;\n\n\nvoid calc_color(vec4 lpos, vec3 lcolor)\n{\n    vec3 L = lpos.xyz - pos*lpos.w; // w == 0 for distant_light\n    L = normalize(L);\n    float N = max(dot(normal,L), 0.0);\n    color += (lcolor * N)*diffuse_color;\n    if (shininess > 0.0) {\n        vec3 R = reflect(L,normal);\n        color += specular_color * LC(0) * pow(max(dot(R,normalize(pos)),0.0),100.0*shininess);\n    }\n}\n\n// Return lit surface color based on the given surface properties and the lights\n//   specified by the light_* uniforms.\nvoid lightAt()\n{    \n    if (hasTexture != 0.0) {\n        diffuse_color = diffuse_color * texture2D(texmap, mat_pos).xyz;\n    }\n    if (hasBump != 0.0) {\n        vec3 Y = cross(normal, bumpX);\n        vec3 Nb = texture2D(bumpmap, mat_pos).xyz;\n        Nb = 2.0*Nb - 1.0;\n        normal = normalize(Nb.x*bumpX + Nb.y*Y + Nb.z*normal);\n    }\n    if (emissive != 0.0) {\n        // From VPython materials.emissive:\n        float d = dot(normalize(-pos), normal);\n        d = pow(d * 1.5, 0.4) * 1.1;\n        if (d > 1.0) d = 1.0;\n        color = diffuse_color * d;\n        return;\n    }\n    \n    color = light_ambient * diffuse_color;\n    \n    // It was necessary to restructure this shader completely in order to\n    // run on the Samsung Galaxy S3 smartphone. Apparently its compiler\n    // does not handle for loops correctly. An Asus Android tablet was ok.\n    if (light_count == 0) return;\n    calc_color(LP(0), LC(0));\n    if (light_count == 1) return;\n    calc_color(LP(1), LC(1));\n    if (light_count == 2) return;\n    calc_color(LP(2), LC(2));\n    if (light_count == 3) return;\n    calc_color(LP(3), LC(3));\n    if (light_count == 4) return;\n    calc_color(LP(4), LC(4));\n    if (light_count == 5) return;\n    calc_color(LP(5), LC(5));\n    if (light_count == 6) return;\n    calc_color(LP(6), LC(6));\n    if (light_count == 7) return;\n    calc_color(LP(7), LC(7));\n}\n\nivec4 encode(float k) { // assumes k is >= 0\n    if (k <= 0.0) return ivec4(0, 0, 0, 0);\n    k = 3.0*128.0*k;\n    int b1 = int(k);\n    int b2 = int(256.0*fract(k));\n    return ivec4(\n    \tb1,\n    \tb2,\n    \t0,\n    \t0);\n}\n\nint decode(ivec4 d) {\n    return int(256*d[0] + d[1]);\n}\n\nint fdecode(vec4 d) {\n    return int(255.0*(256.0*d[0] + d[1]));\n}\n\nvoid main(void) {\n    // create transparency color map - C1 (minormode 6), C2 (8), C3 (19), C4 (12)\n    ivec4 c = encode(1.0 - gl_FragCoord.z);\n    int z = decode(c);\n    vec2 loc = vec2(gl_FragCoord.x/canvas_size.x, gl_FragCoord.y/canvas_size.y);\n    int zmin = fdecode(texture2D(D0, loc));\n    int zmax = fdecode(texture2D(D2, loc));\n    \n    normal = normalize(es_normal);\n    pos = es_position;\n    diffuse_color = vcolor.rgb;\n    specular_color = vec3(.8,.8,.8);\n    lightAt(); // determine color from lighting\n    \n    if (zmin < z && z < zmax) {\n        gl_FragColor = vec4( color, vcolor.a );\n    } else {\n        discard;\n    }\n}\n",peel_color_fragmentC4:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nuniform int light_count;\nuniform vec4 light_pos[8];\nuniform vec3 light_color[8];\nuniform vec3 light_ambient;\n#define LP(i) light_pos[i]\n#define LC(i) light_color[i]\nuniform vec2 canvas_size;\n\nuniform sampler2D texmap;  // TEXTURE0 - user texture\nuniform sampler2D bumpmap; // TEXTURE1 - user bumpmap\nuniform sampler2D D0; // TEXTURE3 - opaque depth map (minormode 5)\nuniform sampler2D D3; // TEXTURE9 - depth map (minormode 11)\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump\n#define shininess parameters[0]\n#define emissive parameters[1]\n#define hasTexture parameters[2]\n#define hasBump parameters[3]\n\nvec3 normal;\nvec3 pos;\nvec3 diffuse_color;\nvec3 specular_color;\nvec3 color;\n\nvoid calc_color(vec4 lpos, vec3 lcolor)\n{\n    vec3 L = lpos.xyz - pos*lpos.w; // w == 0 for distant_light\n    L = normalize(L);\n    float N = max(dot(normal,L), 0.0);\n    color += (lcolor * N)*diffuse_color;\n    if (shininess > 0.0) {\n        vec3 R = reflect(L,normal);\n        color += specular_color * LC(0) * pow(max(dot(R,normalize(pos)),0.0),100.0*shininess);\n    }\n}\n\n// Return lit surface color based on the given surface properties and the lights\n//   specified by the light_* uniforms.\nvoid lightAt()\n{    \n    if (hasTexture != 0.0) {\n        diffuse_color = diffuse_color * texture2D(texmap, mat_pos).xyz;\n    }\n    if (hasBump != 0.0) {\n        vec3 Y = cross(normal, bumpX);\n        vec3 Nb = texture2D(bumpmap, mat_pos).xyz;\n        Nb = 2.0*Nb - 1.0;\n        normal = normalize(Nb.x*bumpX + Nb.y*Y + Nb.z*normal);\n    }\n    if (emissive != 0.0) {\n        // From VPython materials.emissive:\n        float d = dot(normalize(-pos), normal);\n        d = pow(d * 1.5, 0.4) * 1.1;\n        if (d > 1.0) d = 1.0;\n        color = diffuse_color * d;\n        return;\n    }\n    \n    color = light_ambient * diffuse_color;\n    \n    // It was necessary to restructure this shader completely in order to\n    // run on the Samsung Galaxy S3 smartphone. Apparently its compiler\n    // does not handle for loops correctly. An Asus Android tablet was ok.\n    if (light_count == 0) return;\n    calc_color(LP(0), LC(0));\n    if (light_count == 1) return;\n    calc_color(LP(1), LC(1));\n    if (light_count == 2) return;\n    calc_color(LP(2), LC(2));\n    if (light_count == 3) return;\n    calc_color(LP(3), LC(3));\n    if (light_count == 4) return;\n    calc_color(LP(4), LC(4));\n    if (light_count == 5) return;\n    calc_color(LP(5), LC(5));\n    if (light_count == 6) return;\n    calc_color(LP(6), LC(6));\n    if (light_count == 7) return;\n    calc_color(LP(7), LC(7));\n}\n\nivec4 encode(float k) { // assumes k is >= 0\n    if (k <= 0.0) return ivec4(0, 0, 0, 0);\n    k = 3.0*128.0*k;\n    int b1 = int(k);\n    int b2 = int(256.0*fract(k));\n    return ivec4(\n    \tb1,\n    \tb2,\n    \t0,\n    \t0);\n}\n\nint decode(ivec4 d) {\n    return int(256*d[0] + d[1]);\n}\n\nint fdecode(vec4 d) {\n    return int(255.0*(256.0*d[0] + d[1]));\n}\n\nvoid main(void) {\n    // create transparency color map - C1 (minormode 6), C2 (8), C3 (19), C4 (12)\n    ivec4 c = encode(1.0 - gl_FragCoord.z);\n    int z = decode(c);\n    vec2 loc = vec2(gl_FragCoord.x/canvas_size.x, gl_FragCoord.y/canvas_size.y);\n    int zmin = fdecode(texture2D(D0, loc));\n    int zmax = fdecode(texture2D(D3, loc));\n    \n    normal = normalize(es_normal);\n    pos = es_position;\n    diffuse_color = vcolor.rgb;\n    specular_color = vec3(.8,.8,.8);\n    lightAt(); // determine color from lighting\n    \n    if (zmin < z && z < zmax) {\n        gl_FragColor = vec4( color, vcolor.a );\n    } else {\n        discard;\n    }\n}\n",peel_depth_fragmentD0:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\n// Construct depth maps for depth peeling handling of opacity\n\n// minormode = 0 render, 1 pick, 2 autoscale, 4 C0, 5 D0, 6 C1, 7 D1, 8 C2, 9 D2, 10 C3, 11 D3, 12 C4\n\nivec4 encode(float k) { // assumes k is >= 0\n    if (k <= 0.0) return ivec4(0, 0, 0, 0);\n    k = 3.0*128.0*k;\n    int b1 = int(k);\n    int b2 = int(256.0*fract(k));\n    return ivec4(\n    \tb1,\n    \tb2,\n    \t0,\n    \t0);\n}\n\nvoid main(void) {\n    // create depth map D0 (5)\n    ivec4 c = encode(1.0 - gl_FragCoord.z);\n    gl_FragColor = vec4(float(c.r)/255.0, float(c.g)/255.0, 0, 0);\n}",peel_depth_fragmentD1:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\n// Construct depth maps for depth peeling handling of opacity\n\nuniform vec2 canvas_size;\nuniform sampler2D D0; // TEXTURE3 - opaque depth map (minormode 5)\n\n// minormode = 0 render, 1 pick, 2 autoscale, 4 C0, 5 D0, 6 C1, 7 D1, 8 C2, 9 D2, 10 C3, 11 D3, 12 C4\n\nivec4 encode(float k) { // assumes k is >= 0\n    if (k <= 0.0) return ivec4(0, 0, 0, 0);\n    k = 3.0*128.0*k;\n    int b1 = int(k);\n    int b2 = int(256.0*fract(k));\n    return ivec4(\n    \tb1,\n    \tb2,\n    \t0,\n    \t0);\n}\n\nint decode(ivec4 d) {\n    return int(256*d[0] + d[1]);\n}\n\nint fdecode(vec4 d) {\n    return int(255.0*(256.0*d[0] + d[1]));\n}\n\nvoid main(void) {\n    // create depth map D1 (6)\n    ivec4 c = encode(1.0 - gl_FragCoord.z);\n    int z = decode(c);\n    vec2 loc = vec2(gl_FragCoord.x/canvas_size.x, gl_FragCoord.y/canvas_size.y);\n    int zmin = fdecode(texture2D(D0, loc));\n    if (zmin < z) {\n        gl_FragColor = vec4(float(c.r)/255.0, float(c.g)/255.0, 0, 0);\n    } else {\n        discard;\n    }\n}\n",peel_depth_fragmentD2:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\n// Construct depth maps for depth peeling handling of opacity\n\nuniform vec2 canvas_size;\nuniform sampler2D D0; // TEXTURE3 - opaque depth map (minormode 5)\nuniform sampler2D D1; // TEXTURE5 - 1st transparency depth map (minormode 7)\n\n// minormode = 0 render, 1 pick, 2 autoscale, 4 C0, 5 D0, 6 C1, 7 D1, 8 C2, 9 D2, 10 C3, 11 D3, 12 C4\n\nivec4 encode(float k) { // assumes k is >= 0\n    if (k <= 0.0) return ivec4(0, 0, 0, 0);\n    k = 3.0*128.0*k;\n    int b1 = int(k);\n    int b2 = int(256.0*fract(k));\n    return ivec4(\n    \tb1,\n    \tb2,\n    \t0,\n    \t0);\n}\n\nint decode(ivec4 d) {\n    return int(256*d[0] + d[1]);\n}\n\nint fdecode(vec4 d) {\n    return int(255.0*(256.0*d[0] + d[1]));\n}\n\nvoid main(void) {\n    // create depth map D2 (7)\n    ivec4 c = encode(1.0 - gl_FragCoord.z);\n    int z = decode(c);\n    vec2 loc = vec2(gl_FragCoord.x/canvas_size.x, gl_FragCoord.y/canvas_size.y);\n    int zmin = fdecode(texture2D(D0, loc));\n    int zmax = fdecode(texture2D(D1, loc));\n    if (zmin < z && z < zmax) {\n    \tgl_FragColor = vec4(float(c.r)/255.0, float(c.g)/255.0, 0, 0);\n    } else {\n        discard;\n    }\n}",peel_depth_fragmentD3:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\n// Construct depth maps for depth peeling handling of opacity\n\nuniform vec2 canvas_size;\nuniform sampler2D D0; // TEXTURE3 - opaque depth map (minormode 5)\nuniform sampler2D D2; // TEXTURE7 - 2nd transparency depth map (minormode 9)\n\n// minormode = 0 render, 1 pick, 2 autoscale, 4 C0, 5 D0, 6 C1, 7 D1, 8 C2, 9 D2, 10 C3, 11 D3, 12 C4\n\nivec4 encode(float k) { // assumes k is >= 0\n    if (k <= 0.0) return ivec4(0, 0, 0, 0);\n    k = 3.0*128.0*k;\n    int b1 = int(k);\n    int b2 = int(256.0*fract(k));\n    return ivec4(\n    \tb1,\n    \tb2,\n    \t0,\n    \t0);\n}\n\nint decode(ivec4 d) {\n    return int(256*d[0] + d[1]);\n}\n\nint fdecode(vec4 d) {\n    return int(255.0*(256.0*d[0] + d[1]));\n}\n\nvoid main(void) {\n    // create depth map D3 (8)\n    ivec4 c = encode(1.0 - gl_FragCoord.z);\n    int z = decode(c);\n    vec2 loc = vec2(gl_FragCoord.x/canvas_size.x, gl_FragCoord.y/canvas_size.y);\n    int zmin = fdecode(texture2D(D0, loc));\n    int zmax = fdecode(texture2D(D2, loc));\n    if (zmin < z && z < zmax) {\n        gl_FragColor = vec4(float(c.r)/255.0, float(c.g)/255.0, 0, 0);\n    } else {\n        discard;\n    }\n}",peel_depth_vertex:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectShininess objectData[0].w\n#define objectAxis objectData[1].xyz\n#define objectEmissive objectData[1].w\n#define objectUp objectData[2].xyz\n#define flags objectData[2].w\n#define objectScale objectData[3].xyz\n#define objectColor objectData[4].rgba\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nvoid main(void) {\n    mat3 rot = getObjectRotation();\n    // The position of this vertex in world space\n    vec3 ws_pos = rot*(objectScale*pos) + objectPos;\n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    gl_Position = projMatrix * pos4;\n}\n",pick_fragment:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nvarying vec4 vcolor;\n\nvoid main(void) {\n    gl_FragColor = vcolor;\n}\n",pick_vertex:"// Vertex shader for picking standard 'objects' parameterized by\n// pos, axis, up, size, color\n\n#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectAxis objectData[1].xyz\n#define objectUp objectData[2].xyz\n#define objectScale objectData[3].xyz\n#define objectColor objectData[4].rgba\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nvarying vec4 vcolor;\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nvoid main(void) {\n    mat3 rot = getObjectRotation();\n    // The position of this vertex in world space\n    vec3 ws_pos = rot*(objectScale*pos) + objectPos;\n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    gl_Position = projMatrix * pos4;\n    vcolor = objectColor;\n}\n",render_vertex:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\nattribute vec3 normal;\nattribute vec3 color;\nattribute float opacity;\nattribute float shininess;\nattribute float emissive;\nattribute vec2 texpos;\nattribute vec3 bumpaxis;\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectShininess objectData[0].w\n#define objectAxis objectData[1].xyz\n#define objectEmissive objectData[1].w\n#define objectUp objectData[2].xyz\n#define flags objectData[2].w\n#define objectScale objectData[3].xyz\n#define objectColor objectData[4].rgba\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump, flipx, flipy, turn\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nvoid main(void) {\n    mat3 rot = getObjectRotation();\n    // The position of this vertex in world space\n    vec3 ws_pos = rot*(objectScale*pos) + objectPos;\n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    es_position = pos4.xyz;\n    es_normal = (viewMatrix * vec4(rot*(normal/objectScale), 0.0)).xyz;\n    gl_Position = projMatrix * pos4;\n    bumpX = (viewMatrix * vec4(rot*bumpaxis, 0.0)).xyz;\n    mat_pos = texpos;\n    vcolor = vec4(color*objectColor.rgb, opacity*objectColor.a);\n    \n    float f = flags; // turn, flipy, flipx, sides, right, left, bumpmap, texture\n    float turn = floor(f/128.0);\n    f -= 128.0*turn;\n    float flipy = floor(f/64.0);\n    f -= 64.0*flipy;\n    float flipx = floor(f/32.0);\n    f -= 32.0*flipx;\n    float sides = floor(f/16.0);\n    f -= 16.0*sides;\n    float right = floor(f/8.0);\n    f -= 8.0*right;\n    float left = floor(f/4.0);\n    f -= 4.0*left;\n    float B = floor(f/2.0);\n    f -= 2.0*B;\n    float T = f;\n    if (T != 0.0) {\n        if (flipx != 0.0) {\n            mat_pos.x = 1.0 - mat_pos.x;\n        }\n        if (flipy != 0.0) {\n            mat_pos.y = 1.0 - mat_pos.y;\n        }\n        if (turn > 0.0 && turn <= 3.0) {\n            if (turn == 1.0) {\n                mat_pos = vec2(mat_pos.y,1.0 - mat_pos.x);\n            } else if (turn == 2.0) {\n                mat_pos = vec2(1.0 - mat_pos.x,1.0 - mat_pos.y);\n            } else {\n                mat_pos = vec2(1.0 - mat_pos.y,mat_pos.x);\n            }\n        }\n        T = 0.0;\n        bool L = (normal.x == -1.0);\n        bool R = (normal.x == 1.0);\n        bool S = !L && !R;\n        if (L && left == 1.0) T = 1.0;\n        if (R && right == 1.0) T = 1.0;\n        if (S && sides == 1.0) T = 1.0;\n        if (T == 0.0) {\n            B = 0.0;\n        } else if (left == 0.0 || right == 0.0 || sides == 0.0) {\n            // don't mix texture and object color if texture doesn't cover entire object\n            vcolor = vec4(1.0, 1.0, 1.0, 1.0);\n        }\n    }\n    float emit = 0.0;\n    if (objectEmissive != 0.0) emit = 1.0;\n    if (emissive != 0.0) emit = 1.0;\n    parameters = vec4(objectShininess * shininess, emit, T, B);\n}\n",ring_peel_depth_vertex:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\nattribute vec3 normal;\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectShininess objectData[0].w\n#define objectAxis objectData[1].xyz\n#define objectEmissive objectData[1].w\n#define objectUp objectData[2].xyz\n#define flags objectData[2].w\n#define objectScale objectData[3].xyz\n#define objectColor objectData[4].rgba\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nvoid main(void) {\n\tmat3 rot = getObjectRotation();\n\t// See mesh.js for details on mesh; default radius of cross section is 0.05 (default outer radius is 0.5)\n    vec3 r = normal*objectScale;           // from center of ring to outer edge of circular cross section\n    vec3 n = normalize(r/objectScale);     // lies in the plane of the cross section at this location, perpendicular to outer edge\n    vec3 adjpos = r + (objectScale.x/0.1)*(pos.x*vec3(1,0,0) + pos.z*n);    // vertex in world coordinates\n    \n    vec3 ws_pos = rot*(adjpos) + objectPos;  // point in world space\n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    gl_Position = projMatrix * pos4;\n}\n",ring_pick_vertex:"// Vertex shader for picking standard 'objects' parameterized by\n// pos, axis, up, size, color\n\n#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\nattribute vec3 normal;\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectAxis objectData[1].xyz\n#define objectUp objectData[2].xyz\n#define objectScale objectData[3].xyz\n#define objectColor objectData[4].rgba\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nvarying vec4 vcolor;\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nvoid main(void) {\n\tmat3 rot = getObjectRotation();\n\t// See mesh.js for details on mesh; default radius of cross section is 0.05 (default outer radius is 0.5)\n    vec3 r = normal*objectScale;           // from center of ring to outer edge of circular cross section\n    vec3 n = normalize(r/objectScale);     // lies in the plane of the cross section at this location, perpendicular to outer edge\n    vec3 adjpos = r + (objectScale.x/0.1)*(pos.x*vec3(1,0,0) + pos.z*n);    // vertex in world coordinates\n    \n    vec3 ws_pos = rot*(adjpos) + objectPos;  // point in world space\n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    gl_Position = projMatrix * pos4;\n    vcolor = objectColor;\n}\n",ring_render_vertex:"#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\nattribute vec3 normal;\nattribute vec3 color;\nattribute float opacity;\nattribute float shininess;\nattribute float emissive;\nattribute vec2 texpos;\nattribute vec3 bumpaxis;\n\nuniform vec4 objectData[5];\n#define objectPos objectData[0].xyz\n#define objectShininess objectData[0].w\n#define objectAxis objectData[1].xyz\n#define objectEmissive objectData[1].w\n#define objectUp objectData[2].xyz\n#define flags objectData[2].w\n#define objectScale objectData[3].xyz\n#define objectColor objectData[4].rgba\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump, flipx, flipy, turn\n\nmat3 getObjectRotation() { // Construct the object rotation matrix.\n    // Divide objectAxis by its largest component before normalizing,\n    // to avoid problems with very large or very small magnitudes.\n    float vmax = max( max( abs(objectAxis.x), abs(objectAxis.y) ), abs(objectAxis.z) );\n    vec3 X = normalize(objectAxis/vmax);\n    vec3 Y = normalize(objectUp);\n    // Note that axis and up are kept perpendicular to each other by CPU code.\n    return mat3( X, Y, cross(X,Y));\n}\n\nvoid main(void) {\n\tmat3 rot = getObjectRotation();\n\t// See mesh.js for details on mesh; default radius of cross section is 0.05 (default outer radius is 0.5)\n    vec3 r = normal*objectScale;  // from center of ring to outer edge of circular cross section\n    vec3 n = normalize(normal);   // lies in the plane of the cross section at this location, perpendicular to outer edge\n    vec3 adjpos = r + (objectScale.x/0.1)*(pos.x*vec3(1,0,0) + pos.z*n);    // vertex in world coordinates\n    vec3 N = adjpos - (r-0.5*objectScale.x*n);                              // normal in world coordinates\n    \n    vec3 ws_pos = rot*(adjpos) + objectPos;  // point in world space\n    vec4 pos4 = viewMatrix * vec4( ws_pos, 1.0);\n    es_position = pos4.xyz;\n    es_normal = (viewMatrix * vec4(rot*N, 0.0)).xyz;\n    gl_Position = projMatrix * pos4;\n    bumpX = (viewMatrix * vec4(rot*bumpaxis, 0.0)).xyz;\n    mat_pos = texpos;\n    vcolor = vec4(color*objectColor.rgb, opacity*objectColor.a);\n    \n    float f = flags; // turn, flipy, flipx, sides, right, left, bumpmap, texture\n    float turn = floor(f/128.0);\n    f -= 128.0*turn;\n    float flipy = floor(f/64.0);\n    f -= 64.0*flipy;\n    float flipx = floor(f/32.0);\n    f -= 32.0*flipx;\n    float sides = floor(f/16.0);\n    f -= 16.0*sides;\n    float right = floor(f/8.0);\n    f -= 8.0*right;\n    float left = floor(f/4.0);\n    f -= 4.0*left;\n    float B = floor(f/2.0);\n    f -= 2.0*B;\n    float T = f;\n    if (T != 0.0) {\n        if (flipx != 0.0) {\n            mat_pos.x = 1.0 - mat_pos.x;\n        }\n        if (flipy != 0.0) {\n            mat_pos.y = 1.0 - mat_pos.y;\n        }\n        if (turn > 0.0 && turn <= 3.0) {\n            if (turn == 1.0) {\n                mat_pos = vec2(mat_pos.y,1.0 - mat_pos.x);\n            } else if (turn == 2.0) {\n                mat_pos = vec2(1.0 - mat_pos.x,1.0 - mat_pos.y);\n            } else {\n                mat_pos = vec2(1.0 - mat_pos.y,mat_pos.x);\n            }\n        }\n        T = 0.0;\n        bool L = (normal.x == -1.0);\n        bool R = (normal.x == 1.0);\n        bool S = !L && !R;\n        if (L && left == 1.0) T = 1.0;\n        if (R && right == 1.0) T = 1.0;\n        if (S && sides == 1.0) T = 1.0;\n        if (T == 0.0) {\n            B = 0.0;\n        } else if (left == 0.0 || right == 0.0 || sides == 0.0) {\n            // don't mix texture and object color if texture doesn't cover entire object\n            vcolor = vec4(1.0, 1.0, 1.0, 1.0);\n        }\n    }\n    float emit = 0.0;\n    if (objectEmissive != 0.0) emit = 1.0;\n    if (emissive != 0.0) emit = 1.0;\n    parameters = vec4(objectShininess * shininess, emit, T, B);\n}\n",
  tri_peel_depth_vertex:"// Vertex shader for rendering triangles\n\n#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nvoid main(void) {\n    gl_Position = projMatrix * viewMatrix * vec4( pos, 1.0);\n}\n",tri_pick_vertex:"// Vertex shader for picking triangles\n\n#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\nattribute vec4 color;\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\n\nvarying vec4 vcolor;\n\nvoid main(void) {\n    gl_Position = projMatrix * viewMatrix * vec4( pos, 1.0);\n    vcolor = color;\n}\n",tri_render_vertex:"// Vertex shader for rendering triangles\n\n#ifdef GL_ES\n#  ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#  else\nprecision mediump float;\n#  endif\n#endif\n\nattribute vec3 pos;\nattribute vec3 normal;\nattribute vec3 color;\nattribute float opacity;\nattribute float shininess;\nattribute float emissive;\nattribute vec2 texpos;\nattribute vec3 bumpaxis;\n\nuniform mat4 viewMatrix;\nuniform mat4 projMatrix;\nuniform float T; // 1.0 if there is a texture, else 0.0\nuniform float B; // 1.0 if there is a bumpmap, else 0.0\n\nvarying vec3 es_position;     // eye space surface position\nvarying vec3 es_normal;       // eye space surface normal\nvarying vec2 mat_pos;         // surface material position in [0,1]^2\nvarying vec4 vcolor;\nvarying vec3 bumpX;\nvarying vec4 parameters; // shininess, emissive, hasTexture, hasBump\n\nvoid main(void) {\n    vec4 pos4 = viewMatrix * vec4( pos, 1.0);\n    es_position = pos4.xyz;\n    es_normal = (viewMatrix * vec4(normal, 0.0)).xyz;\n    gl_Position = projMatrix * pos4;\n    bumpX = (viewMatrix * vec4(bumpaxis, 0.0)).xyz;\n    mat_pos = texpos;\n    vcolor = vec4(color, opacity);\n    parameters = vec4(shininess, emissive, T, B);\n}\n"}});if(!Object.create||!Object.defineProperty||!Object.defineProperties)alert("Example will fail because your browser does not support ECMAScript 5. Try with another browser!");var __filename=""+window.location;window.Streamline={globals:{}};function srequire(str){if(str=="streamline/lib/util/flows")return Streamline.flows;else if(str=="streamline/lib/globals")return Streamline.globals;else if(str=="streamline/lib/version")return Streamline.version;else if(str=="streamline/lib/callbacks/runtime")return Streamline.runtime;else if(str=="streamline/lib/callbacks/transform")return Streamline;else if(str=="streamline/lib/callbacks/builtins")return Streamline.builtins;else if(str=="streamline/lib/util/future")return Streamline.future;else if(str=="streamline/lib/util/source-map")return Streamline.sourceMap.exports;else throw new Error("Cannot require "+str)}(function(){var narcissus={options:{version:185},hostGlobal:this};Narcissus=narcissus})();Narcissus.definitions=function(){var tokens=["END","\n",";",",","=","?",":","CONDITIONAL","||","&&","|","^","&","==","!=","===","!==","<","<=",">=",">","<<",">>",">>>","+","-","*","/","%","!","~","UNARY_PLUS","UNARY_MINUS","++","--",".","[","]","{","}","(",")","SCRIPT","BLOCK","LABEL","FOR_IN","CALL","NEW_WITH_ARGS","INDEX","ARRAY_INIT","OBJECT_INIT","PROPERTY_INIT","GETTER","SETTER","GROUP","LIST","LET_BLOCK","ARRAY_COMP","GENERATOR","COMP_TAIL","IDENTIFIER","NUMBER","STRING","REGEXP","break","case","catch","const","continue","debugger","default","delete","do","else","false","finally","for","function","if","in","instanceof","let","new","null","return","switch","this","throw","true","try","typeof","var","void","yield","while","with"];var statementStartTokens=["break","const","continue","debugger","do","for","if","return","switch","throw","try","var","yield","while","with"];var opTypeNames={"\n":"NEWLINE",";":"SEMICOLON",",":"COMMA","?":"HOOK",":":"COLON","||":"OR","&&":"AND","|":"BITWISE_OR","^":"BITWISE_XOR","&":"BITWISE_AND","===":"STRICT_EQ","==":"EQ","=":"ASSIGN","!==":"STRICT_NE","!=":"NE","<<":"LSH","<=":"LE","<":"LT",">>>":"URSH",">>":"RSH",">=":"GE",">":"GT","++":"INCREMENT","--":"DECREMENT","+":"PLUS","-":"MINUS","*":"MUL","/":"DIV","%":"MOD","!":"NOT","~":"BITWISE_NOT",".":"DOT","[":"LEFT_BRACKET","]":"RIGHT_BRACKET","{":"LEFT_CURLY","}":"RIGHT_CURLY","(":"LEFT_PAREN",")":"RIGHT_PAREN"};var keywords={__proto__:null};var tokenIds={};var consts="var ";for(var i=0,j=tokens.length;i<j;i++){if(i>0)consts+=", ";var t=tokens[i];var name;if(/^[a-z]/.test(t)){name=t.toUpperCase();keywords[t]=i}else{name=/^\W/.test(t)?opTypeNames[t]:t}consts+=name+" = "+i;tokenIds[name]=i;tokens[t]=i}consts+=";";var isStatementStartCode={__proto__:null};for(i=0,j=statementStartTokens.length;i<j;i++)isStatementStartCode[keywords[statementStartTokens[i]]]=true;var assignOps=["|","^","&","<<",">>",">>>","+","-","*","/","%"];for(i=0,j=assignOps.length;i<j;i++){t=assignOps[i];assignOps[t]=tokens[t]}function defineGetter(obj,prop,fn,dontDelete,dontEnum){Object.defineProperty(obj,prop,{get:fn,configurable:!dontDelete,enumerable:!dontEnum})}function defineProperty(obj,prop,val,dontDelete,readOnly,dontEnum){Object.defineProperty(obj,prop,{value:val,writable:!readOnly,configurable:!dontDelete,enumerable:!dontEnum})}function isNativeCode(fn){return typeof fn==="function"&&fn.toString().match(/\[native code\]/)}function getPropertyDescriptor(obj,name){while(obj){if({}.hasOwnProperty.call(obj,name))return Object.getOwnPropertyDescriptor(obj,name);obj=Object.getPrototypeOf(obj)}}function getOwnProperties(obj){var map={};for(var name in Object.getOwnPropertyNames(obj))map[name]=Object.getOwnPropertyDescriptor(obj,name);return map}function makePassthruHandler(obj){return{getOwnPropertyDescriptor:function(name){var desc=Object.getOwnPropertyDescriptor(obj,name);desc.configurable=true;return desc},getPropertyDescriptor:function(name){var desc=getPropertyDescriptor(obj,name);desc.configurable=true;return desc},getOwnPropertyNames:function(){return Object.getOwnPropertyNames(obj)},defineProperty:function(name,desc){Object.defineProperty(obj,name,desc)},delete:function(name){return delete obj[name]},fix:function(){if(Object.isFrozen(obj)){return getOwnProperties(obj)}return undefined},has:function(name){return name in obj},hasOwn:function(name){return{}.hasOwnProperty.call(obj,name)},get:function(receiver,name){return obj[name]},set:function(receiver,name,val){obj[name]=val;return true},enumerate:function(){var result=[];for(name in obj){result.push(name)}return result},keys:function(){return Object.keys(obj)}}}function noPropFound(){return undefined}var hasOwnProperty={}.hasOwnProperty;function StringMap(){this.table=Object.create(null,{});this.size=0}StringMap.prototype={has:function(x){return hasOwnProperty.call(this.table,x)},set:function(x,v){if(!hasOwnProperty.call(this.table,x))this.size++;this.table[x]=v},get:function(x){return this.table[x]},getDef:function(x,thunk){if(!hasOwnProperty.call(this.table,x)){this.size++;this.table[x]=thunk()}return this.table[x]},forEach:function(f){var table=this.table;for(var key in table)f.call(this,key,table[key])},toString:function(){return"[object StringMap]"}};function Stack(elts){this.elts=elts||null}Stack.prototype={push:function(x){return new Stack({top:x,rest:this.elts})},top:function(){if(!this.elts)throw new Error("empty stack");return this.elts.top},isEmpty:function(){return this.top===null},find:function(test){for(var elts=this.elts;elts;elts=elts.rest){if(test(elts.top))return elts.top}return null},has:function(x){return Boolean(this.find(function(elt){return elt===x}))},forEach:function(f){for(var elts=this.elts;elts;elts=elts.rest){f(elts.top)}}};return{tokens:tokens,opTypeNames:opTypeNames,keywords:keywords,isStatementStartCode:isStatementStartCode,tokenIds:tokenIds,consts:consts,assignOps:assignOps,defineGetter:defineGetter,defineProperty:defineProperty,isNativeCode:isNativeCode,makePassthruHandler:makePassthruHandler,noPropFound:noPropFound,StringMap:StringMap,Stack:Stack}}();Narcissus.lexer=function(){var definitions=Narcissus.definitions;eval(definitions.consts);var opTokens={};for(var op in definitions.opTypeNames){if(op==="\n"||op===".")continue;var node=opTokens;for(var i=0;i<op.length;i++){var ch=op[i];if(!(ch in node))node[ch]={};node=node[ch];node.op=op}}function Tokenizer(s,f,l){this.cursor=0;this.source=String(s);this.tokens=[];this.tokenIndex=0;this.lookahead=0;this.scanNewlines=false;this.unexpectedEOF=false;this.filename=f||"";this.lineno=l||1}Tokenizer.prototype={get done(){return this.peek(true)===END},get token(){return this.tokens[this.tokenIndex]},match:function(tt,scanOperand){return this.get(scanOperand)===tt||this.unget()},mustMatch:function(tt){if(!this.match(tt)){throw this.newSyntaxError("Missing "+definitions.tokens[tt].toLowerCase())}return this.token},forceIdentifier:function(){if(!this.match(IDENTIFIER)){if(this.get()>=definitions.keywords[0]||this.unget){this.token.type=IDENTIFIER}else{throw this.newSyntaxError("Missing identifier")}}return this.token},peek:function(scanOperand){var tt,next;if(this.lookahead){next=this.tokens[this.tokenIndex+this.lookahead&3];tt=this.scanNewlines&&next.lineno!==this.lineno?NEWLINE:next.type}else{tt=this.get(scanOperand);this.unget()}return tt},peekOnSameLine:function(scanOperand){this.scanNewlines=true;var tt=this.peek(scanOperand);this.scanNewlines=false;return tt},skip:function(){var input=this.source;for(;;){var ch=input[this.cursor++];var next=input[this.cursor];if(ch==="\n"&&!this.scanNewlines){this.lineno++}else if(ch==="/"&&next==="*"){this.cursor++;for(;;){ch=input[this.cursor++];if(ch===undefined)throw this.newSyntaxError("Unterminated comment");if(ch==="*"){next=input[this.cursor];if(next==="/"){this.cursor++;break}}else if(ch==="\n"){this.lineno++}}}else if(ch==="/"&&next==="/"){this.cursor++;for(;;){ch=input[this.cursor++];if(ch===undefined)return;if(ch==="\n"){this.lineno++;break}}}else if(ch!==" "&&ch!=="\t"){this.cursor--;return}}},lexExponent:function(){var input=this.source;var next=input[this.cursor];if(next==="e"||next==="E"){this.cursor++;ch=input[this.cursor++];if(ch==="+"||ch==="-")ch=input[this.cursor++];if(ch<"0"||ch>"9")throw this.newSyntaxError("Missing exponent");do{ch=input[this.cursor++]}while(ch>="0"&&ch<="9");this.cursor--;return true}return false},lexZeroNumber:function(ch){var token=this.token,input=this.source;token.type=NUMBER;ch=input[this.cursor++];if(ch==="."){do{ch=input[this.cursor++]}while(ch>="0"&&ch<="9");this.cursor--;this.lexExponent();token.value=parseFloat(input.substring(token.start,this.cursor))}else if(ch==="x"||ch==="X"){do{ch=input[this.cursor++]}while(ch>="0"&&ch<="9"||ch>="a"&&ch<="f"||ch>="A"&&ch<="F");this.cursor--;token.value=parseInt(input.substring(token.start,this.cursor))}else if(ch>="0"&&ch<="7"){do{ch=input[this.cursor++]}while(ch>="0"&&ch<="7");this.cursor--;token.value=parseInt(input.substring(token.start,this.cursor),8);token.value.isOctal=true}else{this.cursor--;this.lexExponent();token.value=0}},lexNumber:function(ch){var token=this.token,input=this.source;token.type=NUMBER;var floating=false;do{ch=input[this.cursor++];if(ch==="."&&!floating){floating=true;ch=input[this.cursor++]}}while(ch>="0"&&ch<="9");this.cursor--;var exponent=this.lexExponent();floating=floating||exponent;var str=input.substring(token.start,this.cursor);token.value=floating?parseFloat(str):parseInt(str)},lexDot:function(ch){var token=this.token,input=this.source;var next=input[this.cursor];if(next>="0"&&next<="9"){do{ch=input[this.cursor++]}while(ch>="0"&&ch<="9");this.cursor--;this.lexExponent();token.type=NUMBER;token.value=parseFloat(input.substring(token.start,this.cursor))}else{token.type=DOT;token.assignOp=null;token.value="."}},lexString:function(ch){var token=this.token,input=this.source;token.type=STRING;var hasEscapes=false;var delim=ch;while((ch=input[this.cursor++])!==delim){if(this.cursor==input.length)throw this.newSyntaxError("Unterminated string literal");if(ch==="\\"){hasEscapes=true;if(input[this.cursor]==="\n")this.lineno++;if(++this.cursor==input.length)throw this.newSyntaxError("Unterminated string literal")}}token.value=hasEscapes?eval(input.substring(token.start,this.cursor)):input.substring(token.start+1,this.cursor-1)},lexRegExp:function(ch){var token=this.token,input=this.source;token.type=REGEXP;do{ch=input[this.cursor++];if(ch==="\\"){this.cursor++}else if(ch==="["){do{if(ch===undefined)throw this.newSyntaxError("Unterminated character class");if(ch==="\\")this.cursor++;ch=input[this.cursor++]}while(ch!=="]")}else if(ch===undefined){throw this.newSyntaxError("Unterminated regex")}}while(ch!=="/");do{ch=input[this.cursor++]}while(ch>="a"&&ch<="z");this.cursor--;token.value=eval(input.substring(token.start,this.cursor))},lexOp:function(ch){var token=this.token,input=this.source;var node=opTokens[ch];var next=input[this.cursor];if(next in node){node=node[next];this.cursor++;next=input[this.cursor];if(next in node){node=node[next];this.cursor++;next=input[this.cursor]}}var op=node.op;if(definitions.assignOps[op]&&input[this.cursor]==="="){this.cursor++;token.type=ASSIGN;token.assignOp=definitions.tokenIds[definitions.opTypeNames[op]];op+="="}else{token.type=definitions.tokenIds[definitions.opTypeNames[op]];token.assignOp=null}token.value=op},lexIdent:function(ch){var token=this.token,input=this.source;do{ch=input[this.cursor++]}while(ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch>="0"&&ch<="9"||ch==="$"||ch==="_");this.cursor--;var id=input.substring(token.start,this.cursor);token.type=definitions.keywords[id]||IDENTIFIER;token.value=id},get:function(scanOperand){var token;while(this.lookahead){--this.lookahead;this.tokenIndex=this.tokenIndex+1&3;token=this.tokens[this.tokenIndex];if(token.type!==NEWLINE||this.scanNewlines)return token.type}this.skip();this.tokenIndex=this.tokenIndex+1&3;token=this.tokens[this.tokenIndex];if(!token)this.tokens[this.tokenIndex]=token={};var input=this.source;if(this.cursor===input.length)return token.type=END;token.start=this.cursor;token.lineno=this.lineno;var ch=input[this.cursor++];if(ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch==="$"||ch==="_"){this.lexIdent(ch)}else if(scanOperand&&ch==="/"){this.lexRegExp(ch)}else if(ch in opTokens){this.lexOp(ch)}else if(ch==="."){this.lexDot(ch)}else if(ch>="1"&&ch<="9"){this.lexNumber(ch)}else if(ch==="0"){this.lexZeroNumber(ch)}else if(ch==='"'||ch==="'"){this.lexString(ch)}else if(this.scanNewlines&&ch==="\n"){token.type=NEWLINE;token.value="\n";this.lineno++}else{throw this.newSyntaxError("Illegal token")}token.end=this.cursor;return token.type},unget:function(){if(++this.lookahead===4)throw"PANIC: too much lookahead!";this.tokenIndex=this.tokenIndex-1&3},newSyntaxError:function(m){var e=new SyntaxError(this.filename+":"+this.lineno+":"+m);e.source=this.source;e.cursor=this.lookahead?this.tokens[this.tokenIndex+this.lookahead&3].start:this.cursor;return e}};return{Tokenizer:Tokenizer}}();Narcissus.parser=function(){var lexer=Narcissus.lexer;var definitions=Narcissus.definitions;const StringMap=definitions.StringMap;const Stack=definitions.Stack;eval(definitions.consts);function pushDestructuringVarDecls(n,s){for(var i in n){var sub=n[i];if(sub.type===IDENTIFIER){s.varDecls.push(sub)}else{pushDestructuringVarDecls(sub,s)}}}const NESTING_TOP=0,NESTING_SHALLOW=1,NESTING_DEEP=2;function StaticContext(parentScript,parentBlock,inFunction,inForLoopInit,nesting){this.parentScript=parentScript;this.parentBlock=parentBlock;this.inFunction=inFunction;this.inForLoopInit=inForLoopInit;this.nesting=nesting;this.allLabels=new Stack;this.currentLabels=new Stack;this.labeledTargets=new Stack;this.defaultTarget=null;Narcissus.options.ecma3OnlyMode&&(this.ecma3OnlyMode=true);Narcissus.options.parenFreeMode&&(this.parenFreeMode=true)}StaticContext.prototype={ecma3OnlyMode:false,parenFreeMode:false,update:function(ext){var desc={};for(var key in ext){desc[key]={value:ext[key],writable:true,enumerable:true,configurable:true}}return Object.create(this,desc)},pushLabel:function(label){return this.update({currentLabels:this.currentLabels.push(label),allLabels:this.allLabels.push(label)})},pushTarget:function(target){var isDefaultTarget=target.isLoop||target.type===SWITCH;if(isDefaultTarget)target.target=this.defaultTarget;if(this.currentLabels.isEmpty()){return isDefaultTarget?this.update({defaultTarget:target}):this}target.labels=new StringMap;this.currentLabels.forEach(function(label){target.labels.set(label,true)});return this.update({currentLabels:new Stack,labeledTargets:this.labeledTargets.push(target),defaultTarget:isDefaultTarget?target:this.defaultTarget})},nest:function(atLeast){var nesting=Math.max(this.nesting,atLeast);return nesting!==this.nesting?this.update({nesting:nesting}):this}};function Script(t,inFunction){var n=new Node(t,scriptInit());var x=new StaticContext(n,n,inFunction,false,NESTING_TOP);Statements(t,x,n);return n}definitions.defineProperty(Array.prototype,"top",function(){return this.length&&this[this.length-1]},false,false,true);function Node(t,init){var token=t.token;if(token){this.type=token.type;this.value=token.value;this.lineno=token.lineno;this.start=token.start;this.end=token.end}else{this.lineno=t.lineno}this.tokenizer=t;this.children=[];for(var prop in init)this[prop]=init[prop]}var Np=Node.prototype={};Np.constructor=Node;Np.toSource=Object.prototype.toSource;Np.push=function(kid){if(kid!==null){if(kid.start<this.start)this.start=kid.start;if(this.end<kid.end)this.end=kid.end}return this.children.push(kid)};Node.indentLevel=0;function tokenString(tt){var t=definitions.tokens[tt];return/^\W/.test(t)?definitions.opTypeNames[t]:t.toUpperCase()}Np.toString=function(){var a=[];for(var i in this){if(this.hasOwnProperty(i)&&i!=="type"&&i!=="target")a.push({id:i,value:this[i]})}a.sort(function(a,b){return a.id<b.id?-1:1});const INDENTATION="    ";var n=++Node.indentLevel;var s="{\n"+INDENTATION.repeat(n)+"type: "+tokenString(this.type);for(i=0;i<a.length;i++)s+=", "+a[i].id+": "+a[i].value;n=--Node.indentLevel;s+="\n"+INDENTATION.repeat(n)+"}";return s};Np.getSource=function(){return this.tokenizer.source.slice(this.start,this.end)};const LOOP_INIT={isLoop:true};function blockInit(){return{type:BLOCK,varDecls:[]}}function scriptInit(){return{type:SCRIPT,funDecls:[],varDecls:[],modDecls:[],impDecls:[],expDecls:[],loadDeps:[],hasEmptyReturn:false,hasReturnWithValue:false,isGenerator:false}}definitions.defineGetter(Np,"filename",function(){return this.tokenizer.filename});definitions.defineGetter(Np,"length",function(){throw new Error("Node.prototype.length is gone; "+"use n.children.length instead")});definitions.defineProperty(String.prototype,"repeat",function(n){var s="",t=this+s;while(--n>=0)s+=t;return s},false,false,true);function MaybeLeftParen(t,x){if(x.parenFreeMode)return t.match(LEFT_PAREN)?LEFT_PAREN:END;return t.mustMatch(LEFT_PAREN).type}function MaybeRightParen(t,p){if(p===LEFT_PAREN)t.mustMatch(RIGHT_PAREN)}function Statements(t,x,n){try{while(!t.done&&t.peek(true)!==RIGHT_CURLY)n.push(Statement(t,x))}catch(e){if(t.done)t.unexpectedEOF=true;throw e}}function Block(t,x){t.mustMatch(LEFT_CURLY);var n=new Node(t,blockInit());Statements(t,x.update({parentBlock:n}).pushTarget(n),n);t.mustMatch(RIGHT_CURLY);n.end=t.token.end;return n}const DECLARED_FORM=0,EXPRESSED_FORM=1,STATEMENT_FORM=2;function Statement(t,x){var i,label,n,n2,p,c,ss,tt=t.get(true),tt2,x2,x3;switch(tt){case FUNCTION:return FunctionDefinition(t,x,true,x.nesting!==NESTING_TOP?STATEMENT_FORM:DECLARED_FORM);case LEFT_CURLY:n=new Node(t,blockInit());Statements(t,x.update({parentBlock:n}).pushTarget(n).nest(NESTING_SHALLOW),n);t.mustMatch(RIGHT_CURLY);n.end=t.token.end;return n;case IF:n=new Node(t);n.condition=HeadExpression(t,x);x2=x.pushTarget(n).nest(NESTING_DEEP);n.thenPart=Statement(t,x2);n.elsePart=t.match(ELSE)?Statement(t,x2):null;return n;case SWITCH:n=new Node(t,{cases:[],defaultIndex:-1});n.discriminant=HeadExpression(t,x);x2=x.pushTarget(n).nest(NESTING_DEEP);t.mustMatch(LEFT_CURLY);while((tt=t.get())!==RIGHT_CURLY){switch(tt){case DEFAULT:if(n.defaultIndex>=0)throw t.newSyntaxError("More than one switch default");case CASE:n2=new Node(t);if(tt===DEFAULT)n.defaultIndex=n.cases.length;else n2.caseLabel=Expression(t,x2,COLON);break;default:throw t.newSyntaxError("Invalid switch case")}t.mustMatch(COLON);n2.statements=new Node(t,blockInit());while((tt=t.peek(true))!==CASE&&tt!==DEFAULT&&tt!==RIGHT_CURLY)n2.statements.push(Statement(t,x2));n.cases.push(n2)}n.end=t.token.end;return n;case FOR:n=new Node(t,LOOP_INIT);if(t.match(IDENTIFIER)){if(t.token.value==="each")n.isEach=true;else t.unget()}if(!x.parenFreeMode)t.mustMatch(LEFT_PAREN);x2=x.pushTarget(n).nest(NESTING_DEEP);x3=x.update({inForLoopInit:true});if((tt=t.peek())!==SEMICOLON){if(tt===VAR||tt===CONST){t.get();n2=Variables(t,x3)}else if(tt===LET){t.get();if(t.peek()===LEFT_PAREN){n2=LetBlock(t,x3,false)}else{x3.parentBlock=n;n.varDecls=[];n2=Variables(t,x3)}}else{n2=Expression(t,x3)}}if(n2&&t.match(IN)){n.type=FOR_IN;n.object=Expression(t,x3);if(n2.type===VAR||n2.type===LET){c=n2.children;if(c.length!==1&&n2.destructurings.length!==1){throw new SyntaxError("Invalid for..in left-hand side",t.filename,n2.lineno)}if(n2.destructurings.length>0){n.iterator=n2.destructurings[0]}else{n.iterator=c[0]}n.varDecl=n2}else{if(n2.type===ARRAY_INIT||n2.type===OBJECT_INIT){n2.destructuredNames=checkDestructuring(t,x3,n2)}n.iterator=n2}}else{n.setup=n2;t.mustMatch(SEMICOLON);if(n.isEach)throw t.newSyntaxError("Invalid for each..in loop");n.condition=t.peek()===SEMICOLON?null:Expression(t,x3);t.mustMatch(SEMICOLON);tt2=t.peek();n.update=(x.parenFreeMode?tt2===LEFT_CURLY||definitions.isStatementStartCode[tt2]:tt2===RIGHT_PAREN)?null:Expression(t,x3)}if(!x.parenFreeMode)t.mustMatch(RIGHT_PAREN);n.body=Statement(t,x2);n.end=t.token.end;return n;case WHILE:n=new Node(t,{isLoop:true});n.condition=HeadExpression(t,x);n.body=Statement(t,x.pushTarget(n).nest(NESTING_DEEP));n.end=t.token.end;return n;case DO:n=new Node(t,{isLoop:true});n.body=Statement(t,x.pushTarget(n).nest(NESTING_DEEP));t.mustMatch(WHILE);n.condition=HeadExpression(t,x);if(!x.ecmaStrictMode){t.match(SEMICOLON);n.end=t.token.end;return n}break;case BREAK:case CONTINUE:n=new Node(t);x2=x.pushTarget(n);if(t.peekOnSameLine()===IDENTIFIER){t.get();n.label=t.token.value}n.target=n.label?x2.labeledTargets.find(function(target){return target.labels.has(n.label)}):x2.defaultTarget;if(!n.target)throw t.newSyntaxError("Invalid "+(tt===BREAK?"break":"continue"));if(tt===CONTINUE){for(var ttt=n.target;ttt&&!ttt.isLoop;ttt=ttt.target);if(!ttt)throw t.newSyntaxError("Invalid continue")}break;case TRY:n=new Node(t,{catchClauses:[]});n.tryBlock=Block(t,x);while(t.match(CATCH)){n2=new Node(t);p=MaybeLeftParen(t,x);switch(t.get()){case LEFT_BRACKET:case LEFT_CURLY:t.unget();n2.varName=DestructuringExpression(t,x,true);break;case IDENTIFIER:n2.varName=t.token.value;break;default:throw t.newSyntaxError("missing identifier in catch");break}if(t.match(IF)){if(x.ecma3OnlyMode)throw t.newSyntaxError("Illegal catch guard");if(n.catchClauses.length&&!n.catchClauses.top().guard)throw t.newSyntaxError("Guarded catch after unguarded");n2.guard=Expression(t,x)}MaybeRightParen(t,p);n2.block=Block(t,x);n.catchClauses.push(n2)}if(t.match(FINALLY))n.finallyBlock=Block(t,x);if(!n.catchClauses.length&&!n.finallyBlock)throw t.newSyntaxError("Invalid try statement");n.end=t.token.end;return n;case CATCH:case FINALLY:throw t.newSyntaxError(definitions.tokens[tt]+" without preceding try");case THROW:n=new Node(t);n.exception=Expression(t,x);break;case RETURN:n=ReturnOrYield(t,x);break;case WITH:n=new Node(t);n.object=HeadExpression(t,x);n.body=Statement(t,x.pushTarget(n).nest(NESTING_DEEP));n.end=t.token.end;return n;case VAR:case CONST:n=Variables(t,x);n.eligibleForASI=true;break;case LET:if(t.peek()===LEFT_PAREN)n=LetBlock(t,x,true);else n=Variables(t,x);n.eligibleForASI=true;break;case DEBUGGER:n=new Node(t);break;case NEWLINE:case SEMICOLON:n=new Node(t,{type:SEMICOLON});n.expression=null;return n;default:if(tt===IDENTIFIER){tt=t.peek();if(tt===COLON){label=t.token.value;if(x.allLabels.has(label))throw t.newSyntaxError("Duplicate label");t.get();n=new Node(t,{type:LABEL,label:label});n.statement=Statement(t,x.pushLabel(label).nest(NESTING_SHALLOW));n.target=n.statement.type===LABEL?n.statement.target:n.statement;n.end=t.token.end;return n}}n=new Node(t,{type:SEMICOLON});t.unget();n.expression=Expression(t,x);n.end=n.expression.end;break}MagicalSemicolon(t);n.end=t.token.end;return n}function MagicalSemicolon(t){var tt;if(t.lineno===t.token.lineno){tt=t.peekOnSameLine();if(tt!==END&&tt!==NEWLINE&&tt!==SEMICOLON&&tt!==RIGHT_CURLY)throw t.newSyntaxError("missing ; before statement")}t.match(SEMICOLON)}function ReturnOrYield(t,x){var n,b,tt=t.token.type,tt2;var parentScript=x.parentScript;if(tt===RETURN){if(false&&!x.inFunction)throw t.newSyntaxError("Return not in function")}else{if(!x.inFunction)throw t.newSyntaxError("Yield not in function");parentScript.isGenerator=true}n=new Node(t,{value:undefined});tt2=t.peek(true);if(tt2!==END&&tt2!==NEWLINE&&tt2!==SEMICOLON&&tt2!==RIGHT_CURLY&&(tt!==YIELD||tt2!==tt&&tt2!==RIGHT_BRACKET&&tt2!==RIGHT_PAREN&&tt2!==COLON&&tt2!==COMMA)){if(tt===RETURN){n.value=Expression(t,x);parentScript.hasReturnWithValue=true}else{n.value=AssignExpression(t,x)}}else if(tt===RETURN){parentScript.hasEmptyReturn=true}if(parentScript.hasReturnWithValue&&parentScript.isGenerator)throw t.newSyntaxError("Generator returns a value");return n}function FunctionDefinition(t,x,requireName,functionForm){var tt;var f=new Node(t,{params:[]});if(f.type!==FUNCTION)f.type=f.value==="get"?GETTER:SETTER;if(t.match(IDENTIFIER))f.name=t.token.value;else if(requireName)throw t.newSyntaxError("missing function identifier");var x2=new StaticContext(null,null,true,false,NESTING_TOP);t.mustMatch(LEFT_PAREN);if(!t.match(RIGHT_PAREN)){do{switch(t.get()){case LEFT_BRACKET:case LEFT_CURLY:t.unget();f.params.push(DestructuringExpression(t,x2));break;case IDENTIFIER:f.params.push(t.token.value);break;default:throw t.newSyntaxError("missing formal parameter");break}}while(t.match(COMMA));t.mustMatch(RIGHT_PAREN)}tt=t.get();if(tt!==LEFT_CURLY)t.unget();if(tt!==LEFT_CURLY){f.body=AssignExpression(t,x2);if(f.body.isGenerator)throw t.newSyntaxError("Generator returns a value")}else{f.body=Script(t,true)}if(tt===LEFT_CURLY)t.mustMatch(RIGHT_CURLY);f.end=t.token.end;f.functionForm=functionForm;if(functionForm===DECLARED_FORM)x.parentScript.funDecls.push(f);return f}function Variables(t,x,letBlock){var n,n2,ss,i,s,tt;tt=t.token.type;switch(tt){case VAR:case CONST:s=x.parentScript;break;case LET:s=x.parentBlock;break;case LEFT_PAREN:tt=LET;s=letBlock;break}n=new Node(t,{type:tt,destructurings:[]});do{tt=t.get();if(tt===LEFT_BRACKET||tt===LEFT_CURLY){t.unget();var dexp=DestructuringExpression(t,x,true);n2=new Node(t,{type:IDENTIFIER,name:dexp,readOnly:n.type===CONST});n.push(n2);pushDestructuringVarDecls(n2.name.destructuredNames,s);n.destructurings.push({exp:dexp,decl:n2});if(x.inForLoopInit&&t.peek()===IN){continue}t.mustMatch(ASSIGN);if(t.token.assignOp)throw t.newSyntaxError("Invalid variable initialization");n2.initializer=AssignExpression(t,x);continue}if(tt!==IDENTIFIER)throw t.newSyntaxError("missing variable name");n2=new Node(t,{type:IDENTIFIER,name:t.token.value,readOnly:n.type===CONST});n.push(n2);s.varDecls.push(n2);if(t.match(ASSIGN)){if(t.token.assignOp)throw t.newSyntaxError("Invalid variable initialization");n2.initializer=AssignExpression(t,x)}}while(t.match(COMMA));n.end=t.token.end;return n}function LetBlock(t,x,isStatement){var n,n2;n=new Node(t,{type:LET_BLOCK,varDecls:[]});t.mustMatch(LEFT_PAREN);n.variables=Variables(t,x,n);t.mustMatch(RIGHT_PAREN);if(isStatement&&t.peek()!==LEFT_CURLY){n2=new Node(t,{type:SEMICOLON,expression:n});isStatement=false}if(isStatement)n.block=Block(t,x);else n.expression=AssignExpression(t,x);return n}function checkDestructuring(t,x,n,simpleNamesOnly){if(n.type===ARRAY_COMP)throw t.newSyntaxError("Invalid array comprehension left-hand side");if(n.type!==ARRAY_INIT&&n.type!==OBJECT_INIT)return;var lhss={};var nn,n2,idx,sub,cc,c=n.children;for(var i=0,j=c.length;i<j;i++){if(!(nn=c[i]))continue;if(nn.type===PROPERTY_INIT){cc=nn.children;sub=cc[1];idx=cc[0].value}else if(n.type===OBJECT_INIT){sub=nn;idx=nn.value}else{sub=nn;idx=i}if(sub.type===ARRAY_INIT||sub.type===OBJECT_INIT){lhss[idx]=checkDestructuring(t,x,sub,simpleNamesOnly)}else{if(simpleNamesOnly&&sub.type!==IDENTIFIER){throw t.newSyntaxError("missing name in pattern")}lhss[idx]=sub}}return lhss}function DestructuringExpression(t,x,simpleNamesOnly){var n=PrimaryExpression(t,x);n.destructuredNames=checkDestructuring(t,x,n,simpleNamesOnly);return n}function GeneratorExpression(t,x,e){return new Node(t,{type:GENERATOR,expression:e,tail:ComprehensionTail(t,x)})}function ComprehensionTail(t,x){var body,n,n2,n3,p;body=new Node(t,{type:COMP_TAIL});do{n=new Node(t,{type:FOR_IN,isLoop:true});if(t.match(IDENTIFIER)){if(t.token.value==="each")n.isEach=true;else t.unget()}p=MaybeLeftParen(t,x);switch(t.get()){case LEFT_BRACKET:case LEFT_CURLY:t.unget();n.iterator=DestructuringExpression(t,x);break;case IDENTIFIER:n.iterator=n3=new Node(t,{type:IDENTIFIER});n3.name=n3.value;n.varDecl=n2=new Node(t,{type:VAR});n2.push(n3);x.parentScript.varDecls.push(n3);break;default:throw t.newSyntaxError("missing identifier")}t.mustMatch(IN);n.object=Expression(t,x);MaybeRightParen(t,p);body.push(n)}while(t.match(FOR));if(t.match(IF))body.guard=HeadExpression(t,x);return body}function HeadExpression(t,x){var p=MaybeLeftParen(t,x);var n=ParenExpression(t,x);MaybeRightParen(t,p);if(p===END&&!n.parenthesized){var tt=t.peek();if(tt!==LEFT_CURLY&&!definitions.isStatementStartCode[tt])throw t.newSyntaxError("Unparenthesized head followed by unbraced body")}return n}function ParenExpression(t,x){var n=Expression(t,x.update({inForLoopInit:x.inForLoopInit&&t.token.type===LEFT_PAREN}));if(t.match(FOR)){if(n.type===YIELD&&!n.parenthesized)throw t.newSyntaxError("Yield expression must be parenthesized");if(n.type===COMMA&&!n.parenthesized)throw t.newSyntaxError("Generator expression must be parenthesized");n=GeneratorExpression(t,x,n)}return n}function Expression(t,x){var n,n2;n=AssignExpression(t,x);if(t.match(COMMA)){n2=new Node(t,{type:COMMA});n2.push(n);n=n2;do{n2=n.children[n.children.length-1];if(n2.type===YIELD&&!n2.parenthesized)throw t.newSyntaxError("Yield expression must be parenthesized");n.push(AssignExpression(t,x))}while(t.match(COMMA))}return n}function AssignExpression(t,x){var n,lhs;if(t.match(YIELD,true))return ReturnOrYield(t,x);n=new Node(t,{type:ASSIGN});lhs=ConditionalExpression(t,x);if(!t.match(ASSIGN)){return lhs}switch(lhs.type){case OBJECT_INIT:case ARRAY_INIT:lhs.destructuredNames=checkDestructuring(t,x,lhs);case IDENTIFIER:case DOT:case INDEX:case CALL:break;default:throw t.newSyntaxError("Bad left-hand side of assignment");break}n.assignOp=t.token.assignOp;n.push(lhs);n.push(AssignExpression(t,x));return n}function ConditionalExpression(t,x){var n,n2;n=OrExpression(t,x);if(t.match(HOOK)){n2=n;n=new Node(t,{type:HOOK});n.push(n2);n.push(AssignExpression(t,x.update({inForLoopInit:false})));if(!t.match(COLON))throw t.newSyntaxError("missing : after ?");n.push(AssignExpression(t,x))}return n}function OrExpression(t,x){var n,n2;n=AndExpression(t,x);while(t.match(OR)){n2=new Node(t);n2.push(n);n2.push(AndExpression(t,x));n=n2}return n}function AndExpression(t,x){var n,n2;n=BitwiseOrExpression(t,x);while(t.match(AND)){n2=new Node(t);n2.push(n);n2.push(BitwiseOrExpression(t,x));n=n2}return n}function BitwiseOrExpression(t,x){var n,n2;n=BitwiseXorExpression(t,x);while(t.match(BITWISE_OR)){n2=new Node(t);n2.push(n);n2.push(BitwiseXorExpression(t,x));n=n2}return n}function BitwiseXorExpression(t,x){var n,n2;n=BitwiseAndExpression(t,x);while(t.match(BITWISE_XOR)){
  n2=new Node(t);n2.push(n);n2.push(BitwiseAndExpression(t,x));n=n2}return n}function BitwiseAndExpression(t,x){var n,n2;n=EqualityExpression(t,x);while(t.match(BITWISE_AND)){n2=new Node(t);n2.push(n);n2.push(EqualityExpression(t,x));n=n2}return n}function EqualityExpression(t,x){var n,n2;n=RelationalExpression(t,x);while(t.match(EQ)||t.match(NE)||t.match(STRICT_EQ)||t.match(STRICT_NE)){n2=new Node(t);n2.push(n);n2.push(RelationalExpression(t,x));n=n2}return n}function RelationalExpression(t,x){var n,n2;var x2=x.update({inForLoopInit:false});n=ShiftExpression(t,x2);while(t.match(LT)||t.match(LE)||t.match(GE)||t.match(GT)||!x.inForLoopInit&&t.match(IN)||t.match(INSTANCEOF)){n2=new Node(t);n2.push(n);n2.push(ShiftExpression(t,x2));n=n2}return n}function ShiftExpression(t,x){var n,n2;n=AddExpression(t,x);while(t.match(LSH)||t.match(RSH)||t.match(URSH)){n2=new Node(t);n2.push(n);n2.push(AddExpression(t,x));n=n2}return n}function AddExpression(t,x){var n,n2;n=MultiplyExpression(t,x);while(t.match(PLUS)||t.match(MINUS)){n2=new Node(t);n2.push(n);n2.push(MultiplyExpression(t,x));n=n2}return n}function MultiplyExpression(t,x){var n,n2;n=UnaryExpression(t,x);while(t.match(MUL)||t.match(DIV)||t.match(MOD)){n2=new Node(t);n2.push(n);n2.push(UnaryExpression(t,x));n=n2}return n}function UnaryExpression(t,x){var n,n2,tt;switch(tt=t.get(true)){case DELETE:case VOID:case TYPEOF:case NOT:case BITWISE_NOT:case PLUS:case MINUS:if(tt===PLUS)n=new Node(t,{type:UNARY_PLUS});else if(tt===MINUS)n=new Node(t,{type:UNARY_MINUS});else n=new Node(t);n.push(UnaryExpression(t,x));break;case INCREMENT:case DECREMENT:n=new Node(t);n.push(MemberExpression(t,x,true));break;default:t.unget();n=MemberExpression(t,x,true);if(t.tokens[t.tokenIndex+t.lookahead-1&3].lineno===t.lineno){if(t.match(INCREMENT)||t.match(DECREMENT)){n2=new Node(t,{postfix:true});n2.push(n);n=n2}}break}return n}function MemberExpression(t,x,allowCallSyntax){var n,n2,name,tt;if(t.match(NEW)){n=new Node(t);n.push(MemberExpression(t,x,false));if(t.match(LEFT_PAREN)){n.type=NEW_WITH_ARGS;n.push(ArgumentList(t,x))}}else{n=PrimaryExpression(t,x)}while((tt=t.get())!==END){switch(tt){case DOT:n2=new Node(t);n2.push(n);t.forceIdentifier();n2.push(new Node(t));break;case LEFT_BRACKET:n2=new Node(t,{type:INDEX});n2.push(n);n2.push(Expression(t,x));t.mustMatch(RIGHT_BRACKET);n2.end=t.token.end;break;case LEFT_PAREN:if(allowCallSyntax){n2=new Node(t,{type:CALL});n2.push(n);n2.push(ArgumentList(t,x));break}default:t.unget();return n}n=n2}return n}function ArgumentList(t,x){var n,n2;n=new Node(t,{type:LIST});if(t.match(RIGHT_PAREN,true)){n.end=t.token.end;return n}do{n2=AssignExpression(t,x);if(n2.type===YIELD&&!n2.parenthesized&&t.peek()===COMMA)throw t.newSyntaxError("Yield expression must be parenthesized");if(t.match(FOR)){n2=GeneratorExpression(t,x,n2);if(n.children.length>1||t.peek(true)===COMMA)throw t.newSyntaxError("Generator expression must be parenthesized")}n.push(n2)}while(t.match(COMMA));t.mustMatch(RIGHT_PAREN);n.end=t.token.end;return n}function PrimaryExpression(t,x){var n,n2,tt=t.get(true);switch(tt){case FUNCTION:n=FunctionDefinition(t,x,false,EXPRESSED_FORM);break;case LEFT_BRACKET:n=new Node(t,{type:ARRAY_INIT});while((tt=t.peek(true))!==RIGHT_BRACKET){if(tt===COMMA){t.get();n.push(null);continue}n.push(AssignExpression(t,x));if(tt!==COMMA&&!t.match(COMMA))break}if(n.children.length===1&&t.match(FOR)){n2=new Node(t,{type:ARRAY_COMP,expression:n.children[0],tail:ComprehensionTail(t,x)});n=n2}t.mustMatch(RIGHT_BRACKET);n.end=t.token.end;break;case LEFT_CURLY:var id,fd;n=new Node(t,{type:OBJECT_INIT});object_init:if(!t.match(RIGHT_CURLY)){do{tt=t.get();if((t.token.value==="get"||t.token.value==="set")&&t.peek()===IDENTIFIER){if(x.ecma3OnlyMode)throw t.newSyntaxError("Illegal property accessor");n.push(FunctionDefinition(t,x,true,EXPRESSED_FORM))}else{switch(tt){case IDENTIFIER:case NUMBER:case STRING:id=new Node(t,{type:IDENTIFIER});break;case RIGHT_CURLY:if(x.ecma3OnlyMode)throw t.newSyntaxError("Illegal trailing ,");break object_init;default:if(t.token.value in definitions.keywords){id=new Node(t,{type:IDENTIFIER});break}throw t.newSyntaxError("Invalid property name")}if(t.match(COLON)){n2=new Node(t,{type:PROPERTY_INIT});n2.push(id);n2.push(AssignExpression(t,x));n.push(n2)}else{if(t.peek()!==COMMA&&t.peek()!==RIGHT_CURLY)throw t.newSyntaxError("missing : after property");n.push(id)}}}while(t.match(COMMA));t.mustMatch(RIGHT_CURLY)}n.end=t.token.end;break;case LEFT_PAREN:var start=t.token.start;n=ParenExpression(t,x);t.mustMatch(RIGHT_PAREN);n.start=start;n.end=t.token.end;n.parenthesized=true;break;case LET:n=LetBlock(t,x,false);break;case NULL:case THIS:case TRUE:case FALSE:case IDENTIFIER:case NUMBER:case STRING:case REGEXP:n=new Node(t);break;default:throw t.newSyntaxError("missing operand");break}return n}function parse(s,f,l){var t=new lexer.Tokenizer(s,f,l);var n=Script(t,false);if(!t.done)throw t.newSyntaxError("Syntax error");return n}function parseStdin(s,ln){for(;;){try{var t=new lexer.Tokenizer(s,"stdin",ln.value);var n=Script(t,false);ln.value=t.lineno;return n}catch(e){if(!t.unexpectedEOF)throw e;var more=readline();if(!more)throw e;s+="\n"+more}}}return{parse:parse,parseStdin:parseStdin,Node:Node,DECLARED_FORM:DECLARED_FORM,EXPRESSED_FORM:EXPRESSED_FORM,STATEMENT_FORM:STATEMENT_FORM,Tokenizer:lexer.Tokenizer,FunctionDefinition:FunctionDefinition}}();Narcissus.decompiler=function(){const parser=Narcissus.parser;const definitions=Narcissus.definitions;const tokens=definitions.tokens;eval(definitions.consts);function indent(n,s){var ss="",d=true;for(var i=0,j=s.length;i<j;i++){if(d)for(var k=0;k<n;k++)ss+=" ";ss+=s[i];d=s[i]==="\n"}return ss}function isBlock(n){return n&&n.type===BLOCK}function isNonEmptyBlock(n){return isBlock(n)&&n.children.length>0}function nodeStr(n){return'"'+n.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r")+'"'}function pp(n,d,inLetHead){var topScript=false;if(!n)return"";if(!(n instanceof Object))return n;if(!d){topScript=true;d=1}var p="";if(n.parenthesized)p+="(";switch(n.type){case FUNCTION:case GETTER:case SETTER:if(n.type===FUNCTION)p+="function";else if(n.type===GETTER)p+="get";else p+="set";p+=(n.name?" "+n.name:"")+"(";for(var i=0,j=n.params.length;i<j;i++)p+=(i>0?", ":"")+pp(n.params[i],d);p+=") "+pp(n.body,d);break;case SCRIPT:case BLOCK:var nc=n.children;if(topScript){for(var i=0,j=nc.length;i<j;i++){if(i>0)p+="\n";p+=pp(nc[i],d);var eoc=p[p.length-1];if(eoc!=";")p+=";"}break}p+="{";if(n.id!==undefined)p+=" /* "+n.id+" */";p+="\n";for(var i=0,j=nc.length;i<j;i++){if(i>0)p+="\n";p+=indent(4,pp(nc[i],d));var eoc=p[p.length-1];if(eoc!=";")p+=";"}p+="\n}";break;case LET_BLOCK:p+="let ("+pp(n.variables,d,true)+") ";if(n.expression)p+=pp(n.expression,d);else p+=pp(n.block,d);break;case IF:p+="if ("+pp(n.condition,d)+") ";var tp=n.thenPart,ep=n.elsePart;var b=isBlock(tp)||isBlock(ep);if(!b)p+="{\n";p+=(b?pp(tp,d):indent(4,pp(tp,d)))+"\n";if(ep){if(!b)p+="} else {\n";else p+=" else ";p+=(b?pp(ep,d):indent(4,pp(ep,d)))+"\n"}if(!b)p+="}";break;case SWITCH:p+="switch ("+pp(n.discriminant,d)+") {\n";for(var i=0,j=n.cases.length;i<j;i++){var ca=n.cases[i];if(ca.type===CASE)p+="  case "+pp(ca.caseLabel,d)+":\n";else p+="  default:\n";ps=pp(ca.statements,d);p+=ps.slice(2,ps.length-2)+"\n"}p+="}";break;case FOR:p+="for ("+pp(n.setup,d)+"; "+pp(n.condition,d)+"; "+pp(n.update,d)+") ";var pb=pp(n.body,d);if(!isBlock(n.body))p+="{\n"+indent(4,pb)+";\n}";else if(n.body)p+=pb;break;case WHILE:p+="while ("+pp(n.condition,d)+") ";var pb=pp(n.body,d);if(!isBlock(n.body))p+="{\n"+indent(4,pb)+";\n}";else p+=pb;break;case FOR_IN:var u=n.varDecl;p+=n.isEach?"for each (":"for (";p+=(u?pp(u,d):pp(n.iterator,d))+" in "+pp(n.object,d)+") ";var pb=pp(n.body,d);if(!isBlock(n.body))p+="{\n"+indent(4,pb)+";\n}";else if(n.body)p+=pb;break;case DO:p+="do "+pp(n.body,d);p+=" while ("+pp(n.condition,d)+");";break;case BREAK:p+="break"+(n.label?" "+n.label:"")+";";break;case CONTINUE:p+="continue"+(n.label?" "+n.label:"")+";";break;case TRY:p+="try ";p+=pp(n.tryBlock,d);for(var i=0,j=n.catchClauses.length;i<j;i++){var t=n.catchClauses[i];p+=" catch ("+pp(t.varName,d)+(t.guard?" if "+pp(t.guard,d):"")+") ";p+=pp(t.block,d)}if(n.finallyBlock){p+=" finally ";p+=pp(n.finallyBlock,d)}break;case THROW:p+="throw "+pp(n.exception,d);break;case RETURN:p+="return";if(n.value)p+=" "+pp(n.value,d);break;case YIELD:p+="yield";if(n.value.type)p+=" "+pp(n.value,d);break;case GENERATOR:p+=pp(n.expression,d)+" "+pp(n.tail,d);break;case WITH:p+="with ("+pp(n.object,d)+") ";p+=pp(n.body,d);break;case LET:case VAR:case CONST:var nc=n.children;if(!inLetHead){p+=tokens[n.type]+" "}for(var i=0,j=nc.length;i<j;i++){if(i>0)p+=", ";var u=nc[i];p+=pp(u.name,d);if(u.initializer)p+=" = "+pp(u.initializer,d)}break;case DEBUGGER:p+="debugger\n";break;case SEMICOLON:if(n.expression){p+=pp(n.expression,d)+";"}break;case LABEL:p+=n.label+":\n"+pp(n.statement,d);break;case COMMA:case LIST:var nc=n.children;for(var i=0,j=nc.length;i<j;i++){if(i>0)p+=", ";p+=pp(nc[i],d)}break;case ASSIGN:var nc=n.children;var t=n.assignOp;p+=pp(nc[0],d)+" "+(t?tokens[t]:"")+"="+" "+pp(nc[1],d);break;case HOOK:var nc=n.children;p+="("+pp(nc[0],d)+" ? "+pp(nc[1],d)+" : "+pp(nc[2],d);p+=")";break;case OR:case AND:var nc=n.children;p+="("+pp(nc[0],d)+" "+tokens[n.type]+" "+pp(nc[1],d);p+=")";break;case BITWISE_OR:case BITWISE_XOR:case BITWISE_AND:case EQ:case NE:case STRICT_EQ:case STRICT_NE:case LT:case LE:case GE:case GT:case IN:case INSTANCEOF:case LSH:case RSH:case URSH:case PLUS:case MINUS:case MUL:case DIV:case MOD:var nc=n.children;p+="("+pp(nc[0],d)+" "+tokens[n.type]+" "+pp(nc[1],d)+")";break;case DELETE:case VOID:case TYPEOF:p+=tokens[n.type]+" "+pp(n.children[0],d);break;case NOT:case BITWISE_NOT:p+=tokens[n.type]+pp(n.children[0],d);break;case UNARY_PLUS:p+="+"+pp(n.children[0],d);break;case UNARY_MINUS:p+="-"+pp(n.children[0],d);break;case INCREMENT:case DECREMENT:if(n.postfix){p+=pp(n.children[0],d)+tokens[n.type]}else{p+=tokens[n.type]+pp(n.children[0],d)}break;case DOT:var nc=n.children;p+=pp(nc[0],d)+"."+pp(nc[1],d);break;case INDEX:var nc=n.children;p+=pp(nc[0],d)+"["+pp(nc[1],d)+"]";break;case CALL:var nc=n.children;p+=pp(nc[0],d)+"("+pp(nc[1],d)+")";break;case NEW:case NEW_WITH_ARGS:var nc=n.children;p+="new "+pp(nc[0],d);if(nc[1])p+="("+pp(nc[1],d)+")";break;case ARRAY_INIT:p+="[";var nc=n.children;for(var i=0,j=nc.length;i<j;i++){if(nc[i])p+=pp(nc[i],d);p+=","}p+="]";break;case ARRAY_COMP:p+="["+pp(n.expression,d)+" ";p+=pp(n.tail,d);p+="]";break;case COMP_TAIL:var nc=n.children;for(var i=0,j=nc.length;i<j;i++){if(i>0)p+=" ";p+=pp(nc[i],d)}if(n.guard)p+=" if ("+pp(n.guard,d)+")";break;case OBJECT_INIT:var nc=n.children;if(nc[0]&&nc[0].type===PROPERTY_INIT)p+="{\n";else p+="{";for(var i=0,j=nc.length;i<j;i++){if(i>0){p+=",\n"}var t=nc[i];if(t.type===PROPERTY_INIT){var tc=t.children;var l;if(typeof tc[0].value==="string"&&!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(tc[0].value)){l=nodeStr(tc[0])}else{l=pp(tc[0],d)}p+=indent(4,l)+": "+indent(4,pp(tc[1],d)).substring(4)}else{p+=indent(4,pp(t,d))}}p+="\n}";break;case NULL:p+="null";break;case THIS:p+="this";break;case TRUE:p+="true";break;case FALSE:p+="false";break;case IDENTIFIER:case NUMBER:case REGEXP:if(n.value.isOctal)p+="0"+n.value.toString(8);else p+=n.value;break;case STRING:p+=nodeStr(n);break;case GROUP:p+="("+pp(n.children[0],d)+")";break;default:throw"PANIC: unknown operation "+tokens[n.type]+" "+n.toSource()}if(n.parenthesized)p+=")";return p}return{pp:pp}}();"use strict";(function(exports){exports.version="0.10.8"})(typeof exports!=="undefined"?exports:Streamline.version=Streamline.version||{});"use strict";(function(){var sourceMap;if(typeof exports!=="undefined"){var req=srequire;try{sourceMap=req("source-map")}catch(ex){}}if(!sourceMap){sourceMap={SourceNode:function(lineno,column,source,content){this.children=content?[content]:[]}};sourceMap.SourceNode.prototype.add=function(elt){if(Array.isArray(elt))this.children=this.children.concat(elt);else this.children.push(elt);return this};sourceMap.SourceNode.prototype.prepend=function(elt){if(Array.isArray(elt))this.children=elt.concat(this.children.concat);else this.children.unshift(elt);return this};sourceMap.SourceNode.prototype.toString=function(){var str="";this.walk(function(chunk){str+=chunk});return str};sourceMap.SourceNode.prototype.walk=function(f){this.children.forEach(function(n){if(n instanceof sourceMap.SourceNode)n.walk(f);else f(n)});return this}}(function(module){function SourceNode(){sourceMap.SourceNode.apply(this,arguments)}SourceNode.prototype=Object.create(sourceMap.SourceNode.prototype,{constructor:{value:SourceNode,enumerable:false,writable:true,configurable:true},length:{get:function(){var len=0;this.walk(function(str){len+=str.length});return len}}});SourceNode.prototype.stripPrefix=function(offset){var _len;while(this.children.length>0&&offset>0&&(_len=this.children[0].length)<=offset){this.children.shift();offset-=_len}if(this.children.length==0||offset==0)return this;if(typeof this.children[0]=="string"){this.children[0]=this.children[0].substring(offset)}else{this.children[0].stripPrefix(offset)}return this};SourceNode.prototype.stripSuffix=function(offset){var _len,chlen;while((chlen=this.children.length)>0&&offset>0&&(_len=this.children[chlen-1].length)<=offset){this.children.pop();offset-=_len}if(chlen==0||offset==0)return this;if(typeof this.children[chlen-1]=="string"){this.children[chlen-1]=this.children[0].slice(0,-offset)}else{this.children[chlen-1].stripSuffix(offset)}return this};SourceNode.prototype.map=function(f){this.children=this.children.map(function(chunk){if(chunk instanceof sourceMap.SourceNode){return chunk.map(f)}else{return f(chunk)}});return this};SourceNode.prototype.lastChar=function(){for(var i=this.children.length;i--;){var ret;if(typeof this.children[i]=="string"){ret=this.children[i].slice(-1)}else{ret=this.children[i].lastChar()}if(ret)return ret}return""};module.exports=Object.create(sourceMap,{SourceNode:{value:SourceNode}})})(typeof exports!=="undefined"?module:Streamline.sourceMap=Streamline.sourceMap||{})})();if(typeof exports!=="undefined"){var Narcissus=srequire("streamline/deps/narcissus")}var sourceMap=srequire("streamline/lib/util/source-map");(function(exports){eval(Narcissus.definitions.consts);var tokens=Narcissus.definitions.tokens;exports.format=function(node,linesOpt){var result="";var ppOut=_pp(node);if(linesOpt=="sourcemap"){return ppOut.source}ppOut.source=ppOut.source.toString();if(linesOpt=="ignore")return ppOut.source;var lineMap=ppOut.lineMap;var lines=ppOut.source.split("\n");if(linesOpt=="preserve"){var outputLineNo=1,bol=true;for(var i=0;i<lines.length;i++){var sourceNodes=(lineMap[i]||[]).filter(function(n){return n._isSourceNode});if(sourceNodes.length>0){var sourceLineNo=sourceNodes[0].lineno;while(outputLineNo<sourceLineNo){result+="\n";outputLineNo+=1;bol=true}}result+=bol?lines[i]:lines[i].replace(/^\s+/," ");bol=false}result+="\n"}else if(linesOpt=="mark"){for(var i=0;i<lines.length;i++){var line=lines[i];var sourceNodes=(lineMap[i]||[]).filter(function(n){return n._isSourceNode});var linePrefix="            ";if(sourceNodes.length>0){var sourceLineNo=""+sourceNodes[0].lineno;linePrefix="/* ";for(var j=sourceLineNo.length;j<5;j++)linePrefix+=" ";linePrefix+=sourceLineNo+" */ "}result+=linePrefix+line+"\n"}}else throw new Error("bad --lines option: "+linesOpt);return result};function _pp(node){var curLineNo=0;var lineNodeMap={};var src=pp(node);return{source:src,lineMap:lineNodeMap};function countNewline(s){curLineNo+=1;return s}function indent(n,s){var dent=new Array(n+1).join(" ");s.map(function(str){return str.replace(/\n/g,"\n"+dent)});s.prepend(new sourceMap.SourceNode(null,null,null,dent));return s}function isBlock(n){return n&&n.type===BLOCK}function isNonEmptyBlock(n){return isBlock(n)&&n.children.length>0}var lines;function sourceNodeFromNode(n,content){var lineno,column,source=n.tokenizer&&n.tokenizer.filename;source=source||void 0;var start=n.start,end=n.end;var sourceString=n.tokenizer&&n.tokenizer.source;if(!source||!start||!end||!sourceString){return new sourceMap.SourceNode(void 0,void 0,void 0,content)}if(source&&!lines){lines=[];lines[-1]=0;var lineno=1;for(var index=sourceString.indexOf("\n");index>=0;index=sourceString.indexOf("\n",index+1)){lines[index]=lineno;lineno++}}while(start<end&&" \n\t;{}".indexOf(sourceString[start])>=0)start++;if(start<end){var fragment=sourceString.substring(start,end);var newline=sourceString.lastIndexOf("\n",start);lineno=lines[newline]+1;column=start-(newline+1)}else{source=void 0}return new sourceMap.SourceNode(lineno,column,source,content)}function nodeStr(n){return sourceNodeFromNode(n,'"'+n.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r")+'"')}function pp(n,d,inLetHead){var topScript=false;if(!n)return"";if(!(n instanceof Object))return""+n;if(!d){topScript=true;d=1}if(!lineNodeMap[curLineNo])lineNodeMap[curLineNo]=[];lineNodeMap[curLineNo].push(n);var p=sourceNodeFromNode(n);if(n.parenthesized)p.add("(");switch(n.type){case FUNCTION:case GETTER:case SETTER:if(n.type===FUNCTION)p.add("function");else if(n.type===GETTER)p.add("get");else p.add("set");if(n.name){p.add([" ",sourceNodeFromNode(n,n.name)])}p.add("(");for(var i=0,j=n.params.length;i<j;i++){p.add([i>0?", ":"",pp(n.params[i],d)])}p.add([") ",pp(n.body,d)]);break;case SCRIPT:case BLOCK:var nc=n.children;if(topScript){for(var i=0,j=nc.length;i<j;i++){if(i>0)p.add(countNewline("\n"));p.add(pp(nc[i],d));if(p.lastChar()!=";")p.add(";")}break}p.add("{");if(n.id!==undefined)p.add(" /* "+n.id+" */");p.add(countNewline("\n"));for(var i=0,j=nc.length;i<j;i++){if(i>0)p.add(countNewline("\n"));p.add(indent(2,pp(nc[i],d)));if(p.lastChar()!=";")p.add(";")}p.add(countNewline("\n}"));break;case LET_BLOCK:p.add(["let (",pp(n.variables,d,true),") "]);if(n.expression)p.add(pp(n.expression,d));else p.add(pp(n.block,d));break;case IF:p.add(["if (",pp(n.condition,d),") "]);var tp=n.thenPart,ep=n.elsePart;var b=isBlock(tp)||isBlock(ep);if(!b)p.add(countNewline("{\n"));p.add(b?pp(tp,d):indent(2,pp(tp,d)));if(ep&&";}".indexOf(p.lastChar())<0)p.add(";");p.add(countNewline("\n"));if(ep){if(!b)p.add(countNewline("} else {\n"));else p.add(" else ");p.add([b?pp(ep,d):indent(2,pp(ep,d)),countNewline("\n")])}if(!b)p.add("}");break;case SWITCH:p.add(["switch (",pp(n.discriminant,d),countNewline(") {\n")]);for(var i=0,j=n.cases.length;i<j;i++){var ca=n.cases[i];if(ca.type===CASE)p.add(["case ",pp(ca.caseLabel,d),countNewline(":\n")]);else p.add(countNewline("  default:\n"));p.add([pp(ca.statements,d).stripPrefix(2).stripSuffix(2),countNewline("\n")]);curLineNo-=2}p.add("}");break;case FOR:p.add(["for (",pp(n.setup,d),"; ",pp(n.condition,d),"; ",pp(n.update,d),") "]);var pb=pp(n.body,d);if(!isBlock(n.body)){p.add([countNewline("{\n"),indent(2,pb),countNewline(";\n}")])}else if(n.body)p.add(pb);break;case WHILE:p.add(["while (",pp(n.condition,d),") "]);var pb=pp(n.body,d);if(!isBlock(n.body)){p.add([countNewline("{\n"),indent(2,pb),countNewline(";\n}")])}else p.add(pb);break;case FOR_IN:var u=n.varDecl;p.add([n.isEach?"for each (":"for (",u?pp(u,d):pp(n.iterator,d)," in ",pp(n.object,d),") "]);var pb=pp(n.body,d);if(!isBlock(n.body)){p.add([countNewline("{\n"),indent(2,pb),countNewline(";\n}")])}else if(n.body)p.add(pb);break;case DO:p.add(["do ",pp(n.body,d)," while (",pp(n.condition,d),");"]);break;case BREAK:p.add(["break",n.label?" "+n.label:"",";"]);break;case CONTINUE:p.add(["continue",n.label?" "+n.label:"",";"]);break;case TRY:p.add(["try ",pp(n.tryBlock,d)]);for(var i=0,j=n.catchClauses.length;i<j;i++){var t=n.catchClauses[i];p.add([" catch (",pp(t.varName,d),t.guard?" if "+pp(t.guard,d):"",") ",pp(t.block,d)])}if(n.finallyBlock){p.add([" finally ",pp(n.finallyBlock,d)])}break;case THROW:p.add(["throw ",pp(n.exception,d)]);break;case RETURN:p.add("return");if(n.value){p.add([" ",pp(n.value,d)])}break;case YIELD:p.add("yield");if(n.value.type){p.add([" ",pp(n.value,d)])}break;case GENERATOR:p.add([pp(n.expression,d)," ",pp(n.tail,d)]);break;case WITH:p.add(["with (",pp(n.object,d),") ",pp(n.body,d)]);break;case LET:case VAR:case CONST:var nc=n.children;if(!inLetHead){p.add([tokens[n.type]," "])}for(var i=0,j=nc.length;i<j;i++){if(i>0)p.add(", ");var u=nc[i];p.add(pp(u.name,d));if(u.initializer){p.add([" = ",pp(u.initializer,d)])}}break;case DEBUGGER:p.add(countNewline("debugger\n"));break;case SEMICOLON:if(n.expression){p.add([pp(n.expression,d),";"])}break;case LABEL:p.add([n.label,countNewline(":\n"),pp(n.statement,d)]);break;case COMMA:case LIST:var nc=n.children;for(var i=0,j=nc.length;i<j;i++){if(i>0)p.add(", ");p.add(pp(nc[i],d))}break;case ASSIGN:var nc=n.children;var t=n.assignOp;p.add([pp(nc[0],d)," ",t?tokens[t]:"","="," ",pp(nc[1],d)]);break;case HOOK:var nc=n.children;p.add(["(",pp(nc[0],d)," ? ",pp(nc[1],d)," : ",pp(nc[2],d),")"]);break;case OR:case AND:var nc=n.children;p.add(["(",pp(nc[0],d)," ",tokens[n.type]," ",pp(nc[1],d),")"]);break;case BITWISE_OR:case BITWISE_XOR:case BITWISE_AND:case EQ:case NE:case STRICT_EQ:case STRICT_NE:case LT:case LE:case GE:case GT:case IN:case INSTANCEOF:case LSH:case RSH:case URSH:case PLUS:case MINUS:case MUL:case DIV:case MOD:var nc=n.children;p.add(["(",pp(nc[0],d)," ",tokens[n.type]," ",pp(nc[1],d),")"]);break;case DELETE:case VOID:case TYPEOF:p.add([tokens[n.type]," ",pp(n.children[0],d)]);break;case NOT:case BITWISE_NOT:p.add([tokens[n.type],pp(n.children[0],d)]);break;case UNARY_PLUS:p.add(["+",pp(n.children[0],d)]);break;case UNARY_MINUS:p.add(["-",pp(n.children[0],d)]);break;case INCREMENT:case DECREMENT:if(n.postfix){p.add([pp(n.children[0],d),tokens[n.type]])}else{p.add([tokens[n.type],pp(n.children[0],d)])}break;case DOT:var nc=n.children;p.add([pp(nc[0],d),".",pp(nc[1],d)]);break;case INDEX:var nc=n.children;p.add([pp(nc[0],d),"[",pp(nc[1],d),"]"]);break;case CALL:var nc=n.children;p.add([pp(nc[0],d),"(",pp(nc[1],d),")"]);break;case NEW:case NEW_WITH_ARGS:var nc=n.children;p.add("new ");p.add(pp(nc[0],d));if(nc[1]){p.add(["(",pp(nc[1],d),")"])}break;case ARRAY_INIT:p.add("[");var nc=n.children;for(var i=0,j=nc.length;i<j;i++){if(nc[i])p.add(pp(nc[i],d));p.add(",")}p.add("]");break;case ARRAY_COMP:p.add(["[",pp(n.expression,d)," ",pp(n.tail,d),"]"]);break;case COMP_TAIL:var nc=n.children;for(var i=0,j=nc.length;i<j;i++){if(i>0)p.add(" ");p.add(pp(nc[i],d))}if(n.guard){p.add([" if (",pp(n.guard,d),")"])}break;case OBJECT_INIT:var nc=n.children;if(nc[0]&&nc[0].type===PROPERTY_INIT)p.add(countNewline("{\n"));else p.add("{");for(var i=0,j=nc.length;i<j;i++){if(i>0){p.add(countNewline(",\n"))}var t=nc[i];if(t.type===PROPERTY_INIT){var tc=t.children;var l;if(typeof tc[0].value==="string"&&!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(tc[0].value)){l=nodeStr(tc[0]);p.add(l)}else{l=pp(tc[0],d);p.add(indent(2,l))}p.add([": ",indent(2,pp(tc[1],d)).stripPrefix(2)])}else{p.add(indent(2,pp(t,d)))}}p.add(countNewline("\n}"));break;case NULL:p.add("null");break;case THIS:p.add("this");break;case TRUE:p.add("true");break;case FALSE:p.add("false");break;case IDENTIFIER:case NUMBER:case REGEXP:if(n.value.isOctal)p.add("0"+n.value.toString(8));else p.add(""+n.value);break;case STRING:p.add(nodeStr(n));break;case GROUP:p.add(["(",pp(n.children[0],d),")"]);break;default:throw"PANIC: unknown operation "+tokens[n.type]+" "+n.toSource()}if(n.parenthesized)p.add(")");return p}}})(typeof exports!=="undefined"?exports:window.Streamline=window.Streamline||{});if(typeof exports!=="undefined"){var Narcissus=srequire("../../deps/narcissus");var format=srequire("./format").format}else{var format=Streamline.format}(function(exports){exports.version=srequire("streamline/lib/version").version+" (callbacks)";var parse=Narcissus.parser.parse;var pp=Narcissus.decompiler.pp;var definitions=Narcissus.definitions;eval(definitions.consts.replace(/const /g,"var "));function _assert(cond){if(!cond)throw new Error("Assertion failed!")}function _tag(node){if(!node||!node.type)return"*NOT_A_NODE*";var t=definitions.tokens[node.type];return/^\W/.test(t)?definitions.opTypeNames[t]:t.toUpperCase()}function originalLine(options,line,col){if(!options.prevMap)return line;if(col==null)col=1e3;var r=options.prevMap.originalPositionFor({line:line,column:col}).line;return r==null?line:r}function originalCol(options,line,col){if(!options.prevMap)return col;return options.prevMap.originalPositionFor({line:line,column:col}).column||0}function _node(ref,type,children){return{_scope:ref&&ref._scope,_async:ref&&ref._async,type:type,children:children}}function _identifier(name,initializer){return{_scope:initializer&&initializer._scope,type:IDENTIFIER,name:name,value:name,initializer:initializer}}function _number(val){return{type:NUMBER,value:val}}function _string(val){return{type:STRING,value:val}}function _return(node){return{type:RETURN,_scope:node._scope,value:node}}function _semicolon(node){var stmt=_node(node,SEMICOLON);stmt.expression=node;return stmt}function _safeName(precious,name){if(name.substring(0,2)==="__")while(precious[name])name+="A";return name}function _flatten(node){if(node.type==BLOCK||node.type==SCRIPT){do{var found=false;var children=[];node.children.forEach(function(child){if(child._isFunctionReference||child.type==SEMICOLON&&(child.expression==null||child.expression._isFunction))return;node._async|=child._async;if(child.type==BLOCK||child.type==SCRIPT){children=children.concat(child.children);found=true}else children.push(child)});node.children=children}while(found)}return node}function _propagate(node,fn,doAll,clone){var result=clone?clone:node;for(var prop in node){if(node.hasOwnProperty(prop)&&prop.indexOf("Decls")<0&&(doAll||prop!="target")&&prop[0]!="_"){var child=node[prop];if(child!=null){if(Array.isArray(child)){if(clone)result[prop]=child=[].concat(child);var undef=false;for(var i=0;i<child.length;i++){if(doAll||child[i]&&child[i].type){child[i]=fn(child[i],node);undef|=typeof child[i]==="undefined"}}if(undef){result[prop]=child.filter(function(elt){return typeof elt!=="undefined"})}}else{if(doAll||child&&child.type)result[prop]=fn(child,node)}}}}return result}function _clone(node){var lastId=0;var clones={};function cloneOne(child){if(!child||!child.type)return child;var cloneId=child._cloneId;if(!cloneId)cloneId=child._cloneId=++lastId;var clone=clones[cloneId];if(clone)return clone;clones[cloneId]=clone={_cloneId:cloneId};return _propagate(child,cloneOne,true,clone)}return _propagate(node,cloneOne,true,{})}function Template(pass,str,isExpression,createScope){var _root=parse("function _t(){"+str+"}").children[0].body;if(_root.children.length==1)_root=_root.children[0];else _root=_node(_root.children[0],BLOCK,_root.children);this.generate=function(scopeNode,bindings){var scope=scopeNode._scope;_assert(scope!=null);bindings=bindings||{};var fn=null;function gen(node){if(node.type!=SCRIPT&&node.type!=BLOCK)node._pass=pass;if(node.type==FUNCTION&&createScope){_assert(fn==null);fn=node}if(!node||!node.type){if(node=="_")return scope.options.callback;if(typeof node==="string"){if(node[0]==="$")return bindings[node];return _safeName(scope.options.precious,node)}return node}node._scope=scope;var ident=node.type==SEMICOLON?node.expression:node;if(ident&&ident.type==IDENTIFIER&&ident.value[0]==="$"){var result=bindings[ident.value];if(ident.initializer){result.initializer=gen(ident.initializer);if(result.initializer._async)result._async=true}return result}else{node=_propagate(node,function(child){child=gen(child);if(child&&(child._async||child===scope.options.callback&&createScope)&&node.type!==FUNCTION)node._async=true;return child},true);node=_flatten(node);return node}}var result=gen(_clone(_root));if(fn){fn.parenthesized=true;var scope=new Scope(fn.body,fn._scope.options);scope.name=fn._scope.name;scope.line=fn._scope.line;scope.last=fn._scope.last;_assert(fn.params[0]===fn._scope.options.callback);scope.cbIndex=0;function _changeScope(node,parent){if(node.type==FUNCTION)return node;node._scope=scope;return _propagate(node,_changeScope)}_propagate(fn,_changeScope)}return isExpression?result.value:result};this.root=isExpression?_root.value:_root}function Scope(script,options){this.script=script;this.line=0;this.last=0;this.vars=[];this.functions=[];this.options=options;this.cbIndex=-1;this.isAsync=function(){return this.cbIndex>=0}}function _genId(node){return _safeName(node._scope.options.precious,"__"+ ++node._scope.last)}function _removeFast(node,options){function _isMarker(node){return node.type===IDENTIFIER&&node.value===options.callback}function _isStar(node){return node.type===CALL&&_isMarker(node.children[0])&&node.children[1].children.length===2}if(node.type===BITWISE_NOT&&_isMarker(node.children[0])){options.needsTransform=true;return node.children[0]}if(node.type===ARRAY_INIT&&node.children.length===1&&_isMarker(node.children[0])){options.needsTransform=true;node.children[0]._returnArray=true;return node.children[0]}if(node.type===RSH&&_isMarker(node.children[0])){options.needsTransform=true;return node.children[1]}if(node.type===LSH&&_isMarker(node.children[0])){options.needsTransform=true;return node.children[1]}if(node.type===NOT&&_isMarker(node.children[0])){options.needsTransform=true;node.type=FALSE;node.children=[];return node}if(_isStar(node)){node._isStar=true;options.needsTransform=true;node.children[0].value=_safeName(options.precious,"__rt")+".streamlinify";return node}return node}function _markSource(node,options){function _markOne(node){if(typeof node.value==="string")options.precious[node.value]=true;node.params&&node.params.forEach(function(param){options.precious[param]=true});node._isSourceNode=true;_propagate(node,function(child){child=_removeFast(child,options);_markOne(child);return child})}_markOne(node)}function _isScriptAsync(script,options){var async=false;function _doIt(node,parent){switch(node.type){case FUNCTION:return node;case IDENTIFIER:if(node.value==options.callback){async=true}else{_propagate(node,_doIt)}return node;case CALL:var fn=node.children[0],args=node.children[1],ident;if(fn.type===DOT&&(ident=fn.children[1]).value==="call"&&(fn=fn.children[0]).type===FUNCTION&&fn.params.length===0&&!fn.name&&args.children.length===1&&args.children[0].type===THIS){_propagate(fn.body,_doIt);return node}default:if(!async){_propagate(node,_doIt)}return node}}_propagate(script,_doIt);if(async&&options.verbose)console.log("WARNING: async calls found at top level in "+script.filename);return async}var _rootTemplate=new Template("root","(function main(_){ $script }).call(this, __trap);");function _canonTopLevelScript(script,options){script._scope=new Scope(script,options);if(_isScriptAsync(script,options))return _rootTemplate.generate(script,{$script:script});else return script}var _assignTemplate=new Template("canon","$lhs = $rhs;");function _guessName(node,parent){function _sanitize(name){name=name.replace(/[^A-Z0-9_$]/gi,"_o_");return name&&!/^\d/.test(name)?name:"_o_"+name}var id=_genId(node),n,nn;if(parent.type===IDENTIFIER)return _sanitize(parent.value)+id;if(parent.type===ASSIGN){n=parent.children[0];var s="";while(n.type===DOT&&(nn=n.children[1]).type===IDENTIFIER||n.type===INDEX&&(nn=n.children[1]).type===STRING){s=s?nn.value+"_"+s:nn.value;n=n.children[0]}if(n.type===IDENTIFIER)s=s?n.value+"_"+s:n.value;if(s)return _sanitize(s)+id}else if(parent.type==PROPERTY_INIT){n=parent.children[0];if(n.type===IDENTIFIER||n.type===STRING)return _sanitize(n.value)+id}return id}function _canonScopes(node,options){function _doIt(node,parent){var scope=parent._scope;node._scope=scope;var async=scope.isAsync();if(!async&&node.type!==FUNCTION){if(node.type===IDENTIFIER&&node.value===options.callback&&!parent._isStar){throw new Error(node.filename+": Function contains async calls but does not have _ parameter: "+node.name+" at line "+node.lineno)}return _propagate(node,_doIt);
  }if(node.type===TRY)node._async=true;switch(node.type){case FUNCTION:var result=node;var cbIndex=node.params.reduce(function(index,param,i){if(param!=options.callback)return index;if(index<0)return i;else throw new Error("duplicate _ parameter")},-1);if(cbIndex>=0){if(_isFatArrow(node))return node;options.needsTransform=true;if(!node.name)node.name=_guessName(node,parent)}if(async&&(parent.type===SCRIPT||parent.type===BLOCK)){scope.functions.push(node);result=undefined}var bodyScope=new Scope(node.body,options);node.body._scope=bodyScope;bodyScope.name=node.name;bodyScope.cbIndex=cbIndex;bodyScope.line=node.lineno;node.body=_propagate(node.body,_doIt);if(cbIndex>=0)bodyScope.functions.push(_string("BEGIN_BODY"));node.body.children=bodyScope.functions.concat(node.body.children);if(bodyScope.hasThis&&!node._inhibitThis){bodyScope.vars.push(_identifier(_safeName(options.precious,"__this"),_node(node,THIS)))}if(bodyScope.hasArguments&&!node._inhibitArguments){bodyScope.vars.push(_identifier(_safeName(options.precious,"__arguments"),_identifier("arguments")))}if(bodyScope.vars.length>0){node.body.children.splice(0,0,_node(node,VAR,bodyScope.vars))}return result;case VAR:var children=node.children.map(function(child){if(!scope.vars.some(function(elt){return elt.value==child.value})){scope.vars.push(_identifier(child.value))}if(!child.initializer)return null;child=_assignTemplate.generate(parent,{$lhs:_identifier(child.value),$rhs:child.initializer});if(parent.type===FOR)child=child.expression;return child}).filter(function(child){return child!=null});if(children.length==0){return}var type=parent.type==BLOCK||parent.type===SCRIPT?BLOCK:COMMA;var result=_node(parent,type,children);result=_propagate(result,_doIt);parent._async|=result._async;return result;case THIS:scope.hasThis=true;return _identifier(_safeName(options.precious,"__this"));case IDENTIFIER:if(node.value==="arguments"){scope.hasArguments=true;return _identifier(_safeName(options.precious,"__arguments"))}node=_propagate(node,_doIt);node._async|=node.value===options.callback;if(node._async&&!parent.isArgsList&&!(parent.type===PROPERTY_INIT&&node===parent.children[0])&&!(parent.type===DOT&&node===parent.children[1]))throw new Error("invalid usage of '_'");parent._async|=node._async;return node;case NEW_WITH_ARGS:var cbIndex=node.children[1].children.reduce(function(index,arg,i){if(arg.type!==IDENTIFIER||arg.value!==options.callback)return index;if(index<0)return i;else throw new Error("duplicate _ argument")},-1);if(cbIndex>=0){var constr=_node(node,CALL,[_identifier(_safeName(options.precious,"__construct")),_node(node,LIST,[node.children[0],_number(cbIndex)])]);node=_node(node,CALL,[constr,node.children[1]])}node.children[1].isArgsList=true;node=_propagate(node,_doIt);parent._async|=node._async;return node;case CALL:node.children[1].isArgsList=true;_convertCoffeeScriptCalls(node,options);_convertApply(node,options);node.children[1].isArgsList=true;default:node=_propagate(node,_doIt);_setBreaks(node);parent._async|=node._async;return node}}return _propagate(node,_doIt)}function _convertCoffeeScriptCalls(node,options){var fn=node.children[0];var args=node.children[1];if(fn.type===FUNCTION&&fn.params.length===0&&!fn.name&&args.children.length==0){fn._noFuture=true;fn.name="___closure";fn.params=[options.callback];args.children=[_identifier(options.callback)]}else if(fn.type===DOT){var ident=fn.children[1];fn=fn.children[0];if(fn.type===FUNCTION&&fn.params.length===0&&!fn.name&&ident.type===IDENTIFIER){if(ident.value==="call"&&args.children.length===1&&args.children[0].type===THIS){node.children[0]=fn;fn._noFuture=true;fn.name="___closure";fn.params=[options.callback];args.children=[_identifier(options.callback)];node._scope.hasThis=true;fn._inhibitThis=true}else if(ident.value==="apply"&&args.children.length===2&&args.children[0].type===THIS&&args.children[1].type===IDENTIFIER&&args.children[1].value==="arguments"){node.children[0]=fn;fn._noFuture=true;fn.name="___closure";fn.params=[options.callback];args.children=[_identifier(options.callback)];node._scope.hasThis=true;node._scope.hasArguments=true;fn._inhibitThis=true;fn._inhibitArguments=true}}}}function _isFatArrow(node){if(node.body.children.length!==1)return false;var n=node.body.children[0];if(n.type!==RETURN||!n.value)return false;n=n.value;if(n.type!==CALL)return false;var args=n.children[1].children;var target=n.children[0];if(args.length!==2||args[0].value!=="_this"||args[1].value!=="arguments")return false;if(target.type!==DOT||target.children[1].value!=="apply")return false;target=target.children[0];if(target.type!==DOT||target.children[1].type!==IDENTIFIER)return false;target=target.children[0];if(target.type!==DOT||target.children[1].value!=="prototype")return false;target=target.children[0];if(target.type!==IDENTIFIER)return false;node.params=[];return true}function _convertApply(node,options){var dot=node.children[0];var args=node.children[1];if(dot.type===DOT){var ident=dot.children[1];if(ident.type===IDENTIFIER&&ident.value==="apply"&&args.children.length===2&&args.children[0].type===THIS&&args.children[1].type===IDENTIFIER&&args.children[1].value==="arguments"){var f=dot.children[0];node.children[0]=_identifier("__apply");args.children=[_identifier(options.callback),f,_identifier("__this"),_identifier("__arguments"),_number(node._scope.cbIndex)];node._scope.hasThis=true;node._scope.hasArguments=true}}}var _switchVarTemplate=new Template("canon","{ var $v = true; }");var _switchIfTemplate=new Template("canon","if ($v) { $block; }");function _setBreaks(node){switch(node.type){case IF:node._breaks=node.thenPart._breaks&&node.elsePart&&node.elsePart._breaks;break;case SWITCH:for(var i=0;i<node.cases.length;i++){var stmts=node.cases[i].statements;if(node._async&&stmts.children.length>0&&!stmts._breaks){if(i==node.cases.length-2&&node.cases[i+1].type===DEFAULT&&node.cases[i+1].statements.children.length===1&&node.cases[i+1].statements.children[0].type===SEMICOLON&&node.cases[i+1].statements.children[0].expression==null){stmts.children.push(_node(node,BREAK));stmts._breaks=true}else if(i===node.cases.length-1){stmts.children.push(_node(node,BREAK));stmts._breaks=true}else{var v=_identifier(_genId(node));node.cases[i].statements=_switchVarTemplate.generate(node.cases[i],{$v:v});var ifStmt=_switchIfTemplate.generate(node.cases[i],{$v:v,$block:stmts});node.cases[i+1].statements.children.splice(0,0,ifStmt)}}}break;case TRY:node._breaks=node.tryBlock._breaks&&node.catchClauses[0]&&node.catchClauses[0].block._breaks;break;case BLOCK:case SCRIPT:node.children.forEach(function(child){node._breaks|=child._breaks});break;case RETURN:case THROW:case BREAK:node._breaks=true;break}}function _statementify(exp){if(!exp)return exp;var block=_node(exp,BLOCK,[]);function uncomma(node){if(node.type===COMMA){node.children.forEach(uncomma)}else{block.children.push(node.type==SEMICOLON?node:_semicolon(node))}}uncomma(exp);return block}function _blockify(node){if(!node||node.type==BLOCK)return node;if(node.type==COMMA)return _statementify(node);var block=_node(node,BLOCK,[node]);block._async=node._async;return block}var _flowsTemplates={WHILE:new Template("flows","{"+"\tfor (; $condition;) {"+"\t\t$body;"+"\t}"+"}"),DO:new Template("flows","{"+"\tvar $firstTime = true;"+"\tfor (; $firstTime || $condition;) {"+"\t\t$firstTime = false;"+"\t\t$body;"+"\t}"+"}"),FOR:new Template("flows","{"+"\t$setup;"+"\tfor (; $condition; $update) {"+"\t\t$body;"+"\t}"+"}"),FOR_IN:new Template("flows","{"+"\tvar $array = __forIn($object);"+"\tvar $i = 0;"+"\tfor (; $i < $array.length;) {"+"\t\t$iter = $array[$i++];"+"\t\t$body;"+"\t}"+"}"),TRY:new Template("flows",""+"try {"+"\ttry { $try; }"+"\tcatch ($ex) { $catch; }"+"}"+"finally { $finally; }"),AND:new Template("flows",""+"return (function $name(_){"+"\tvar $v = $op1;"+"\tif (!$v) {"+"\t\treturn $v;"+"\t}"+"\treturn $op2;"+"})(_)",true,true),OR:new Template("flows",""+"return (function $name(_){"+"\tvar $v = $op1;"+"\tif ($v) {"+"\t\treturn $v;"+"\t}"+"\treturn $op2;"+"})(_)",true,true),HOOK:new Template("flows",""+"return (function $name(_){"+"\tvar $v = $condition;"+"\tif ($v) {"+"\t\treturn $true;"+"\t}"+"\treturn $false;"+"})(_);",true,true),COMMA:new Template("flows",""+"return (function $name(_){"+"\t$body;"+"\treturn $result;"+"})(_);",true,true),CONDITION:new Template("flows",""+"return (function $name(_){"+"\treturn $condition;"+"})(_);",true,true),UPDATE:new Template("flows",""+"return (function $name(_){"+"\t$update;"+"})(_);",true,true)};function _canonFlows(node,options){function _doIt(node,parent,force){var scope=node._scope;function _doAsyncFor(node){if(node.condition&&node.condition._async&&node.condition.type!==CALL)node.condition=_flowsTemplates.CONDITION.generate(node,{$name:"__$"+node._scope.name,$condition:_doIt(node.condition,node,true)});if(node.update&&node.update._async)node.update=_flowsTemplates.UPDATE.generate(node,{$name:"__$"+node._scope.name,$update:_statementify(node.update)})}if(node.type==FOR&&node._pass==="flows")_doAsyncFor(node);if(!scope||!scope.isAsync()||!force&&node._pass==="flows")return _propagate(node,_doIt);switch(node.type){case IF:node.thenPart=_blockify(node.thenPart);node.elsePart=_blockify(node.elsePart);break;case SWITCH:if(node._async){var def=node.cases.filter(function(n){return n.type==DEFAULT})[0];if(!def){def=_node(node,DEFAULT);def.statements=_node(node,BLOCK,[]);node.cases.push(def)}if(!def._breaks){def.statements.children.push(_node(node,BREAK))}}break;case WHILE:node.body=_blockify(node.body);if(node._async){node=_flowsTemplates.WHILE.generate(node,{$condition:node.condition,$body:node.body})}break;case DO:node.body=_blockify(node.body);if(node._async){node=_flowsTemplates.DO.generate(node,{$firstTime:_identifier(_genId(node)),$condition:node.condition,$body:node.body})}break;case FOR:node.condition=node.condition||_number(1);node.body=_blockify(node.body);if(node._async){if(node.setup){node=_flowsTemplates.FOR.generate(node,{$setup:_statementify(node.setup),$condition:node.condition,$update:node.update,$body:node.body})}else{if(node._pass!=="flows"){node._pass="flows";_doAsyncFor(node)}}}break;case FOR_IN:node.body=_blockify(node.body);if(node._async){if(node.iterator.type!=IDENTIFIER){throw new Error("unsupported 'for ... in' syntax: type="+_tag(node.iterator))}node=_flowsTemplates.FOR_IN.generate(node,{$array:_identifier(_genId(node)),$i:_identifier(_genId(node)),$object:node.object,$iter:node.iterator,$body:node.body})}break;case TRY:if(node.tryBlock&&node.catchClauses[0]&&node.finallyBlock){node=_flowsTemplates.TRY.generate(node,{$try:node.tryBlock,$catch:node.catchClauses[0].block,$ex:node.catchClauses[0].varName,$finally:node.finallyBlock})}break;case AND:case OR:if(node._async){node=_flowsTemplates[_tag(node)].generate(node,{$name:"__$"+node._scope.name,$v:_identifier(_genId(node)),$op1:node.children[0],$op2:node.children[1]})}break;case HOOK:if(node._async){node=_flowsTemplates.HOOK.generate(node,{$name:"__$"+node._scope.name,$v:_identifier(_genId(node)),$condition:node.children[0],$true:node.children[1],$false:node.children[2]})}break;case COMMA:if(node._async){node=_flowsTemplates.COMMA.generate(node,{$name:"__$"+node._scope.name,$body:_node(node,BLOCK,node.children.slice(0,node.children.length-1).map(_semicolon)),$result:node.children[node.children.length-1]})}break}return _propagate(node,_doIt)}return _propagate(node,_doIt)}function _split(node,prop){var exp=node[prop];if(!exp||!exp._async)return node;var id=_genId(node);var v=_identifier(id,exp);node[prop]=_identifier(id);return _node(node,BLOCK,[_node(node,VAR,[v]),node])}function _disassemble(node,options){function _disassembleIt(node,parent,noResult){if(!node._async)return _propagate(node,_scanIt);node=_propagate(node,_disassembleIt);if(node.type===CALL){if(node.children[0].type===IDENTIFIER&&node.children[0].value.indexOf("__wrap")==0){node._isWrapper=true;return node}var args=node.children[1];if(args.children.some(function(arg){return arg.type===IDENTIFIER&&arg.value===options.callback||arg._isWrapper})){if(noResult){node._scope.disassembly.push(_statementify(node));return}else{if(parent.type==IDENTIFIER&&parent.value.indexOf("__")===0){node._skipDisassembly=true;return node}var id=_genId(node);var v=_identifier(id,node);node=_node(node,VAR,[v]);node._scope.disassembly.push(node);return _identifier(id)}}}return node}function _scanIt(node,parent){var scope=node._scope;if(!scope||!scope.isAsync()||!node._async)return _propagate(node,_scanIt);switch(node.type){case IF:node=_split(node,"condition");break;case SWITCH:node=_split(node,"discriminant");break;case FOR:break;case RETURN:node=_split(node,"value");break;case THROW:node=_split(node,"exception");break;case VAR:_assert(node.children.length===1);var ident=node.children[0];scope.disassembly=[];ident.initializer=_disassembleIt(ident.initializer,ident);node._async=ident.initializer._skipDisassembly;scope.disassembly.push(node);return _node(parent,BLOCK,scope.disassembly);case SEMICOLON:scope.disassembly=[];node.expression=_disassembleIt(node.expression,node,true);if(node.expression){node._async=false;scope.disassembly.push(node)}return _node(parent,BLOCK,scope.disassembly)}return _propagate(node,_scanIt)}return _propagate(node,_scanIt)}var _cbTemplates={FUNCTION:new Template("cb","{"+"\t$decls;"+"\tvar __frame = { name: $fname, line: $line };"+"\treturn __func(_, this, arguments, $fn, $index, __frame, function $name(){"+"\t\t$body;"+"\t\t_();"+"\t});"+"}"),FUNCTION_INTERNAL:new Template("cb","{ $decls; $body; _(); }"),RETURN:new Template("cb","return _(null, $value);"),RETURN_UNDEFINED:new Template("cb","return _(null);"),THROW:new Template("cb","return _($exception);"),IF:new Template("cb",""+"return (function $name(__then){"+"\tif ($condition) { $then; __then(); }"+"\telse { $else; __then(); }"+"})(function $name(){ $tail; });"),SWITCH:new Template("cb",""+"return (function $name(__break){"+"\t$statement;"+"})(function $name(){ $tail; });"),LABEL:new Template("cb",""+"$statement;"+"$tail;"),BREAK:new Template("cb","return __break();"),LABELLED_BREAK:new Template("cb","return $break();"),CONTINUE:new Template("cb",""+"while (__more) { __loop(); } __more = true;"+"return;"),LABELLED_CONTINUE:new Template("cb",""+"while ($more.get()) { $loop(); } $more.set(true);"+"return;"),LOOP1:new Template("cb",""+"if ($v) {"+"\t$body;"+"\twhile (__more) { __loop(); } __more = true;"+"}"+"else { __break(); }"),LOOP2:new Template("temp","var $v = $condition; $loop1;"),LOOP2_UPDATE:new Template("temp",""+"if ($beenHere) { $update; } else { $beenHere = true; }"+"var $v = $condition; $loop1;"),FOR:new Template("cb",""+"return (function ___(__break){"+"\tvar __more;"+"\tvar __loop = __cb(_, __frame, 0, 0, function $name(){"+"\t\t__more = false;"+"\t\t$loop2"+"\t});"+"\tdo { __loop(); } while (__more); __more = true;"+"})(function $name(){ $tail;});"),LABELLED_FOR:new Template("cb",""+"return (function ___(__break){"+"\tvar __more, $more = { get: function() { return __more; }, set: function(v) { __more = v; }};"+"\tvar __loop = __cb(_, __frame, 0, 0, function $name(){"+"\t\tvar $break = __break, $loop = __loop;"+"\t\t__more = false;"+"\t\t$loop2"+"\t});"+"\tdo { __loop(); } while (__more); __more = true;"+"})(function $name(){ $tail;});"),FOR_UPDATE:new Template("cb",""+"var $beenHere = false;"+"return (function ___(__break){"+"\tvar __more;"+"\tvar __loop = __cb(_, __frame, 0, 0, function $name(){"+"\t\t__more = false;"+"\t\t$loop2"+"\t});"+"\tdo { __loop(); } while (__more); __more = true;"+"})(function $name(){ $tail; });"),LABELLED_FOR_UPDATE:new Template("cb",""+"var $beenHere = false;"+"return (function ___(__break){"+"\tvar __more, $more = { get: function() { return __more; }, set: function(v) { __more = v; }};"+"\tvar __loop = __cb(_, __frame, 0, 0, function $name(){"+"\t\tvar $break = __break, $loop = __loop;"+"\t\t__more = false;"+"\t\t$loop2"+"\t});"+"\tdo { __loop(); } while (__more); __more = true;"+"})(function $name(){ $tail; });"),CATCH:new Template("cb",""+"return (function ___(__then){"+"\t(function ___(_){"+"\t\t__tryCatch(_, function $name(){ $try; __then(); });"+"\t})(function ___($ex, __result){"+"\t\t__catch(function $name(){"+"\t\t\tif ($ex) { $catch; __then(); }"+"\t\t\telse { _(null, __result); }"+"\t\t});"+"\t});"+"})(function ___(){"+"\t__tryCatch(_, function $name(){ $tail; });"+"});"),FINALLY:new Template("cb",""+"return (function ___(__then){"+"\t(function ___(_){"+"\t\t__tryCatch(_, function $name(){ $try; _(null, null, true); });"+"\t})(function ___(__e, __r, __cont){"+"\t\t(function ___(__then){"+"\t\t\t__tryCatch(_, function $name(){ $finally; __then(); });"+"\t\t})(function ___(){"+"\t\t\t__tryCatch(_, function ___(){"+"\t\t\t\tif (__cont) __then(); else _(__e, __r);"+"\t\t\t});"+"\t\t})"+"\t});"+"})(function ___(){"+"\t__tryCatch(_, function $name(){ $tail; });"+"});"),CALL_VOID:new Template("cb","return __cb(_, __frame, $offset, $col, function $name(){ $tail; }, true, $returnArray)",true),CALL_TMP:new Template("cb","return __cb(_, __frame, $offset, $col, function ___(__0, $result){ $tail }, true, $returnArray)",true),CALL_RESULT:new Template("cb",""+"return __cb(_, __frame, $offset, $col, function $name(__0, $v){"+"\tvar $result = $v;"+"\t$tail"+"}, true, $returnArray)",true)};function _callbackify(node,options){var label;function _scanIt(node,parent){node=_flatten(node);if(!node._scope||!node._scope.isAsync()||node._pass==="cb")return _propagate(node,_scanIt);switch(node.type){case SCRIPT:if(parent._pass!=="cb"){var decls;for(var cut=0;cut<node.children.length;cut++){var child=node.children[cut];if(child.type===STRING&&child.value==="BEGIN_BODY"){decls=node.children.splice(0,cut);node.children.splice(0,1);break}}var template=parent._noFuture||parent._pass==="flows"?_cbTemplates.FUNCTION_INTERNAL:_cbTemplates.FUNCTION;node=template.generate(node,{$fn:parent.name,$name:"__$"+node._scope.name,$fname:_string(parent.name),$line:_number(originalLine(options,node._scope.line)),$index:_number(node._scope.cbIndex),$decls:_node(node,BLOCK,decls||[]),$body:node})}node.type=SCRIPT;case BLOCK:for(var i=0;i<node.children.length;i++){node.children[i]=_restructureIt(node,i)}return node}return _propagate(node,_scanIt)}function _extractTail(parent,i){return _node(parent,BLOCK,parent.children.splice(i+1,parent.children.length-i-1))}function _restructureIt(parent,i){var node=parent.children[i];if(node._pass==="cb")return _propagate(node,_scanIt);switch(node.type){case RETURN:_extractTail(parent,i);var template=node.value?_cbTemplates.RETURN:_cbTemplates.RETURN_UNDEFINED;node=template.generate(node,{$value:node.value});break;case THROW:_extractTail(parent,i);node=_cbTemplates.THROW.generate(node,{$exception:node.exception});break;case BREAK:if(node.target&&!node.target._async){break}_extractTail(parent,i);if(node.label){node=_cbTemplates.LABELLED_BREAK.generate(node,{$break:_safeName(options.precious,"__break__"+node.label)})}else{node=_cbTemplates.BREAK.generate(node,{})}break;case CONTINUE:if(node.target&&!node.target._async){break}_extractTail(parent,i);if(node.label){node=_cbTemplates.LABELLED_CONTINUE.generate(node,{$loop:_safeName(options.precious,"__loop__"+node.label),$more:_safeName(options.precious,"__more__"+node.label)})}else{node=_cbTemplates.CONTINUE.generate(node,{})}break;case TRY:var tail=_extractTail(parent,i);if(node.catchClauses[0]){node=_cbTemplates.CATCH.generate(node,{$name:"__$"+node._scope.name,$try:node.tryBlock,$catch:node.catchClauses[0].block,$ex:node.catchClauses[0].varName,$tail:tail})}else{node=_cbTemplates.FINALLY.generate(node,{$name:"__$"+node._scope.name,$try:node.tryBlock,$finally:node.finallyBlock,$tail:tail})}break;default:if(node._async){var tail=_extractTail(parent,i);switch(node.type){case IF:node=_cbTemplates.IF.generate(node,{$name:"__$"+node._scope.name,$condition:node.condition,$then:node.thenPart,$else:node.elsePart||_node(node,BLOCK,[]),$tail:tail});break;case SWITCH:node._pass="cb";node=_cbTemplates.SWITCH.generate(node,{$name:"__$"+node._scope.name,$statement:node,$tail:tail});break;case LABEL:var l=label;label=node.label;node=_cbTemplates.LABEL.generate(node,{$name:"__$"+node._scope.name,$statement:node.statement,$tail:tail});node=_scanIt(node,parent);label=l;return node;case FOR:var v=_identifier(_genId(node));var loop1=_cbTemplates.LOOP1.generate(node,{$v:v,$body:node.body});var update=node.update;var beenHere=update&&_identifier(_genId(node));var loop2=(update?_cbTemplates.LOOP2_UPDATE:_cbTemplates.LOOP2).generate(node,{$v:v,$condition:node.condition,$beenHere:beenHere,$update:_statementify(update),$loop1:loop1});node=(update?label?_cbTemplates.LABELLED_FOR_UPDATE:_cbTemplates.FOR_UPDATE:label?_cbTemplates.LABELLED_FOR:_cbTemplates.FOR).generate(node,{$name:"__$"+node._scope.name,$loop:_identifier(_safeName(options.precious,"__loop__"+label)),$break:_identifier(_safeName(options.precious,"__break__"+label)),$more:_identifier(_safeName(options.precious,"__more__"+label)),$beenHere:beenHere,$loop2:loop2,$tail:tail});break;case VAR:_assert(node.children.length==1);var ident=node.children[0];_assert(ident.type===IDENTIFIER);var call=ident.initializer;delete ident.initializer;_assert(call&&call.type===CALL);return _restructureCall(call,tail,ident.value);case SEMICOLON:var call=node.expression;_assert(call.type===CALL);return _restructureCall(call,tail);default:throw new Error("internal error: bad node type: "+_tag(node)+": "+pp(node))}}}return _scanIt(node,parent);function _restructureCall(node,tail,result){var args=node.children[1];function _cbIndex(args){return args.children.reduce(function(index,arg,i){if(arg.type==IDENTIFIER&&arg.value===options.callback||arg._isWrapper)return i;else return index},-1)}var i=_cbIndex(args);_assert(i>=0);var returnArray=args.children[i]._returnArray;if(args.children[i]._isWrapper){args=args.children[i].children[1];i=_cbIndex(args)}var identifier=node.children[0];while(identifier.type==DOT){identifier=identifier.children[1]}var bol=options.source.lastIndexOf("\n",identifier.start)+1;var col=identifier.start-bol;args.children[i]=(result?result.indexOf("__")===0?_cbTemplates.CALL_TMP:_cbTemplates.CALL_RESULT:_cbTemplates.CALL_VOID).generate(node,{$v:_genId(node),$frameName:_string(node._scope.name),$offset:_number(originalLine(options,identifier.lineno,col)-originalLine(options,node._scope.line)),$col:_number(originalCol(options,identifier.lineno,col)),$name:"__$"+node._scope.name,$returnArray:returnArray,$result:result,$tail:tail});node=_propagate(node,_scanIt);var stmt=_node(node,RETURN,[]);stmt.value=node;stmt._pass="cb";return stmt}}return _propagate(node,_scanIt)}function _checkUsed(val,used){if(typeof val==="string"&&val.substring(0,2)==="__")used[val]=true}var _optims={function__0$fn:new Template("simplify","return function ___(__0) { $fn(); }",true).root,function$return:new Template("simplify","return function $fn1() { return $fn2(); }",true).root,function__0$arg1return_null$arg2:new Template("simplify","return function ___(__0, $arg1) { return _(null, $arg2); }",true).root,__cb__:new Template("simplify","return __cb(_, $frameVar, $line, $col, _)",true).root,__cbt__:new Template("simplify","return __cb(_, $frameVar, $line, $col, _, true)",true).root,function$fn:new Template("simplify","return function $fn1() { $fn2(); }",true).root,closure:new Template("simplify","return (function ___closure(_){ $body; })(__cb(_,$frameVar,$line,$col,function $fnName(){_();},true))",true).root,safeParam:new Template("simplify","return (function $fnName($param){ $body; })(function $fnName(){_();})",true).root};function _simplify(node,options,used){if(node._simplified)return node;node._simplified=true;_propagate(node,function(child){return _simplify(child,options,used)});_checkUsed(node.value,used);function _match(prop,v1,v2,result){var ignored=["parenthesized","lineno","start","end","tokenizer","hasReturnWithValue"];if(prop.indexOf("_")==0||ignored.indexOf(prop)>=0)return true;if(v1==v2)return true;if(v1==null||v2==null){if(prop=="children"&&v1&&v1.length===0)return true;return false}if(Array.isArray(v1)){if(v1.length!=v2.length)return false;for(var i=0;i<v1.length;i++){if(!_match(prop,v1[i],v2[i],result))return false}return true}if(v1.type===IDENTIFIER&&v1.value[0]==="$"&&v2.type===NUMBER){result[v1.value]=v2.value;return true}if(typeof v1=="string"&&v1[0]=="$"&&typeof v2=="string"){result[v1]=v2;return true}if(v1.type){var exp;if(v1.type==SCRIPT&&v1.children[0]&&(exp=v1.children[0].expression)&&typeof exp.value=="string"&&exp.value[0]=="$"){result[exp.value]=v2;return true}if(v1.type!=v2.type)return false;if(v1.type==IDENTIFIER&&v1.value=="$"){result[v1.value]=v2.value;return true}for(var prop in v1){if(v1.hasOwnProperty(prop)&&prop.indexOf("Decls")<0&&prop!="target"){if(!_match(prop,v1[prop],v2[prop],result))return false}}return true}return false}var result={};if(_match("",_optims.function__0$fn,node,result))return _identifier(result.$fn);if(_match("",_optims.function$return,node,result)&&(result.$fn1==="___"||result.$fn1.indexOf("__$")===0)&&result.$fn2==="__break")return _identifier(result.$fn2);if(_match("",_optims.function__0$arg1return_null$arg2,node,result)&&result.$arg1==result.$arg2)return _identifier("_");if(options.optimize&&_match("",_optims.__cb__,node,result))return _identifier("_");if(options.optimize&&_match("",_optims.__cbt__,node,result))return _identifier("_");if(_match("",_optims.function$fn,node,result)&&(result.$fn1==="___"||result.$fn1.indexOf("__$")===0)&&(result.$fn2==="__then"||result.$fn2==="__loop"))return _identifier(result.$fn2);if(_match("",_optims.closure,node,result))node.children[1]=_identifier("_");if(_match("",_optims.safeParam,node,result)&&(result.$param==="__then"||result.$param==="__break"))node.children[1]=_identifier("_");_flatten(node);return node}function _extend(obj,other){for(var i in other){obj[i]=other[i]}return obj}function _cl(obj){return _extend({},obj)}exports.transform=function(source,options){try{source=source.replace(/\r\n/g,"\n");options=options?_extend({},options):{};var sourceOptions=/streamline\.options\s*=\s*(\{.*\})/.exec(source);if(sourceOptions){_extend(options,JSON.parse(sourceOptions[1]))}options.source=source;options.callback=options.callback||"_";options.lines=options.lines||"preserve";options.precious={};var node=parse(source+"\n",options.sourceName);var strict=node.children[0]&&node.children[0].expression&&node.children[0].expression.value=="use strict";strict&&node.children.splice(0,1);_markSource(node,options);node=_canonTopLevelScript(node,options);node=_canonScopes(node,options);if(!options.needsTransform)return source;node=_canonFlows(node,options);node=_disassemble(node,options);node=_callbackify(node,options);var used={};node=_simplify(node,options,used);var result=format(node,options.lines);if(!options.noHelpers){var s=exports.helpersSource(options,used,strict);if(options.lines=="sourcemap"){result.prepend(s)}else{result=s+result}}return result}catch(err){var message="error streamlining "+(options.sourceName||"source")+": "+err.message;if(err.source&&err.cursor){var line=1;for(var i=0;i<err.cursor;i++){if(err.source[i]==="\n")line+=1}message+=" on line "+line}else if(err.stack){message+="\nSTACK:\n"+err.stack}throw new Error(message)}};exports.transform.version=exports.version;function _trim(fn){return fn.toString().replace(/\s+/g," ")}function include(mod,modules){var source=modules+"['"+mod+"']=(mod={exports:{}});";source+="(function(module, exports){";var req=srequire;source+=req("fs").readFileSync(__dirname+"/../"+mod+".js","utf8").replace(/(\/\/[^"\n]*\n|\/\*[\s\S]*?\*\/|\n)[ \t]*/g,"");source+="})(mod, mod.exports);";return source}function requireRuntime(options){if(!options.standalone)return"srequire('streamline/lib/callbacks/runtime').runtime(__filename, "+!!options.oldStyleFutures+")";var modules=_safeName(options.precious,"__modules");var s="(function(){var "+modules+"={},mod;";s+="function srequire(p){var m="+modules+"[p.substring(15)]; return m && m.exports};";s+=include("globals",modules);s+=include("util/future",modules);s+=include("callbacks/runtime",modules);if(["funnel","forEach_","map_","filter_","every_","some_","reduce_","reduceRight_","sort_","apply_"].some(function(name){return options.precious[name]}))s+=include("callbacks/builtins",modules);s+="return "+modules+"['callbacks/runtime'].exports.runtime('"+options.sourceName+"', "+!!options.oldStyleFutures+");";s+="})()";return s}exports.helpersSource=function(options,used,strict){var srcName=""+options.sourceName;var i=srcName.indexOf("node_modules/");if(i==-1&&typeof process==="object"&&typeof process.cwd==="function")i=process.cwd().length;srcName=i>=0?srcName.substring(i+13):srcName;var sep=options.lines=="preserve"?" ":"\n";strict=strict?'"use strict";'+sep:"";var s=sep+strict;var keys=["__g","__func","__cb","__future","__propagate","__trap","__catch","__tryCatch","__forIn","__apply","__construct","__setEF"];var __rt=_safeName(options.precious,"__rt");s+="var "+__rt+"="+requireRuntime(options);keys.forEach(function(key){var k=_safeName(options.precious,key);if(used[k])s+=","+k+"="+__rt+"."+key});s+=";"+sep;return s}})(typeof exports!=="undefined"?exports:window.Streamline=window.Streamline||{});(function(exports){exports.future=function(fn,args,i){var err,result,done,q=[],self=this;args=Array.prototype.slice.call(args);args[i]=function(e,r){err=e,result=r,done=true;q&&q.forEach(function(f){f.call(self,e,r)});q=null};fn.apply(this,args);return function F(cb){if(typeof cb!=="function"){if(cb!==false&&!srequire("streamline/lib/globals").oldStyleFutures)throw new Error("no callback given (argument #0). If you're a Streamline user, more info: https://github.com/Sage/streamlinejs/blob/master/FAQ.md#no-callback-given-error");return F}if(done)cb.call(self,err,result);else q.push(cb)}};exports.streamlinify=function(fn,idx){return function(){if(!arguments[idx])return exports.future.call(this,fn,arguments,idx);else return fn.apply(this,arguments)}}})(typeof exports!=="undefined"?exports:Streamline.future=Streamline.future||{});(function(exports){var __g=srequire("streamline/lib/globals");__g.runtime="callbacks";var __fut=srequire("streamline/lib/util/future");__g.context=__g.context||{};__g.depth=__g.depth||0;__g.trampoline=function(){var q=[];return{queue:function(fn){q.push(fn)},flush:function(){__g.depth++;try{var fn;while(fn=q.shift())fn()}finally{__g.depth--}}}}();exports.runtime=function(filename,oldStyleFutures){__g.oldStyleFutures=oldStyleFutures;function __func(_,__this,__arguments,fn,index,frame,body){if(typeof _!=="function"){if(_!==false&&!__g.oldStyleFutures)throw new Error("no callback given (argument #"+index+"). If you're a Streamline user, more info: https://github.com/Sage/streamlinejs/blob/master/FAQ.md#no-callback-given-error");return __fut.future.call(__this,fn,__arguments,index)}frame.file=filename;frame.prev=__g.frame;__g.frame=frame;__g.depth===0&&__g.emitter&&__g.emitter.emit("resume");__g.depth++;try{frame.active=true;body()}catch(e){__propagate(_,e)}finally{frame.active=false;__g.frame=frame.prev;if(--__g.depth===0&&__g.trampoline)__g.trampoline.flush();__g.depth===0&&__g.emitter&&__g.emitter.emit("yield")}}return{__g:__g,__func:__func,__cb:__cb,__future:__fut.future,__propagate:__propagate,__trap:__trap,__tryCatch:__tryCatch,__catch:__catch,__forIn:__forIn,__apply:__apply,__construct:__construct,__setEF:__setEF,streamlinify:__fut.streamlinify}};function __cb(_,frame,offset,col,fn,trampo,returnArray){frame.offset=offset;frame.col=col;var ctx=__g.context;return function ___(err,result){if(returnArray)result=Array.prototype.slice.call(arguments,1);returnArray=false;var oldFrame=__g.frame;__g.frame=frame;__g.context=ctx;__g.depth===0&&__g.emitter&&__g.emitter.emit("resume");__g.depth++;try{if(trampo&&frame.active&&__g.trampoline){__g.trampoline.queue(function(){return ___(err,result)})}else{___.dispatched=true;if(err){__setEF(err,frame);return _(err);
  }frame.active=true;return fn(null,result)}}catch(ex){return __propagate(_,ex)}finally{frame.active=false;__g.frame=oldFrame;if(--__g.depth===0&&__g.trampoline)__g.trampoline.flush();__g.depth===0&&__g.emitter&&__g.emitter.emit("yield")}}}function __propagate(_,err){try{_(err)}catch(ex){__trap(ex)}}function __trap(err){if(err){if(__g.context&&__g.context.errorHandler)__g.context.errorHandler(err);else process.nextTick(function(){throw err})}}function __tryCatch(_,fn){try{fn()}catch(e){try{_(e)}catch(ex){__trap(ex)}}}function __catch(fn){var frame=__g.frame,context=__g.context;__g.trampoline.queue(function(){var oldFrame=__g.frame,oldContext=__g.context;__g.frame=frame;__g.context=context;try{fn()}finally{__g.frame=oldFrame;__g.context=oldContext}})}function __forIn(object){var array=[];for(var obj in object){array.push(obj)}return array}function __apply(cb,fn,thisObj,args,index){if(cb==null)return __fut.future(__apply,arguments,0);args=Array.prototype.slice.call(args,0);args[index!=null?index:args.length]=cb;return fn.apply(thisObj,args)}function __construct(constructor,i){var key="__async"+i,f;return constructor[key]||(constructor[key]=function(){var args=arguments;function F(){var self=this;var cb=args[i];args[i]=function(e,r){cb(e,self)};return constructor.apply(self,args)}F.prototype=constructor.prototype;return new F})}function __setEF(e,f){function formatStack(e,raw){var ff=typeof navigator==="object"&&navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(ff)raw="Error: "+e.message+"\n"+raw;var s=raw,f,skip;if(s){var lines=s.split("\n");s=lines[0]+"\n    <<< async stack >>>\n"+lines.slice(1).map(function(l){var ffOffset=typeof navigator==="object"&&typeof srequire==="function"&&srequire.async?11:0;var m=/([^@]*)\@(.*?)\:(\d+)(?:\:(\d+))?$/.exec(l);l=m?"    at "+m[1]+" ("+m[2]+":"+(parseInt(m[3])-ffOffset)+":"+(m[4]||"0")+")":l;var i=l.indexOf("__$");if(i>=0&&!skip){skip=true;return l.substring(0,i)+l.substring(i+3)}return skip?"":l}).filter(function(l){return l}).join("\n");for(var f=e.__frame;f;f=f.prev){if(f.offset>=0)s+="\n    at "+f.name+" ("+f.file+":"+(f.line+f.offset)+":"+(f.col+1)+")"}}var nl=raw.indexOf("\n");s+="\n    <<< raw stack >>>"+(nl>=0?raw.substring(nl):raw);return s}e.__frame=e.__frame||f;if(exports.stackTraceEnabled&&e.__lookupGetter__&&e.__lookupGetter__("rawStack")==null){var getter=e.__lookupGetter__("stack");if(!getter){var raw=e.stack||"raw stack unavailable";getter=function(){return raw}}e.__defineGetter__("rawStack",getter);e.__defineGetter__("stack",function(){return formatStack(e,getter())})}}exports.stackTraceEnabled=true})(typeof exports!=="undefined"?exports:Streamline.runtime=Streamline.runtime||{});srequire&&srequire("streamline/lib/callbacks/builtins");var __rt=srequire("streamline/lib/callbacks/runtime").runtime(__filename,false),__func=__rt.__func,__cb=__rt.__cb;(function(exports){"use strict";var VERSION=3;var future=function(fn,args,i){var err,result,done,q=[],self=this;args=Array.prototype.slice.call(args);args[i]=function(e,r){err=e,result=r,done=true;q&&q.forEach(function(f){f.call(self,e,r)});q=null};fn.apply(this,args);return function F(cb){if(!cb){return F}if(done){cb.call(self,err,result)}else{q.push(cb)}}};exports.funnel=function(max){max=max==null?-1:max;if(max===0){max=funnel.defaultSize}if(typeof max!=="number"){throw new Error("bad max number: "+max)}var queue=[],active=0,closed=false;var funCb=function(callback,fn){if(callback==null){return future(funCb,arguments,0)}if(max<0||max==Infinity){return fn(callback)}queue.push({fn:fn,cb:callback});function _doOne(){var current=queue.splice(0,1)[0];if(!current.cb){return current.fn()}active++;current.fn(function(err,result){active--;if(!closed){current.cb(err,result);while(active<max&&queue.length>0){_doOne()}}})}while(active<max&&queue.length>0){_doOne()}};var fun=__rt.streamlinify(funCb,0);fun.close=function(){queue=[],closed=true};return fun};var funnel=exports.funnel;funnel.defaultSize=4;function _parallel(options){if(typeof options==="number"){return options}if(typeof options.parallel==="number"){return options.parallel}return options.parallel?-1:1}if(Array.prototype.forEach_&&Array.prototype.forEach_.version_>=VERSION){return}try{Object.defineProperty({},"x",{})}catch(e){return}var has=Object.prototype.hasOwnProperty;delete Array.prototype.forEach_;Object.defineProperty(Array.prototype,"forEach_",{configurable:true,writable:true,enumerable:false,value:function value__1(_,options,fn,thisObj){var par,len,i,__this=this;var __frame={name:"value__1",line:124};return __func(_,this,arguments,value__1,0,__frame,function __$value__1(){if(typeof options==="function"){thisObj=fn,fn=options,options=1}par=_parallel(options);thisObj=thisObj!==undefined?thisObj:__this;len=__this.length;return function __$value__1(__then){if(par===1||len<=1){i=0;var __2=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__1(){__more=false;if(__2){i++}else{__2=true}var __1=i<len;if(__1){return function __$value__1(__then){if(has.call(__this,i)){return fn.call(thisObj,__cb(_,__frame,7,31,__then,true),__this[i],i)}else{__then()}}(function __$value__1(){while(__more){__loop()}__more=true})}else{__break()}});do{__loop()}while(__more);__more=true}(__then)}else{return __this.map_(__cb(_,__frame,10,9,__then,true),par,fn,thisObj)}}(function __$value__1(){return _(null,__this)})})}});Array.prototype.forEach_.version_=VERSION;delete Array.prototype.map_;Object.defineProperty(Array.prototype,"map_",{configurable:true,writable:true,enumerable:false,value:function value__2(_,options,fn,thisObj){var par,len,result,i,fun,__this=this;var __frame={name:"value__2",line:147};return __func(_,this,arguments,value__2,0,__frame,function __$value__2(){if(typeof options==="function"){thisObj=fn,fn=options,options=1}par=_parallel(options);thisObj=thisObj!==undefined?thisObj:__this;len=__this.length;return function __$value__2(__then){if(par===1||len<=1){result=new Array(len);i=0;var __4=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__2(){__more=false;if(__4){i++}else{__4=true}var __3=i<len;if(__3){return function __$value__2(__then){if(has.call(__this,i)){return fn.call(thisObj,__cb(_,__frame,9,43,function ___(__0,__1){result[i]=__1;__then()},true),__this[i],i)}else{__then()}}(function __$value__2(){while(__more){__loop()}__more=true})}else{__break()}});do{__loop()}while(__more);__more=true}(__then)}else{fun=funnel(par);result=__this.map(function(elt,i){return fun(false,function __1(_){var __frame={name:"__1",line:161};return __func(_,this,arguments,__1,0,__frame,function __$__1(){return fn.call(thisObj,__cb(_,__frame,1,16,_,true),elt,i)})})});i=0;var __7=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__2(){__more=false;if(__7){i++}else{__7=true}var __6=i<len;if(__6){return function __$value__2(__then){if(has.call(__this,i)){return result[i](__cb(_,__frame,19,40,function ___(__0,__2){result[i]=__2;__then()},true))}else{__then()}}(function __$value__2(){while(__more){__loop()}__more=true})}else{__break()}});do{__loop()}while(__more);__more=true}(__then)}}(function __$value__2(){return _(null,result)})})}});delete Array.prototype.filter_;Object.defineProperty(Array.prototype,"filter_",{configurable:true,writable:true,enumerable:false,value:function value__3(_,options,fn,thisObj){var par,result,len,i,elt,__this=this;var __frame={name:"value__3",line:179};return __func(_,this,arguments,value__3,0,__frame,function __$value__3(){if(typeof options==="function"){thisObj=fn,fn=options,options=1}par=_parallel(options);thisObj=thisObj!==undefined?thisObj:__this;result=[];len=__this.length;return function __$value__3(__then){if(par===1||len<=1){i=0;var __4=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__3(){__more=false;if(__4){i++}else{__4=true}var __3=i<len;if(__3){return function __$value__3(__then){if(has.call(__this,i)){elt=__this[i];return fn.call(thisObj,__cb(_,__frame,10,13,function ___(__0,__2){return function __$value__3(__then){if(__2){result.push(elt);__then()}else{__then()}}(__then)},true),elt)}else{__then()}}(function __$value__3(){while(__more){__loop()}__more=true})}else{__break()}});do{__loop()}while(__more);__more=true}(__then)}else{return __this.map_(__cb(_,__frame,14,9,__then,true),par,function __1(_,elt){var __frame={name:"__1",line:193};return __func(_,this,arguments,__1,0,__frame,function __$__1(){return fn.call(thisObj,__cb(_,__frame,1,12,function ___(__0,__1){return function __$__1(__then){if(__1){result.push(elt);__then()}else{__then()}}(_)},true),elt)})},thisObj)}}(function __$value__3(){return _(null,result)})})}});delete Array.prototype.every_;Object.defineProperty(Array.prototype,"every_",{configurable:true,writable:true,enumerable:false,value:function value__4(_,options,fn,thisObj){var par,len,i,fun,futures,__this=this;var __frame={name:"value__4",line:207};return __func(_,this,arguments,value__4,0,__frame,function __$value__4(){if(typeof options==="function"){thisObj=fn,fn=options,options=1}par=_parallel(options);thisObj=thisObj!==undefined?thisObj:__this;len=__this.length;return function __$value__4(__then){if(par===1||len<=1){i=0;var __6=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__4(){__more=false;if(__6){i++}else{__6=true}var __5=i<len;if(__5){return function __$value__4(_){var __1=has.call(__this,i);if(!__1){return _(null,__1)}return fn.call(thisObj,__cb(_,__frame,8,34,function ___(__0,__3){var __2=!__3;return _(null,__2)},true),__this[i])}(__cb(_,__frame,-206,17,function ___(__0,__3){return function __$value__4(__then){if(__3){return _(null,false)}else{__then()}}(function __$value__4(){while(__more){__loop()}__more=true})},true))}else{__break()}});do{__loop()}while(__more);__more=true}(__then)}else{fun=funnel(par);futures=__this.map(function(elt){return fun(false,function __1(_){var __frame={name:"__1",line:220};return __func(_,this,arguments,__1,0,__frame,function __$__1(){return fn.call(thisObj,__cb(_,__frame,1,16,_,true),elt)})})});i=0;var __9=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__4(){__more=false;if(__9){i++}else{__9=true}var __8=i<len;if(__8){return function __$value__4(_){var __2=has.call(__this,i);if(!__2){return _(null,__2)}return futures[i](__cb(_,__frame,18,31,function ___(__0,__4){var __3=!__4;return _(null,__3)},true))}(__cb(_,__frame,-206,17,function ___(__0,__4){return function __$value__4(__then){if(__4){fun.close();return _(null,false)}else{__then()}}(function __$value__4(){while(__more){__loop()}__more=true})},true))}else{__break()}});do{__loop()}while(__more);__more=true}(__then)}}(function __$value__4(){return _(null,true)})})}});delete Array.prototype.some_;Object.defineProperty(Array.prototype,"some_",{configurable:true,writable:true,enumerable:false,value:function value__5(_,options,fn,thisObj){var par,len,i,fun,futures,__this=this;var __frame={name:"value__5",line:241};return __func(_,this,arguments,value__5,0,__frame,function __$value__5(){if(typeof options==="function"){thisObj=fn,fn=options,options=1}par=_parallel(options);thisObj=thisObj!==undefined?thisObj:__this;len=__this.length;return function __$value__5(__then){if(par===1||len<=1){i=0;var __6=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__5(){__more=false;if(__6){i++}else{__6=true}var __5=i<len;if(__5){return function __$value__5(_){var __1=has.call(__this,i);if(!__1){return _(null,__1)}return fn.call(thisObj,__cb(_,__frame,7,33,_,true),__this[i])}(__cb(_,__frame,-240,17,function ___(__0,__3){return function __$value__5(__then){if(__3){return _(null,true)}else{__then()}}(function __$value__5(){while(__more){__loop()}__more=true})},true))}else{__break()}});do{__loop()}while(__more);__more=true}(__then)}else{fun=funnel(par);futures=__this.map(function(elt){return fun(false,function __1(_){var __frame={name:"__1",line:253};return __func(_,this,arguments,__1,0,__frame,function __$__1(){return fn.call(thisObj,__cb(_,__frame,1,16,_,true),elt)})})});i=0;var __9=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__5(){__more=false;if(__9){i++}else{__9=true}var __8=i<len;if(__8){return function __$value__5(_){var __2=has.call(__this,i);if(!__2){return _(null,__2)}return futures[i](__cb(_,__frame,17,30,_,true))}(__cb(_,__frame,-240,17,function ___(__0,__4){return function __$value__5(__then){if(__4){fun.close();return _(null,true)}else{__then()}}(function __$value__5(){while(__more){__loop()}__more=true})},true))}else{__break()}});do{__loop()}while(__more);__more=true}(__then)}}(function __$value__5(){return _(null,false)})})}});delete Array.prototype.reduce_;Object.defineProperty(Array.prototype,"reduce_",{configurable:true,writable:true,enumerable:false,value:function value__6(_,fn,v,thisObj){var len,i,__this=this;var __frame={name:"value__6",line:274};return __func(_,this,arguments,value__6,0,__frame,function __$value__6(){thisObj=thisObj!==undefined?thisObj:__this;len=__this.length;i=0;var __3=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__6(){__more=false;if(__3){i++}else{__3=true}var __2=i<len;if(__2){return function __$value__6(__then){if(has.call(__this,i)){return fn.call(thisObj,__cb(_,__frame,4,34,function ___(__0,__1){v=__1;__then()},true),v,__this[i],i,__this)}else{__then()}}(function __$value__6(){while(__more){__loop()}__more=true})}else{__break()}});do{__loop()}while(__more);__more=true}(function __$value__6(){return _(null,v)})})}});delete Array.prototype.reduceRight_;Object.defineProperty(Array.prototype,"reduceRight_",{configurable:true,writable:true,enumerable:false,value:function value__7(_,fn,v,thisObj){var len,i,__this=this;var __frame={name:"value__7",line:290};return __func(_,this,arguments,value__7,0,__frame,function __$value__7(){thisObj=thisObj!==undefined?thisObj:__this;len=__this.length;i=len-1;var __3=false;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$value__7(){__more=false;if(__3){i--}else{__3=true}var __2=i>=0;if(__2){return function __$value__7(__then){if(has.call(__this,i)){return fn.call(thisObj,__cb(_,__frame,4,34,function ___(__0,__1){v=__1;__then()},true),v,__this[i],i,__this)}else{__then()}}(function __$value__7(){while(__more){__loop()}__more=true})}else{__break()}});do{__loop()}while(__more);__more=true}(function __$value__7(){return _(null,v)})})}});delete Array.prototype.sort_;Object.defineProperty(Array.prototype,"sort_",{configurable:true,writable:true,enumerable:false,value:function value__8(_,compare,beg,end){var array,__this=this;function _qsort(_,beg,end){var tmp,mid,o,nbeg,nend;var __frame={name:"_qsort",line:313};return __func(_,this,arguments,_qsort,0,__frame,function __$_qsort(){if(beg>=end){return _(null)}return function __$_qsort(__then){if(end==beg+1){return compare(__cb(_,__frame,4,9,function ___(__0,__4){var __3=__4>0;return function __$_qsort(__then){if(__3){tmp=array[beg];array[beg]=array[end];array[end]=tmp;__then()}else{__then()}}(function __$_qsort(){return _(null)})},true),array[beg],array[end])}else{__then()}}(function __$_qsort(){mid=Math.floor((beg+end)/2);o=array[mid];nbeg=beg;nend=end;return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$_qsort(){__more=false;var __6=nbeg<=nend;if(__6){return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$_qsort(){__more=false;return function __$_qsort(_){return function __$_qsort(_){var __1=nbeg<end;if(!__1){return _(null,__1)}return compare(__cb(_,__frame,18,26,function ___(__0,__3){var __2=__3<0;return _(null,__2)},true),array[nbeg],o)}(__cb(_,__frame,-312,17,_,true))}(__cb(_,__frame,-312,17,function ___(__0,__7){if(__7){nbeg++;while(__more){__loop()}__more=true}else{__break()}},true))});do{__loop()}while(__more);__more=true}(function __$_qsort(){return function ___(__break){var __more;var __loop=__cb(_,__frame,0,0,function __$_qsort(){__more=false;return function __$_qsort(_){return function __$_qsort(_){var __2=beg<nend;if(!__2){return _(null,__2)}return compare(__cb(_,__frame,19,26,function ___(__0,__4){var __3=__4<0;return _(null,__3)},true),o,array[nend])}(__cb(_,__frame,-312,17,_,true))}(__cb(_,__frame,-312,17,function ___(__0,__9){if(__9){nend--;while(__more){__loop()}__more=true}else{__break()}},true))});do{__loop()}while(__more);__more=true}(function __$_qsort(){if(nbeg<=nend){tmp=array[nbeg];array[nbeg]=array[nend];array[nend]=tmp;nbeg++;nend--}while(__more){__loop()}__more=true})})}else{__break()}});do{__loop()}while(__more);__more=true}(function __$_qsort(){return function __$_qsort(__then){if(nbeg<end){return _qsort(__cb(_,__frame,30,20,__then,true),nbeg,end)}else{__then()}}(function __$_qsort(){return function __$_qsort(__then){if(beg<nend){return _qsort(__cb(_,__frame,31,20,__then,true),beg,nend)}else{__then()}}(_)})})})})}var __frame={name:"value__8",line:308};return __func(_,this,arguments,value__8,0,__frame,function __$value__8(){array=__this;beg=beg||0;end=end==null?array.length-1:end;return _qsort(__cb(_,__frame,38,3,function __$value__8(){return _(null,array)},true),beg,end)})}});delete Function.prototype.apply_;Object.defineProperty(Function.prototype,"apply_",{configurable:true,writable:true,enumerable:false,value:function(callback,thisObj,args,index){args=Array.prototype.slice.call(args,0);args.splice(index!=null&&index>=0?index:args.length,0,callback);return this.apply(thisObj,args)}})})(typeof exports!=="undefined"?exports:Streamline.builtins=Streamline.builtins||{});
  /*This is a combined, compressed file.  Look at https://github.com/BruceSherwood/glowscript for source code and copyright information.*/
  ;(function(){})();