<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">// 1.25.137 export 2023-05-09T18:32:01 023e5d57131379b16db054bf32719cdb74d3fa04 
/*
 * Copyright 2016 GameSalad, Inc.
 * http://gamesalad.com/
 *
 * Terms of Use: http://gamesalad.com/terms
 * Privacy Policy: http://gamesalad.com/privacy
 */

/* 
 * Includes Web Font Loader (https://github.com/typekit/webfontloader).
 * Web Font Loader Copyrights as per Apache License below.
 */

/*
 * Copyright 2016 Small Batch, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
/* Web Font Loader v1.6.16 - (c) Adobe Systems, Google. License: Apache 2.0 */






















































'use strict';
var polyfillCanvas=!window.OffscreenCanvas;if(window.OffscreenCanvas){var testCanvas=new window.OffscreenCanvas(10,10);if(testCanvas.getContext("webgl")==null){polyfillCanvas=true}}if(polyfillCanvas){window.OffscreenCanvas=function OffscreenCanvas(width,height){this.canvas=document.createElement("canvas");this.canvas.width=width;this.canvas.height=height;this.canvas.convertToBlob=function(){return new Promise(function(resolve){this.canvas.toBlob(resolve)})};return this.canvas}}(function(global,factory){typeof exports==="object"&amp;&amp;typeof module!=="undefined"?factory(exports):typeof define==="function"&amp;&amp;define.amd?define(["exports"],factory):(global=global||self,factory(global.opentype={}))})(this,function(exports){"use strict";if(!String.prototype.codePointAt){(function(){var defineProperty=function(){try{var object={};var $defineProperty=Object.defineProperty;var result=$defineProperty(object,object,object)&amp;&amp;$defineProperty}catch(error){}return result}();var codePointAt=function(position){if(this==null){throw TypeError()}var string=String(this);var size=string.length;var index=position?Number(position):0;if(index!=index){index=0}if(index&lt;0||index&gt;=size){return undefined}var first=string.charCodeAt(index);var second;if(first&gt;=55296&amp;&amp;first&lt;=56319&amp;&amp;size&gt;index+1){second=string.charCodeAt(index+1);if(second&gt;=56320&amp;&amp;second&lt;=57343){return(first-55296)*1024+second-56320+65536}}return first};if(defineProperty){defineProperty(String.prototype,"codePointAt",{value:codePointAt,configurable:true,writable:true})}else{String.prototype.codePointAt=codePointAt}})()}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);function tinf_build_bits_base(bits,base,delta,first){var i,sum;for(i=0;i&lt;delta;++i){bits[i]=0}for(i=0;i&lt;30-delta;++i){bits[i+delta]=i/delta|0}for(sum=first,i=0;i&lt;30;++i){base[i]=sum;sum+=1&lt;&lt;bits[i]}}function tinf_build_fixed_trees(lt,dt){var i;for(i=0;i&lt;7;++i){lt.table[i]=0}lt.table[7]=24;lt.table[8]=152;lt.table[9]=112;for(i=0;i&lt;24;++i){lt.trans[i]=256+i}for(i=0;i&lt;144;++i){lt.trans[24+i]=i}for(i=0;i&lt;8;++i){lt.trans[24+144+i]=280+i}for(i=0;i&lt;112;++i){lt.trans[24+144+8+i]=144+i}for(i=0;i&lt;5;++i){dt.table[i]=0}dt.table[5]=32;for(i=0;i&lt;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&lt;16;++i){t.table[i]=0}for(i=0;i&lt;num;++i){t.table[lengths[off+i]]++}t.table[0]=0;for(sum=0,i=0;i&lt;16;++i){offs[i]=sum;sum+=t.table[i]}for(i=0;i&lt;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&amp;1;d.tag&gt;&gt;&gt;=1;return bit}function tinf_read_bits(d,num,base){if(!num){return base}while(d.bitcount&lt;24){d.tag|=d.source[d.sourceIndex++]&lt;&lt;d.bitcount;d.bitcount+=8}var val=d.tag&amp;65535&gt;&gt;&gt;16-num;d.tag&gt;&gt;&gt;=num;d.bitcount-=num;return val+base}function tinf_decode_symbol(d,t){while(d.bitcount&lt;24){d.tag|=d.source[d.sourceIndex++]&lt;&lt;d.bitcount;d.bitcount+=8}var sum=0,cur=0,len=0;var tag=d.tag;do{cur=2*cur+(tag&amp;1);tag&gt;&gt;&gt;=1;++len;sum+=t.table[len];cur-=t.table[len]}while(cur&gt;=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&lt;19;++i){lengths[i]=0}for(i=0;i&lt;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&lt;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&lt;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&lt;offs+length;++i){d.dest[d.destLen++]=d.dest[i]}}}}function tinf_inflate_uncompressed_block(d){var length,invlength;var i;while(d.bitcount&gt;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&amp;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&lt;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;var tinyInflate=tinf_uncompress;function derive(v0,v1,v2,v3,t){return Math.pow(1-t,3)*v0+3*Math.pow(1-t,2)*t*v1+3*(1-t)*Math.pow(t,2)*v2+Math.pow(t,3)*v3}function BoundingBox(){this.x1=Number.NaN;this.y1=Number.NaN;this.x2=Number.NaN;this.y2=Number.NaN}BoundingBox.prototype.isEmpty=function(){return isNaN(this.x1)||isNaN(this.y1)||isNaN(this.x2)||isNaN(this.y2)};BoundingBox.prototype.addPoint=function(x,y){if(typeof x==="number"){if(isNaN(this.x1)||isNaN(this.x2)){this.x1=x;this.x2=x}if(x&lt;this.x1){this.x1=x}if(x&gt;this.x2){this.x2=x}}if(typeof y==="number"){if(isNaN(this.y1)||isNaN(this.y2)){this.y1=y;this.y2=y}if(y&lt;this.y1){this.y1=y}if(y&gt;this.y2){this.y2=y}}};BoundingBox.prototype.addX=function(x){this.addPoint(x,null)};BoundingBox.prototype.addY=function(y){this.addPoint(null,y)};BoundingBox.prototype.addBezier=function(x0,y0,x1,y1,x2,y2,x,y){var p0=[x0,y0];var p1=[x1,y1];var p2=[x2,y2];var p3=[x,y];this.addPoint(x0,y0);this.addPoint(x,y);for(var i=0;i&lt;=1;i++){var b=6*p0[i]-12*p1[i]+6*p2[i];var a=-3*p0[i]+9*p1[i]-9*p2[i]+3*p3[i];var c=3*p1[i]-3*p0[i];if(a===0){if(b===0){continue}var t=-c/b;if(0&lt;t&amp;&amp;t&lt;1){if(i===0){this.addX(derive(p0[i],p1[i],p2[i],p3[i],t))}if(i===1){this.addY(derive(p0[i],p1[i],p2[i],p3[i],t))}}continue}var b2ac=Math.pow(b,2)-4*c*a;if(b2ac&lt;0){continue}var t1=(-b+Math.sqrt(b2ac))/(2*a);if(0&lt;t1&amp;&amp;t1&lt;1){if(i===0){this.addX(derive(p0[i],p1[i],p2[i],p3[i],t1))}if(i===1){this.addY(derive(p0[i],p1[i],p2[i],p3[i],t1))}}var t2=(-b-Math.sqrt(b2ac))/(2*a);if(0&lt;t2&amp;&amp;t2&lt;1){if(i===0){this.addX(derive(p0[i],p1[i],p2[i],p3[i],t2))}if(i===1){this.addY(derive(p0[i],p1[i],p2[i],p3[i],t2))}}}};BoundingBox.prototype.addQuad=function(x0,y0,x1,y1,x,y){var cp1x=x0+2/3*(x1-x0);var cp1y=y0+2/3*(y1-y0);var cp2x=cp1x+1/3*(x-x0);var cp2y=cp1y+1/3*(y-y0);this.addBezier(x0,y0,cp1x,cp1y,cp2x,cp2y,x,y)};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}else if(pathOrCommands instanceof BoundingBox){var box=pathOrCommands;this.moveTo(box.x1,box.y1);this.lineTo(box.x2,box.y1);this.lineTo(box.x2,box.y2);this.lineTo(box.x1,box.y2);this.close();return}Array.prototype.push.apply(this.commands,pathOrCommands)};Path.prototype.getBoundingBox=function(){var box=new BoundingBox;var startX=0;var startY=0;var prevX=0;var prevY=0;for(var i=0;i&lt;this.commands.length;i++){var cmd=this.commands[i];switch(cmd.type){case"M":box.addPoint(cmd.x,cmd.y);startX=prevX=cmd.x;startY=prevY=cmd.y;break;case"L":box.addPoint(cmd.x,cmd.y);prevX=cmd.x;prevY=cmd.y;break;case"Q":box.addQuad(prevX,prevY,cmd.x1,cmd.y1,cmd.x,cmd.y);prevX=cmd.x;prevY=cmd.y;break;case"C":box.addBezier(prevX,prevY,cmd.x1,cmd.y1,cmd.x2,cmd.y2,cmd.x,cmd.y);prevX=cmd.x;prevY=cmd.y;break;case"Z":prevX=startX;prevY=startY;break;default:throw new Error("Unexpected path command "+cmd.type)}}if(box.isEmpty()){box.addPoint(0,0)}return box};Path.prototype.draw=function(ctx){ctx.beginPath();for(var i=0;i&lt;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 arguments$1=arguments;var s="";for(var i=0;i&lt;arguments.length;i+=1){var v=arguments$1[i];if(v&gt;=0&amp;&amp;i&gt;0){s+=" "}s+=floatToString(v)}return s}var d="";for(var i=0;i&lt;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='&lt;path d="';svg+=this.toPathData(decimalPlaces);svg+='"';if(this.fill&amp;&amp;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+="/&gt;";return svg};Path.prototype.toDOMElement=function(decimalPlaces){var temporaryPath=this.toPathData(decimalPlaces);var newPath=document.createElementNS("http://www.w3.org/2000/svg","path");newPath.setAttribute("d",temporaryPath);return newPath};function fail(message){throw new Error(message)}function argument(predicate,message){if(!predicate){fail(message)}}var check={fail:fail,argument:argument,assert:argument};var LIMIT16=32768;var LIMIT32=2147483648;var decode={};var encode={};var sizeOf={};function constant(v){return function(){return v}}encode.BYTE=function(v){check.argument(v&gt;=0&amp;&amp;v&lt;=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&lt;v.length;i+=1){b[i]=v.charCodeAt(i)}return b};sizeOf.CHARARRAY=function(v){return v.length};encode.USHORT=function(v){return[v&gt;&gt;8&amp;255,v&amp;255]};sizeOf.USHORT=constant(2);encode.SHORT=function(v){if(v&gt;=LIMIT16){v=-(2*LIMIT16-v)}return[v&gt;&gt;8&amp;255,v&amp;255]};sizeOf.SHORT=constant(2);encode.UINT24=function(v){return[v&gt;&gt;16&amp;255,v&gt;&gt;8&amp;255,v&amp;255]};sizeOf.UINT24=constant(3);encode.ULONG=function(v){return[v&gt;&gt;24&amp;255,v&gt;&gt;16&amp;255,v&gt;&gt;8&amp;255,v&amp;255]};sizeOf.ULONG=constant(4);encode.LONG=function(v){if(v&gt;=LIMIT32){v=-(2*LIMIT32-v)}return[v&gt;&gt;24&amp;255,v&gt;&gt;16&amp;255,v&gt;&gt;8&amp;255,v&amp;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(v){return[0,0,0,0,v&gt;&gt;24&amp;255,v&gt;&gt;16&amp;255,v&gt;&gt;8&amp;255,v&amp;255]};sizeOf.LONGDATETIME=constant(8);encode.TAG=function(v){check.argument(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&gt;=-107&amp;&amp;v&lt;=107){return[v+139]}else if(v&gt;=108&amp;&amp;v&lt;=1131){v=v-108;return[(v&gt;&gt;8)+247,v&amp;255]}else if(v&gt;=-1131&amp;&amp;v&lt;=-108){v=-v-108;return[(v&gt;&gt;8)+251,v&amp;255]}else if(v&gt;=-32768&amp;&amp;v&lt;=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&gt;&gt;8&amp;255,v&amp;255]};sizeOf.NUMBER16=constant(3);encode.NUMBER32=function(v){return[29,v&gt;&gt;24&amp;255,v&gt;&gt;16&amp;255,v&gt;&gt;8&amp;255,v&amp;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="";for(var i=0,ii=value.length;i&lt;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&amp;1?"f":"ff";var out=[30];for(var i$1=0,ii$1=nibbles.length;i$1&lt;ii$1;i$1+=2){out.push(parseInt(nibbles.substr(i$1,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;decode.UTF8=function(data,offset,numBytes){var codePoints=[];var numChars=numBytes;for(var j=0;j&lt;numChars;j++,offset+=1){codePoints[j]=data.getUint8(offset)}return String.fromCharCode.apply(null,codePoints)};decode.UTF16=function(data,offset,numBytes){var codePoints=[];var numChars=numBytes/2;for(var j=0;j&lt;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&lt;v.length;i+=1){var codepoint=v.charCodeAt(i);b[b.length]=codepoint&gt;&gt;8&amp;255;b[b.length]=codepoint&amp;255}return b};sizeOf.UTF16=function(v){return v.length*2};var eightBitMacEncodings={"x-mac-croatian":"Ã„Ã…Ã‡Ã‰Ã‘Ã–ÃœÃ¡Ã&nbsp;Ã¢Ã¤Ã£Ã¥Ã§Ã©Ã¨ÃªÃ«Ã­Ã¬Ã®Ã¯Ã±Ã³Ã²Ã´Ã¶ÃµÃºÃ¹Ã»Ã¼â€&nbsp;Â°Â¢Â£Â§â€¢Â¶ÃŸÂ®Å&nbsp;â„¢Â´Â¨â‰&nbsp;Å½Ã˜âˆžÂ±â‰¤â‰¥âˆ†Âµâˆ‚âˆ‘âˆÅ¡âˆ«ÂªÂºÎ©Å¾Ã¸"+"Â¿Â¡Â¬âˆšÆ’â‰ˆÄ†Â«ÄŒâ€¦ Ã€ÃƒÃ•Å’Å“Äâ€”â€œâ€â€˜â€™Ã·â—Šï£¿Â©â„â‚¬â€¹â€ºÃ†Â»â€“Â·â€šâ€žâ€°Ã‚Ä‡ÃÄÃˆÃÃŽÃÃŒÃ“Ã”Ä‘Ã’ÃšÃ›Ã™Ä±Ë†ËœÂ¯Ï€Ã‹ËšÂ¸ÃŠÃ¦Ë‡","x-mac-cyrillic":"ÐÐ‘Ð’Ð“Ð”Ð•Ð–Ð—Ð˜Ð™ÐšÐ›ÐœÐÐžÐŸÐ&nbsp;Ð¡Ð¢Ð£Ð¤Ð¥Ð¦Ð§Ð¨Ð©ÐªÐ«Ð¬Ð­Ð®Ð¯â€&nbsp;Â°ÒÂ£Â§â€¢Â¶Ð†Â®Â©â„¢Ð‚Ñ’â‰&nbsp;ÐƒÑ“âˆžÂ±â‰¤â‰¥Ñ–ÂµÒ‘ÐˆÐ„Ñ”Ð‡Ñ—Ð‰Ñ™ÐŠÑš"+"Ñ˜Ð…Â¬âˆšÆ’â‰ˆâˆ†Â«Â»â€¦ Ð‹Ñ›ÐŒÑœÑ•â€“â€”â€œâ€â€˜â€™Ã·â€žÐŽÑžÐÑŸâ„–ÐÑ‘ÑÐ°Ð±Ð²Ð³Ð´ÐµÐ¶Ð·Ð¸Ð¹ÐºÐ»Ð¼Ð½Ð¾Ð¿Ñ€ÑÑ‚ÑƒÑ„Ñ…Ñ†Ñ‡ÑˆÑ‰ÑŠÑ‹ÑŒÑÑŽ","x-mac-gaelic":"Ã„Ã…Ã‡Ã‰Ã‘Ã–ÃœÃ¡Ã&nbsp;Ã¢Ã¤Ã£Ã¥Ã§Ã©Ã¨ÃªÃ«Ã­Ã¬Ã®Ã¯Ã±Ã³Ã²Ã´Ã¶ÃµÃºÃ¹Ã»Ã¼â€&nbsp;Â°Â¢Â£Â§â€¢Â¶ÃŸÂ®Â©â„¢Â´Â¨â‰&nbsp;Ã†Ã˜á¸‚Â±â‰¤â‰¥á¸ƒÄŠÄ‹á¸Šá¸‹á¸žá¸ŸÄ&nbsp;Ä¡á¹€Ã¦Ã¸"+"á¹á¹–á¹—É¼Æ’Å¿á¹&nbsp;Â«Â»â€¦ Ã€ÃƒÃ•Å’Å“â€“â€”â€œâ€â€˜â€™á¹¡áº›Ã¿Å¸á¹ªâ‚¬â€¹â€ºÅ¶Å·á¹«Â·á»²á»³âŠÃ‚ÃŠÃÃ‹ÃˆÃÃŽÃÃŒÃ“Ã”â™£Ã’ÃšÃ›Ã™Ä±ÃÃ½Å´Åµáº„áº…áº€áºáº‚áºƒ","x-mac-greek":"Ã„Â¹Â²Ã‰Â³Ã–ÃœÎ…Ã&nbsp;Ã¢Ã¤Î„Â¨Ã§Ã©Ã¨ÃªÃ«Â£â„¢Ã®Ã¯â€¢Â½â€°Ã´Ã¶Â¦â‚¬Ã¹Ã»Ã¼â€&nbsp;Î“Î”Î˜Î›ÎžÎ&nbsp;ÃŸÂ®Â©Î£ÎªÂ§â‰&nbsp;Â°Â·Î‘Â±â‰¤â‰¥Â¥Î’Î•Î–Î—Î™ÎšÎœÎ¦Î«Î¨Î©"+"Î¬ÎÂ¬ÎŸÎ¡â‰ˆÎ¤Â«Â»â€¦ Î¥Î§Î†ÎˆÅ“â€“â€•â€œâ€â€˜â€™Ã·Î‰ÎŠÎŒÎŽÎ­Î®Î¯ÏŒÎÏÎ±Î²ÏˆÎ´ÎµÏ†Î³Î·Î¹Î¾ÎºÎ»Î¼Î½Î¿Ï€ÏŽÏÏƒÏ„Î¸Ï‰Ï‚Ï‡Ï…Î¶ÏŠÏ‹ÎÎ°Â­","x-mac-icelandic":"Ã„Ã…Ã‡Ã‰Ã‘Ã–ÃœÃ¡Ã&nbsp;Ã¢Ã¤Ã£Ã¥Ã§Ã©Ã¨ÃªÃ«Ã­Ã¬Ã®Ã¯Ã±Ã³Ã²Ã´Ã¶ÃµÃºÃ¹Ã»Ã¼ÃÂ°Â¢Â£Â§â€¢Â¶ÃŸÂ®Â©â„¢Â´Â¨â‰&nbsp;Ã†Ã˜âˆžÂ±â‰¤â‰¥Â¥Âµâˆ‚âˆ‘âˆÏ€âˆ«ÂªÂºÎ©Ã¦Ã¸"+"Â¿Â¡Â¬âˆšÆ’â‰ˆâˆ†Â«Â»â€¦ Ã€ÃƒÃ•Å’Å“â€“â€”â€œâ€â€˜â€™Ã·â—ŠÃ¿Å¸â„â‚¬ÃÃ°ÃžÃ¾Ã½Â·â€šâ€žâ€°Ã‚ÃŠÃÃ‹ÃˆÃÃŽÃÃŒÃ“Ã”ï£¿Ã’ÃšÃ›Ã™Ä±Ë†ËœÂ¯Ë˜Ë™ËšÂ¸ËË›Ë‡","x-mac-inuit":"áƒá„á…á†áŠá‹á±á²á³á´á¸á¹á‘‰á‘Žá‘á‘á‘‘á‘•á‘–á‘¦á‘­á‘®á‘¯á‘°á‘²á‘³á’ƒá’‹á’Œá’á’Žá’á’‘Â°á’¡á’¥á’¦â€¢Â¶á’§Â®Â©â„¢á’¨á’ªá’«á’»á“‚á“ƒá“„á“…á“‡á“ˆá“á“¯á“°á“±á“²á“´á“µá”…á“•á“–á“—"+"á“˜á“šá“›á“ªá”¨á”©á”ªá”«á”­â€¦ á”®á”¾á••á•–á•—â€“â€”â€œâ€â€˜â€™á•˜á•™á•šá•á•†á•‡á•ˆá•‰á•‹á•Œá•á•¿á–€á–á–‚á–ƒá–„á–…á–á–á–‘á–’á–“á–”á–•á™±á™²á™³á™´á™µá™¶á––á–&nbsp;á–¡á–¢á–£á–¤á–¥á–¦á•¼ÅÅ‚","x-mac-ce":"Ã„Ä€ÄÃ‰Ä„Ã–ÃœÃ¡Ä…ÄŒÃ¤ÄÄ†Ä‡Ã©Å¹ÅºÄŽÃ­ÄÄ’Ä“Ä–Ã³Ä—Ã´Ã¶ÃµÃºÄšÄ›Ã¼â€&nbsp;Â°Ä˜Â£Â§â€¢Â¶ÃŸÂ®Â©â„¢Ä™Â¨â‰&nbsp;Ä£Ä®Ä¯Äªâ‰¤â‰¥Ä«Ä¶âˆ‚âˆ‘Å‚Ä»Ä¼Ä½Ä¾Ä¹ÄºÅ…"+"Å†ÅƒÂ¬âˆšÅ„Å‡âˆ†Â«Â»â€¦ ÅˆÅÃ•Å‘ÅŒâ€“â€”â€œâ€â€˜â€™Ã·â—ŠÅÅ”Å•Å˜â€¹â€ºÅ™Å–Å—Å&nbsp;â€šâ€žÅ¡ÅšÅ›ÃÅ¤Å¥ÃÅ½Å¾ÅªÃ“Ã”Å«Å®ÃšÅ¯Å°Å±Å²Å³ÃÃ½Ä·Å»ÅÅ¼Ä¢Ë‡",macintosh:"Ã„Ã…Ã‡Ã‰Ã‘Ã–ÃœÃ¡Ã&nbsp;Ã¢Ã¤Ã£Ã¥Ã§Ã©Ã¨ÃªÃ«Ã­Ã¬Ã®Ã¯Ã±Ã³Ã²Ã´Ã¶ÃµÃºÃ¹Ã»Ã¼â€&nbsp;Â°Â¢Â£Â§â€¢Â¶ÃŸÂ®Â©â„¢Â´Â¨â‰&nbsp;Ã†Ã˜âˆžÂ±â‰¤â‰¥Â¥Âµâˆ‚âˆ‘âˆÏ€âˆ«ÂªÂºÎ©Ã¦Ã¸"+"Â¿Â¡Â¬âˆšÆ’â‰ˆâˆ†Â«Â»â€¦ Ã€ÃƒÃ•Å’Å“â€“â€”â€œâ€â€˜â€™Ã·â—ŠÃ¿Å¸â„â‚¬â€¹â€ºï¬ï¬‚â€¡Â·â€šâ€žâ€°Ã‚ÃŠÃÃ‹ÃˆÃÃŽÃÃŒÃ“Ã”ï£¿Ã’ÃšÃ›Ã™Ä±Ë†ËœÂ¯Ë˜Ë™ËšÂ¸ËË›Ë‡","x-mac-romanian":"Ã„Ã…Ã‡Ã‰Ã‘Ã–ÃœÃ¡Ã&nbsp;Ã¢Ã¤Ã£Ã¥Ã§Ã©Ã¨ÃªÃ«Ã­Ã¬Ã®Ã¯Ã±Ã³Ã²Ã´Ã¶ÃµÃºÃ¹Ã»Ã¼â€&nbsp;Â°Â¢Â£Â§â€¢Â¶ÃŸÂ®Â©â„¢Â´Â¨â‰&nbsp;Ä‚È˜âˆžÂ±â‰¤â‰¥Â¥Âµâˆ‚âˆ‘âˆÏ€âˆ«ÂªÂºÎ©ÄƒÈ™"+"Â¿Â¡Â¬âˆšÆ’â‰ˆâˆ†Â«Â»â€¦ Ã€ÃƒÃ•Å’Å“â€“â€”â€œâ€â€˜â€™Ã·â—ŠÃ¿Å¸â„â‚¬â€¹â€ºÈšÈ›â€¡Â·â€šâ€žâ€°Ã‚ÃŠÃÃ‹ÃˆÃÃŽÃÃŒÃ“Ã”ï£¿Ã’ÃšÃ›Ã™Ä±Ë†ËœÂ¯Ë˜Ë™ËšÂ¸ËË›Ë‡","x-mac-turkish":"Ã„Ã…Ã‡Ã‰Ã‘Ã–ÃœÃ¡Ã&nbsp;Ã¢Ã¤Ã£Ã¥Ã§Ã©Ã¨ÃªÃ«Ã­Ã¬Ã®Ã¯Ã±Ã³Ã²Ã´Ã¶ÃµÃºÃ¹Ã»Ã¼â€&nbsp;Â°Â¢Â£Â§â€¢Â¶ÃŸÂ®Â©â„¢Â´Â¨â‰&nbsp;Ã†Ã˜âˆžÂ±â‰¤â‰¥Â¥Âµâˆ‚âˆ‘âˆÏ€âˆ«ÂªÂºÎ©Ã¦Ã¸"+"Â¿Â¡Â¬âˆšÆ’â‰ˆâˆ†Â«Â»â€¦ Ã€ÃƒÃ•Å’Å“â€“â€”â€œâ€â€˜â€™Ã·â—ŠÃ¿Å¸ÄžÄŸÄ°Ä±ÅžÅŸâ€¡Â·â€šâ€žâ€°Ã‚ÃŠÃÃ‹ÃˆÃÃŽÃÃŒÃ“Ã”ï£¿Ã’ÃšÃ›Ã™ï¢&nbsp;Ë†ËœÂ¯Ë˜Ë™ËšÂ¸ËË›Ë‡"};decode.MACSTRING=function(dataView,offset,dataLength,encoding){var table=eightBitMacEncodings[encoding];if(table===undefined){return undefined}var result="";for(var i=0;i&lt;dataLength;i++){var c=dataView.getUint8(offset+i);if(c&lt;=127){result+=String.fromCharCode(c)}else{result+=table[c&amp;127]}}return result};var macEncodingTableCache=typeof WeakMap==="function"&amp;&amp;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&lt;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&lt;str.length;i++){var c=str.charCodeAt(i);if(c&gt;=128){c=table[c];if(c===undefined){return undefined}}result[i]=c}return result};sizeOf.MACSTRING=function(str,encoding){var b=encode.MACSTRING(str,encoding);if(b!==undefined){return b.length}else{return 0}};function isByteEncodable(value){return value&gt;=-128&amp;&amp;value&lt;=127}function encodeVarDeltaRunAsZeroes(deltas,pos,result){var runLength=0;var numDeltas=deltas.length;while(pos&lt;numDeltas&amp;&amp;runLength&lt;64&amp;&amp;deltas[pos]===0){++pos;++runLength}result.push(128|runLength-1);return pos}function encodeVarDeltaRunAsBytes(deltas,offset,result){var runLength=0;var numDeltas=deltas.length;var pos=offset;while(pos&lt;numDeltas&amp;&amp;runLength&lt;64){var value=deltas[pos];if(!isByteEncodable(value)){break}if(value===0&amp;&amp;pos+1&lt;numDeltas&amp;&amp;deltas[pos+1]===0){break}++pos;++runLength}result.push(runLength-1);for(var i=offset;i&lt;pos;++i){result.push(deltas[i]+256&amp;255)}return pos}function encodeVarDeltaRunAsWords(deltas,offset,result){var runLength=0;var numDeltas=deltas.length;var pos=offset;while(pos&lt;numDeltas&amp;&amp;runLength&lt;64){var value=deltas[pos];if(value===0){break}if(isByteEncodable(value)&amp;&amp;pos+1&lt;numDeltas&amp;&amp;isByteEncodable(deltas[pos+1])){break}++pos;++runLength}result.push(64|runLength-1);for(var i=offset;i&lt;pos;++i){var val=deltas[i];result.push(val+65536&gt;&gt;8&amp;255,val+256&amp;255)}return pos}encode.VARDELTAS=function(deltas){var pos=0;var result=[];while(pos&lt;deltas.length){var value=deltas[pos];if(value===0){pos=encodeVarDeltaRunAsZeroes(deltas,pos,result)}else if(value&gt;=-128&amp;&amp;value&lt;=127){pos=encodeVarDeltaRunAsBytes(deltas,pos,result)}else{pos=encodeVarDeltaRunAsWords(deltas,pos,result)}}return result};encode.INDEX=function(l){var offset=1;var offsets=[offset];var data=[];for(var i=0;i&lt;l.length;i+=1){var v=encode.OBJECT(l[i]);Array.prototype.push.apply(data,v);offset+=v.length;offsets.push(offset)}if(data.length===0){return[0,0]}var encodedOffsets=[];var offSize=1+Math.floor(Math.log(offset)/Math.log(2))/8|0;var offsetEncoder=[undefined,encode.BYTE,encode.USHORT,encode.UINT24,encode.ULONG][offSize];for(var i$1=0;i$1&lt;offsets.length;i$1+=1){var encodedOffset=offsetEncoder(offsets[i$1]);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&lt;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&lt;1200){return[v]}else{return[12,v-1200]}};encode.OPERAND=function(v,type){var d=[];if(Array.isArray(type)){for(var i=0;i&lt;type.length;i+=1){check.argument(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"&amp;&amp;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&lt;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];check.argument(encodingFunction!==undefined,"No encoding function for type "+v.type);return encodingFunction(v.value)};sizeOf.OBJECT=function(v){var sizeOfFunction=sizeOf[v.type];check.argument(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=[];for(var i=0;i&lt;length;i+=1){var field=table.fields[i];var encodingFunction=encode[field.type];check.argument(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(var i$1=0;i$1&lt;subtables.length;i$1+=1){var o=subtableOffsets[i$1];var offset=d.length;check.argument(offset&lt;65536,"Table "+table.tableName+" too big.");d[o]=offset&gt;&gt;8;d[o+1]=offset&amp;255;d=d.concat(subtables[i$1])}return d};sizeOf.TABLE=function(table){var numBytes=0;var length=table.fields.length;for(var i=0;i&lt;length;i+=1){var field=table.fields[i];var sizeOfFunction=sizeOf[field.type];check.argument(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};function Table(tableName,fields,options){for(var i=0;i&lt;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(var i$1=0;i$1&lt;optionKeys.length;i$1+=1){var k=optionKeys[i$1];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 ushortList(itemName,list,count){if(count===undefined){count=list.length}var fields=new Array(list.length+1);fields[0]={name:itemName+"Count",type:"USHORT",value:count};for(var i=0;i&lt;list.length;i++){fields[i+1]={name:itemName+i,type:"USHORT",value:list[i]}}return fields}function tableList(itemName,records,itemCallback){var count=records.length;var fields=new Array(count+1);fields[0]={name:itemName+"Count",type:"USHORT",value:count};for(var i=0;i&lt;count;i++){fields[i+1]={name:itemName+i,type:"TABLE",value:itemCallback(records[i],i)}}return fields}function recordList(itemName,records,itemCallback){var count=records.length;var fields=[];fields[0]={name:itemName+"Count",type:"USHORT",value:count};for(var i=0;i&lt;count;i++){fields=fields.concat(itemCallback(records[i],i))}return fields}function Coverage(coverageTable){if(coverageTable.format===1){Table.call(this,"coverageTable",[{name:"coverageFormat",type:"USHORT",value:1}].concat(ushortList("glyph",coverageTable.glyphs)))}else{check.assert(false,"Can't create coverage table format 2 yet.")}}Coverage.prototype=Object.create(Table.prototype);Coverage.prototype.constructor=Coverage;function ScriptList(scriptListTable){Table.call(this,"scriptListTable",recordList("scriptRecord",scriptListTable,function(scriptRecord,i){var script=scriptRecord.script;var defaultLangSys=script.defaultLangSys;check.assert(!!defaultLangSys,"Unable to write GSUB: script "+scriptRecord.tag+" has no default language system.");return[{name:"scriptTag"+i,type:"TAG",value:scriptRecord.tag},{name:"script"+i,type:"TABLE",value:new Table("scriptTable",[{name:"defaultLangSys",type:"TABLE",value:new Table("defaultLangSys",[{name:"lookupOrder",type:"USHORT",value:0},{name:"reqFeatureIndex",type:"USHORT",value:defaultLangSys.reqFeatureIndex}].concat(ushortList("featureIndex",defaultLangSys.featureIndexes)))}].concat(recordList("langSys",script.langSysRecords,function(langSysRecord,i){var langSys=langSysRecord.langSys;return[{name:"langSysTag"+i,type:"TAG",value:langSysRecord.tag},{name:"langSys"+i,type:"TABLE",value:new Table("langSys",[{name:"lookupOrder",type:"USHORT",value:0},{name:"reqFeatureIndex",type:"USHORT",value:langSys.reqFeatureIndex}].concat(ushortList("featureIndex",langSys.featureIndexes)))}]})))}]}))}ScriptList.prototype=Object.create(Table.prototype);ScriptList.prototype.constructor=ScriptList;function FeatureList(featureListTable){Table.call(this,"featureListTable",recordList("featureRecord",featureListTable,function(featureRecord,i){var feature=featureRecord.feature;return[{name:"featureTag"+i,type:"TAG",value:featureRecord.tag},{name:"feature"+i,type:"TABLE",value:new Table("featureTable",[{name:"featureParams",type:"USHORT",value:feature.featureParams}].concat(ushortList("lookupListIndex",feature.lookupListIndexes)))}]}))}FeatureList.prototype=Object.create(Table.prototype);FeatureList.prototype.constructor=FeatureList;function LookupList(lookupListTable,subtableMakers){Table.call(this,"lookupListTable",tableList("lookup",lookupListTable,function(lookupTable){var subtableCallback=subtableMakers[lookupTable.lookupType];check.assert(!!subtableCallback,"Unable to write GSUB lookup type "+lookupTable.lookupType+" tables.");return new Table("lookupTable",[{name:"lookupType",type:"USHORT",value:lookupTable.lookupType},{name:"lookupFlag",type:"USHORT",value:lookupTable.lookupFlag}].concat(tableList("subtable",lookupTable.subtables,subtableCallback)))}))}LookupList.prototype=Object.create(Table.prototype);LookupList.prototype.constructor=LookupList;var table={Table:Table,Record:Table,Coverage:Coverage,ScriptList:ScriptList,FeatureList:FeatureList,LookupList:LookupList,ushortList:ushortList,tableList:tableList,recordList:recordList};function getByte(dataView,offset){return dataView.getUint8(offset)}function getUShort(dataView,offset){return dataView.getUint16(offset,false)}function getShort(dataView,offset){return dataView.getInt16(offset,false)}function getULong(dataView,offset){return dataView.getUint32(offset,false)}function getFixed(dataView,offset){var decimal=dataView.getInt16(offset,false);var fraction=dataView.getUint16(offset+2,false);return decimal+fraction/65535}function getTag(dataView,offset){var tag="";for(var i=offset;i&lt;offset+4;i+=1){tag+=String.fromCharCode(dataView.getInt8(i))}return tag}function getOffset(dataView,offset,offSize){var v=0;for(var i=0;i&lt;offSize;i+=1){v&lt;&lt;=8;v+=dataView.getUint8(offset+i)}return v}function getBytes(dataView,startOffset,endOffset){var bytes=[];for(var i=startOffset;i&lt;endOffset;i+=1){bytes.push(dataView.getUint8(i))}return bytes}function bytesToString(bytes){var s="";for(var i=0;i&lt;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.parseOffset32=Parser.prototype.parseULong;Parser.prototype.parseFixed=function(){var v=getFixed(this.data,this.offset+this.relativeOffset);this.relativeOffset+=4;return v};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&lt;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);v-=2082844800;this.relativeOffset+=8;return v};Parser.prototype.parseVersion=function(minorBase){var major=getUShort(this.data,this.offset+this.relativeOffset);var minor=getUShort(this.data,this.offset+this.relativeOffset+2);this.relativeOffset+=4;if(minorBase===undefined){minorBase=4096}return major+minor/minorBase/10};Parser.prototype.skip=function(type,amount){if(amount===undefined){amount=1}this.relativeOffset+=typeOffsets[type]*amount};Parser.prototype.parseULongList=function(count){if(count===undefined){count=this.parseULong()}var offsets=new Array(count);var dataView=this.data;var offset=this.offset+this.relativeOffset;for(var i=0;i&lt;count;i++){offsets[i]=dataView.getUint32(offset);offset+=4}this.relativeOffset+=count*4;return offsets};Parser.prototype.parseOffset16List=Parser.prototype.parseUShortList=function(count){if(count===undefined){count=this.parseUShort()}var offsets=new Array(count);var dataView=this.data;var offset=this.offset+this.relativeOffset;for(var i=0;i&lt;count;i++){offsets[i]=dataView.getUint16(offset);offset+=2}this.relativeOffset+=count*2;return offsets};Parser.prototype.parseShortList=function(count){var list=new Array(count);var dataView=this.data;var offset=this.offset+this.relativeOffset;for(var i=0;i&lt;count;i++){list[i]=dataView.getInt16(offset);offset+=2}this.relativeOffset+=count*2;return list};Parser.prototype.parseByteList=function(count){var list=new Array(count);var dataView=this.data;var offset=this.offset+this.relativeOffset;for(var i=0;i&lt;count;i++){list[i]=dataView.getUint8(offset++)}this.relativeOffset+=count;return list};Parser.prototype.parseList=function(count,itemCallback){if(!itemCallback){itemCallback=count;count=this.parseUShort()}var list=new Array(count);for(var i=0;i&lt;count;i++){list[i]=itemCallback.call(this)}return list};Parser.prototype.parseList32=function(count,itemCallback){if(!itemCallback){itemCallback=count;count=this.parseULong()}var list=new Array(count);for(var i=0;i&lt;count;i++){list[i]=itemCallback.call(this)}return list};Parser.prototype.parseRecordList=function(count,recordDescription){if(!recordDescription){recordDescription=count;count=this.parseUShort()}var records=new Array(count);var fields=Object.keys(recordDescription);for(var i=0;i&lt;count;i++){var rec={};for(var j=0;j&lt;fields.length;j++){var fieldName=fields[j];var fieldType=recordDescription[fieldName];rec[fieldName]=fieldType.call(this)}records[i]=rec}return records};Parser.prototype.parseRecordList32=function(count,recordDescription){if(!recordDescription){recordDescription=count;count=this.parseULong()}var records=new Array(count);var fields=Object.keys(recordDescription);for(var i=0;i&lt;count;i++){var rec={};for(var j=0;j&lt;fields.length;j++){var fieldName=fields[j];var fieldType=recordDescription[fieldName];rec[fieldName]=fieldType.call(this)}records[i]=rec}return records};Parser.prototype.parseStruct=function(description){if(typeof description==="function"){return description.call(this)}else{var fields=Object.keys(description);var struct={};for(var j=0;j&lt;fields.length;j++){var fieldName=fields[j];var fieldType=description[fieldName];struct[fieldName]=fieldType.call(this)}return struct}};Parser.prototype.parseValueRecord=function(valueFormat){if(valueFormat===undefined){valueFormat=this.parseUShort()}if(valueFormat===0){return}var valueRecord={};if(valueFormat&amp;1){valueRecord.xPlacement=this.parseShort()}if(valueFormat&amp;2){valueRecord.yPlacement=this.parseShort()}if(valueFormat&amp;4){valueRecord.xAdvance=this.parseShort()}if(valueFormat&amp;8){valueRecord.yAdvance=this.parseShort()}if(valueFormat&amp;16){valueRecord.xPlaDevice=undefined;this.parseShort()}if(valueFormat&amp;32){valueRecord.yPlaDevice=undefined;this.parseShort()}if(valueFormat&amp;64){valueRecord.xAdvDevice=undefined;this.parseShort()}if(valueFormat&amp;128){valueRecord.yAdvDevice=undefined;this.parseShort()}return valueRecord};Parser.prototype.parseValueRecordList=function(){var valueFormat=this.parseUShort();var valueCount=this.parseUShort();var values=new Array(valueCount);for(var i=0;i&lt;valueCount;i++){values[i]=this.parseValueRecord(valueFormat)}return values};Parser.prototype.parsePointer=function(description){var structOffset=this.parseOffset16();if(structOffset&gt;0){return new Parser(this.data,this.offset+structOffset).parseStruct(description)}return undefined};Parser.prototype.parsePointer32=function(description){var structOffset=this.parseOffset32();if(structOffset&gt;0){return new Parser(this.data,this.offset+structOffset).parseStruct(description)}return undefined};Parser.prototype.parseListOfLists=function(itemCallback){var offsets=this.parseOffset16List();var count=offsets.length;var relativeOffset=this.relativeOffset;var list=new Array(count);for(var i=0;i&lt;count;i++){var start=offsets[i];if(start===0){list[i]=undefined;continue}this.relativeOffset=start;if(itemCallback){var subOffsets=this.parseOffset16List();var subList=new Array(subOffsets.length);for(var j=0;j&lt;subOffsets.length;j++){this.relativeOffset=start+subOffsets[j];subList[j]=itemCallback.call(this)}list[i]=subList}else{list[i]=this.parseUShortList()}}this.relativeOffset=relativeOffset;return list};Parser.prototype.parseCoverage=function(){var startOffset=this.offset+this.relativeOffset;var format=this.parseUShort();var count=this.parseUShort();if(format===1){return{format:1,glyphs:this.parseUShortList(count)}}else if(format===2){var ranges=new Array(count);for(var i=0;i&lt;count;i++){ranges[i]={start:this.parseUShort(),end:this.parseUShort(),index:this.parseUShort()}}return{format:2,ranges:ranges}}throw new Error("0x"+startOffset.toString(16)+": Coverage format must be 1 or 2.")};Parser.prototype.parseClassDef=function(){var startOffset=this.offset+this.relativeOffset;var format=this.parseUShort();if(format===1){return{format:1,startGlyph:this.parseUShort(),classes:this.parseUShortList()}}else if(format===2){return{format:2,ranges:this.parseRecordList({start:Parser.uShort,end:Parser.uShort,classId:Parser.uShort})}}throw new Error("0x"+startOffset.toString(16)+": ClassDef format must be 1 or 2.")};Parser.list=function(count,itemCallback){return function(){return this.parseList(count,itemCallback)}};Parser.list32=function(count,itemCallback){return function(){return this.parseList32(count,itemCallback)}};Parser.recordList=function(count,recordDescription){return function(){return this.parseRecordList(count,recordDescription)}};Parser.recordList32=function(count,recordDescription){return function(){return this.parseRecordList32(count,recordDescription)}};Parser.pointer=function(description){return function(){return this.parsePointer(description)}};Parser.pointer32=function(description){return function(){return this.parsePointer32(description)}};Parser.tag=Parser.prototype.parseTag;Parser.byte=Parser.prototype.parseByte;Parser.uShort=Parser.offset16=Parser.prototype.parseUShort;Parser.uShortList=Parser.prototype.parseUShortList;Parser.uLong=Parser.offset32=Parser.prototype.parseULong;Parser.uLongList=Parser.prototype.parseULongList;Parser.struct=Parser.prototype.parseStruct;Parser.coverage=Parser.prototype.parseCoverage;Parser.classDef=Parser.prototype.parseClassDef;var langSysTable={reserved:Parser.uShort,reqFeatureIndex:Parser.uShort,featureIndexes:Parser.uShortList};Parser.prototype.parseScriptList=function(){return this.parsePointer(Parser.recordList({tag:Parser.tag,script:Parser.pointer({defaultLangSys:Parser.pointer(langSysTable),langSysRecords:Parser.recordList({tag:Parser.tag,langSys:Parser.pointer(langSysTable)})})}))||[]};Parser.prototype.parseFeatureList=function(){return this.parsePointer(Parser.recordList({tag:Parser.tag,feature:Parser.pointer({featureParams:Parser.offset16,lookupListIndexes:Parser.uShortList})}))||[]};Parser.prototype.parseLookupList=function(lookupTableParsers){return this.parsePointer(Parser.list(Parser.pointer(function(){var lookupType=this.parseUShort();check.argument(1&lt;=lookupType&amp;&amp;lookupType&lt;=9,"GPOS/GSUB lookup type "+lookupType+" unknown.");var lookupFlag=this.parseUShort();var useMarkFilteringSet=lookupFlag&amp;16;return{lookupType:lookupType,lookupFlag:lookupFlag,subtables:this.parseList(Parser.pointer(lookupTableParsers[lookupType])),markFilteringSet:useMarkFilteringSet?this.parseUShort():undefined}})))||[]};Parser.prototype.parseFeatureVariationsList=function(){return this.parsePointer32(function(){var majorVersion=this.parseUShort();var minorVersion=this.parseUShort();check.argument(majorVersion===1&amp;&amp;minorVersion&lt;1,"GPOS/GSUB feature variations table unknown.");var featureVariations=this.parseRecordList32({conditionSetOffset:Parser.offset32,featureTableSubstitutionOffset:Parser.offset32});return featureVariations})||[]};var parse={getByte:getByte,getCard8:getByte,getUShort:getUShort,getCard16:getUShort,getShort:getShort,getULong:getULong,getFixed:getFixed,getTag:getTag,getOffset:getOffset,getBytes:getBytes,bytesToString:bytesToString,Parser:Parser};function parseCmapTableFormat12(cmap,p){p.parseUShort();cmap.length=p.parseULong();cmap.language=p.parseULong();var groupCount;cmap.groupCount=groupCount=p.parseULong();cmap.glyphIndexMap={};for(var i=0;i&lt;groupCount;i+=1){var startCharCode=p.parseULong();var endCharCode=p.parseULong();var startGlyphId=p.parseULong();for(var c=startCharCode;c&lt;=endCharCode;c+=1){cmap.glyphIndexMap[c]=startGlyphId;startGlyphId++}}}function parseCmapTableFormat4(cmap,p,data,start,offset){cmap.length=p.parseUShort();cmap.language=p.parseUShort();var segCount;cmap.segCount=segCount=p.parseUShort()&gt;&gt;1;p.skip("uShort",3);cmap.glyphIndexMap={};var endCountParser=new parse.Parser(data,start+offset+14);var startCountParser=new parse.Parser(data,start+offset+16+segCount*2);var idDeltaParser=new parse.Parser(data,start+offset+16+segCount*4);var idRangeOffsetParser=new parse.Parser(data,start+offset+16+segCount*6);var glyphIndexOffset=start+offset+16+segCount*8;for(var i=0;i&lt;segCount-1;i+=1){var glyphIndex=void 0;var endCount=endCountParser.parseUShort();var startCount=startCountParser.parseUShort();var idDelta=idDeltaParser.parseShort();var idRangeOffset=idRangeOffsetParser.parseUShort();for(var c=startCount;c&lt;=endCount;c+=1){if(idRangeOffset!==0){glyphIndexOffset=idRangeOffsetParser.offset+idRangeOffsetParser.relativeOffset-2;glyphIndexOffset+=idRangeOffset;glyphIndexOffset+=(c-startCount)*2;glyphIndex=parse.getUShort(data,glyphIndexOffset);if(glyphIndex!==0){glyphIndex=glyphIndex+idDelta&amp;65535}}else{glyphIndex=c+idDelta&amp;65535}cmap.glyphIndexMap[c]=glyphIndex}}}function parseCmapTable(data,start){var cmap={};cmap.version=parse.getUShort(data,start);check.argument(cmap.version===0,"cmap table version should be 0.");cmap.numTables=parse.getUShort(data,start+2);var offset=-1;for(var i=cmap.numTables-1;i&gt;=0;i-=1){var platformId=parse.getUShort(data,start+4+i*8);var encodingId=parse.getUShort(data,start+4+i*8+2);if(platformId===3&amp;&amp;(encodingId===0||encodingId===1||encodingId===10)||platformId===0&amp;&amp;(encodingId===0||encodingId===1||encodingId===2||encodingId===3||encodingId===4)){offset=parse.getULong(data,start+4+i*8+4);break}}if(offset===-1){throw new Error("No valid cmap sub-tables found.")}var p=new parse.Parser(data,start+offset);cmap.format=p.parseUShort();if(cmap.format===12){parseCmapTableFormat12(cmap,p)}else if(cmap.format===4){parseCmapTableFormat4(cmap,p,data,start,offset)}else{throw new Error("Only format 4 and 12 cmap tables are supported (found format "+cmap.format+").")}return cmap}function addSegment(t,code,glyphIndex){t.segments.push({end:code,start:code,delta:-(code-glyphIndex),offset:0,glyphIndex:glyphIndex})}function addTerminatorSegment(t){t.segments.push({end:65535,start:65535,delta:1,offset:0})}function makeCmapTable(glyphs){var isPlan0Only=true;var i;for(i=glyphs.length-1;i&gt;0;i-=1){var g=glyphs.get(i);if(g.unicode&gt;65535){console.log("Adding CMAP format 12 (needed!)");isPlan0Only=false;break}}var cmapTable=[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:isPlan0Only?1:2},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:isPlan0Only?12:12+8}];if(!isPlan0Only){cmapTable=cmapTable.concat([{name:"cmap12PlatformID",type:"USHORT",value:3},{name:"cmap12EncodingID",type:"USHORT",value:10},{name:"cmap12Offset",type:"ULONG",value:0}])}cmapTable=cmapTable.concat([{name:"format",type:"USHORT",value:4},{name:"cmap4Length",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}]);var t=new table.Table("cmap",cmapTable);t.segments=[];for(i=0;i&lt;glyphs.length;i+=1){var glyph=glyphs.get(i);for(var j=0;j&lt;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=t.segments.length;var segCountToRemove=0;var endCounts=[];var startCounts=[];var idDeltas=[];var idRangeOffsets=[];var glyphIds=[];var cmap12Groups=[];for(i=0;i&lt;segCount;i+=1){var segment=t.segments[i];if(segment.end&lt;=65535&amp;&amp;segment.start&lt;=65535){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})}}else{segCountToRemove+=1}if(!isPlan0Only&amp;&amp;segment.glyphIndex!==undefined){cmap12Groups=cmap12Groups.concat({name:"cmap12Start_"+i,type:"ULONG",value:segment.start});cmap12Groups=cmap12Groups.concat({name:"cmap12End_"+i,type:"ULONG",value:segment.end});cmap12Groups=cmap12Groups.concat({name:"cmap12Glyph_"+i,type:"ULONG",value:segment.glyphIndex})}}t.segCountX2=(segCount-segCountToRemove)*2;t.searchRange=Math.pow(2,Math.floor(Math.log(segCount-segCountToRemove)/Math.log(2)))*2;t.entrySelector=Math.log(t.searchRange/2)/Math.log(2);t.rangeShift=t.segCountX2-t.searchRange;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.cmap4Length=14+endCounts.length*2+2+startCounts.length*2+idDeltas.length*2+idRangeOffsets.length*2+glyphIds.length*2;if(!isPlan0Only){var cmap12Length=16+cmap12Groups.length*4;t.cmap12Offset=12+2*2+4+t.cmap4Length;t.fields=t.fields.concat([{name:"cmap12Format",type:"USHORT",value:12},{name:"cmap12Reserved",type:"USHORT",value:0},{name:"cmap12Length",type:"ULONG",value:cmap12Length},{name:"cmap12Language",type:"ULONG",value:0},{name:"cmap12nGroups",type:"ULONG",value:cmap12Groups.length/3}]);t.fields=t.fields.concat(cmap12Groups)}return t}var cmap={parse:parseCmapTable,make:makeCmapTable};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.codePointAt(0);var glyphs=this.font.glyphs;if(glyphs){for(var i=0;i&lt;glyphs.length;i+=1){var glyph=glyphs.get(i);for(var j=0;j&lt;glyph.unicodes.length;j+=1){if(glyph.unicodes[j]===code){return i}}}}return null};function CmapEncoding(cmap){this.cmap=cmap}CmapEncoding.prototype.charToGlyphIndex=function(c){return this.cmap.glyphIndexMap[c.codePointAt(0)]||0};function CffEncoding(encoding,charset){this.encoding=encoding;this.charset=charset}CffEncoding.prototype.charToGlyphIndex=function(s){var code=s.codePointAt(0);var charName=this.encoding[code];return this.charset.indexOf(charName)};function GlyphNames(post){switch(post.version){case 1:this.names=standardNames.slice();break;case 2:this.names=new Array(post.numberOfGlyphs);for(var i=0;i&lt;post.numberOfGlyphs;i++){if(post.glyphNameIndex[i]&lt;standardNames.length){this.names[i]=standardNames[post.glyphNameIndex[i]]}else{this.names[i]=post.names[post.glyphNameIndex[i]-standardNames.length]}}break;case 2.5:this.names=new Array(post.numberOfGlyphs);for(var i$1=0;i$1&lt;post.numberOfGlyphs;i$1++){this.names[i$1]=standardNames[i$1+post.glyphNameIndex[i$1]]}break;case 3:this.names=[];break;default:this.names=[];break}}GlyphNames.prototype.nameToGlyphIndex=function(name){return this.names.indexOf(name)};GlyphNames.prototype.glyphIndexToName=function(gid){return this.names[gid]};function addGlyphNamesAll(font){var glyph;var glyphIndexMap=font.tables.cmap.glyphIndexMap;var charCodes=Object.keys(glyphIndexMap);for(var i=0;i&lt;charCodes.length;i+=1){var c=charCodes[i];var glyphIndex=glyphIndexMap[c];glyph=font.glyphs.get(glyphIndex);glyph.addUnicode(parseInt(c))}for(var i$1=0;i$1&lt;font.glyphs.length;i$1+=1){glyph=font.glyphs.get(i$1);if(font.cffEncoding){if(font.isCIDFont){glyph.name="gid"+i$1}else{glyph.name=font.cffEncoding.charset[i$1]}}else if(font.glyphNames.names){glyph.name=font.glyphNames.glyphIndexToName(i$1)}}}function addGlyphNamesToUnicodeMap(font){font._IndexToUnicodeMap={};var glyphIndexMap=font.tables.cmap.glyphIndexMap;var charCodes=Object.keys(glyphIndexMap);for(var i=0;i&lt;charCodes.length;i+=1){var c=charCodes[i];var glyphIndex=glyphIndexMap[c];if(font._IndexToUnicodeMap[glyphIndex]===undefined){font._IndexToUnicodeMap[glyphIndex]={unicodes:[parseInt(c)]}}else{font._IndexToUnicodeMap[glyphIndex].unicodes.push(parseInt(c))}}}function addGlyphNames(font,opt){if(opt.lowMemory){addGlyphNamesToUnicodeMap(font)}else{addGlyphNamesAll(font)}}function line(ctx,x1,y1,x2,y2){ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);ctx.stroke()}var draw={line:line};function getPathDefinition(glyph,path){var _path=path||new Path;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("xMin"in options){this.xMin=options.xMin}if("yMin"in options){this.yMin=options.yMin}if("xMax"in options){this.xMax=options.xMax}if("yMax"in options){this.yMax=options.yMax}if("advanceWidth"in options){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.getBoundingBox=function(){return this.path.getBoundingBox()};Glyph.prototype.getPath=function(x,y,fontSize,options,font){x=x!==undefined?x:0;y=y!==undefined?y:0;fontSize=fontSize!==undefined?fontSize:72;var commands;var hPoints;if(!options){options={}}var xScale=options.xScale;var yScale=options.yScale;if(options.hinting&amp;&amp;font&amp;&amp;font.hinting){hPoints=this.path&amp;&amp;font.hinting.exec(this,fontSize)}if(hPoints){commands=font.hinting.getCommands(hPoints);x=Math.round(x);y=Math.round(y);xScale=yScale=1}else{commands=this.path.commands;var scale=1/(this.path.unitsPerEm||1e3)*fontSize;if(xScale===undefined){xScale=scale}if(yScale===undefined){yScale=scale}}var p=new Path;for(var i=0;i&lt;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&lt;this.points.length;i+=1){var pt=this.points[i];currentContour.push(pt);if(pt.lastPointOfContour){contours.push(currentContour);currentContour=[]}}check.argument(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&lt;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){ctx.beginPath();for(var j=0;j&lt;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,Math.PI*2,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&lt;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 defineDependentProperty(glyph,externalName,internalName){Object.defineProperty(glyph,externalName,{get:function(){glyph.path;return glyph[internalName]},set:function(newValue){glyph[internalName]=newValue},enumerable:true,configurable:true})}function GlyphSet(font,glyphs){this.font=font;this.glyphs={};if(Array.isArray(glyphs)){for(var i=0;i&lt;glyphs.length;i++){var glyph=glyphs[i];glyph.path.unitsPerEm=font.unitsPerEm;this.glyphs[i]=glyph}}this.length=glyphs&amp;&amp;glyphs.length||0}GlyphSet.prototype.get=function(index){if(this.glyphs[index]===undefined){this.font._push(index);if(typeof this.glyphs[index]==="function"){this.glyphs[index]=this.glyphs[index]()}var glyph=this.glyphs[index];var unicodeObj=this.font._IndexToUnicodeMap[index];if(unicodeObj){for(var j=0;j&lt;unicodeObj.unicodes.length;j++){glyph.addUnicode(unicodeObj.unicodes[j])}}if(this.font.cffEncoding){if(this.font.isCIDFont){glyph.name="gid"+index}else{glyph.name=this.font.cffEncoding.charset[index]}}else if(this.font.glyphNames.names){glyph.name=this.font.glyphNames.glyphIndexToName(index)}this.glyphs[index].advanceWidth=this.font._hmtxTableData[index].advanceWidth;this.glyphs[index].leftSideBearing=this.font._hmtxTableData[index].leftSideBearing}else{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};defineDependentProperty(glyph,"xMin","_xMin");defineDependentProperty(glyph,"xMax","_xMax");defineDependentProperty(glyph,"yMin","_yMin");defineDependentProperty(glyph,"yMax","_yMax");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}}var glyphset={GlyphSet:GlyphSet,glyphLoader:glyphLoader,ttfGlyphLoader:ttfGlyphLoader,cffGlyphLoader:cffGlyphLoader};function equals(a,b){if(a===b){return true}else if(Array.isArray(a)&amp;&amp;Array.isArray(b)){if(a.length!==b.length){return false}for(var i=0;i&lt;a.length;i+=1){if(!equals(a[i],b[i])){return false}}return true}else{return false}}function calcCFFSubroutineBias(subrs){var bias;if(subrs.length&lt;1240){bias=107}else if(subrs.length&lt;33900){bias=1131}else{bias=32768}return bias}function parseCFFIndex(data,start,conversionFn){var offsets=[];var objects=[];var count=parse.getCard16(data,start);var objectOffset;var endOffset;if(count!==0){var offsetSize=parse.getByte(data,start+2);objectOffset=start+(count+1)*offsetSize+2;var pos=start+3;for(var i=0;i&lt;count+1;i+=1){offsets.push(parse.getOffset(data,pos,offsetSize));pos+=offsetSize}endOffset=objectOffset+offsets[count]}else{endOffset=start+2}for(var i$1=0;i$1&lt;offsets.length-1;i$1+=1){var value=parse.getBytes(data,objectOffset+offsets[i$1],objectOffset+offsets[i$1+1]);if(conversionFn){value=conversionFn(value)}objects.push(value)}return{objects:objects,startOffset:start,endOffset:endOffset}}function parseCFFIndexLowMemory(data,start){var offsets=[];var count=parse.getCard16(data,start);var objectOffset;var endOffset;if(count!==0){var offsetSize=parse.getByte(data,start+2);objectOffset=start+(count+1)*offsetSize+2;var pos=start+3;for(var i=0;i&lt;count+1;i+=1){offsets.push(parse.getOffset(data,pos,offsetSize));pos+=offsetSize}endOffset=objectOffset+offsets[count]}else{endOffset=start+2}return{offsets:offsets,startOffset:start,endOffset:endOffset}}function getCffIndexObject(i,offsets,data,start,conversionFn){var count=parse.getCard16(data,start);var objectOffset=0;if(count!==0){var offsetSize=parse.getByte(data,start+2);objectOffset=start+(count+1)*offsetSize+2}var value=parse.getBytes(data,objectOffset+offsets[i],objectOffset+offsets[i+1]);if(conversionFn){value=conversionFn(value)}return value}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&gt;&gt;4;var n2=b&amp;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&lt;&lt;8|b2}if(b0===29){b1=parser.parseByte();b2=parser.parseByte();b3=parser.parseByte();b4=parser.parseByte();return b1&lt;&lt;24|b2&lt;&lt;16|b3&lt;&lt;8|b4}if(b0===30){return parseFloatOperand(parser)}if(b0&gt;=32&amp;&amp;b0&lt;=246){return b0-139}if(b0&gt;=247&amp;&amp;b0&lt;=250){b1=parser.parseByte();return(b0-247)*256+b1+108}if(b0&gt;=251&amp;&amp;b0&lt;=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&lt;entries.length;i+=1){var key=entries[i][0];var values=entries[i][1];var value=void 0;if(values.length===1){value=values[0]}else{value=values}if(o.hasOwnProperty(key)&amp;&amp;!isNaN(o[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 parse.Parser(data,start);var entries=[];var operands=[];size=size!==undefined?size:data.length;while(parser.relativeOffset&lt;size){var op=parser.parseByte();if(op&lt;=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&lt;=390){index=cffStandardStrings[index]}else{index=strings[index-391]}return index}function interpretDict(dict,meta,strings){var newDict={};var value;for(var i=0;i&lt;meta.length;i+=1){var m=meta[i];if(Array.isArray(m.type)){var values=[];values.length=m.type.length;for(var j=0;j&lt;m.type.length;j++){value=dict[m.op]!==undefined?dict[m.op][j]:undefined;if(value===undefined){value=m.value!==undefined&amp;&amp;m.value[j]!==undefined?m.value[j]:null}if(m.type[j]==="SID"){value=getCFFString(strings,value)}values[j]=value}newDict[m.name]=values}else{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=parse.getCard8(data,start);header.formatMinor=parse.getCard8(data,start+1);header.size=parse.getCard8(data,start+2);header.offsetSize=parse.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]},{name:"ros",op:1230,type:["SID","SID","number"]},{name:"cidFontVersion",op:1231,type:"number",value:0},{name:"cidFontRevision",op:1232,type:"number",value:0},{name:"cidFontType",op:1233,type:"number",value:0},{name:"cidCount",op:1234,type:"number",value:8720},{name:"uidBase",op:1235,type:"number"},{name:"fdArray",op:1236,type:"offset"},{name:"fdSelect",op:1237,type:"offset"},{name:"fontName",op:1238,type:"SID"}];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 gatherCFFTopDicts(data,start,cffIndex,strings){var topDictArray=[];for(var iTopDict=0;iTopDict&lt;cffIndex.length;iTopDict+=1){var topDictData=new DataView(new Uint8Array(cffIndex[iTopDict]).buffer);var topDict=parseCFFTopDict(topDictData,strings);topDict._subrs=[];topDict._subrsBias=0;var privateSize=topDict.private[0];var privateOffset=topDict.private[1];if(privateSize!==0&amp;&amp;privateOffset!==0){var privateDict=parseCFFPrivateDict(data,privateOffset+start,privateSize,strings);topDict._defaultWidthX=privateDict.defaultWidthX;topDict._nominalWidthX=privateDict.nominalWidthX;if(privateDict.subrs!==0){var subrOffset=privateOffset+privateDict.subrs;var subrIndex=parseCFFIndex(data,subrOffset+start);topDict._subrs=subrIndex.objects;topDict._subrsBias=calcCFFSubroutineBias(topDict._subrs)}topDict._privateDict=privateDict}topDictArray.push(topDict)}return topDictArray}function parseCFFCharset(data,start,nGlyphs,strings){var sid;var count;var parser=new parse.Parser(data,start);nGlyphs-=1;var charset=[".notdef"];var format=parser.parseCard8();if(format===0){for(var i=0;i&lt;nGlyphs;i+=1){sid=parser.parseSID();charset.push(getCFFString(strings,sid))}}else if(format===1){while(charset.length&lt;=nGlyphs){sid=parser.parseSID();count=parser.parseCard8();for(var i$1=0;i$1&lt;=count;i$1+=1){charset.push(getCFFString(strings,sid));sid+=1}}}else if(format===2){while(charset.length&lt;=nGlyphs){sid=parser.parseSID();count=parser.parseCard16();for(var i$2=0;i$2&lt;=count;i$2+=1){charset.push(getCFFString(strings,sid));sid+=1}}}else{throw new Error("Unknown charset format "+format)}return charset}function parseCFFEncoding(data,start,charset){var code;var enc={};var parser=new parse.Parser(data,start);var format=parser.parseCard8();if(format===0){var nCodes=parser.parseCard8();for(var i=0;i&lt;nCodes;i+=1){code=parser.parseCard8();enc[code]=i}}else if(format===1){var nRanges=parser.parseCard8();code=1;for(var i$1=0;i$1&lt;nRanges;i$1+=1){var first=parser.parseCard8();var nLeft=parser.parseCard8();for(var j=first;j&lt;=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 open=false;var x=0;var y=0;var subrs;var subrsBias;var defaultWidthX;var nominalWidthX;if(font.isCIDFont){var fdIndex=font.tables.cff.topDict._fdSelect[glyph.index];var fdDict=font.tables.cff.topDict._fdArray[fdIndex];subrs=fdDict._subrs;subrsBias=fdDict._subrsBias;defaultWidthX=fdDict._defaultWidthX;nominalWidthX=fdDict._nominalWidthX}else{subrs=font.tables.cff.topDict._subrs;subrsBias=font.tables.cff.topDict._subrsBias;defaultWidthX=font.tables.cff.topDict._defaultWidthX;nominalWidthX=font.tables.cff.topDict._nominalWidthX}var width=defaultWidthX;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&amp;&amp;!haveWidth){width=stack.shift()+nominalWidthX}nStems+=stack.length&gt;&gt;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&lt;code.length){var v=code[i];i+=1;switch(v){case 1:parseStems();break;case 3:parseStems();break;case 4:if(stack.length&gt;1&amp;&amp;!haveWidth){width=stack.shift()+nominalWidthX;haveWidth=true}y+=stack.pop();newContour(x,y);break;case 5:while(stack.length&gt;0){x+=stack.shift();y+=stack.shift();p.lineTo(x,y)}break;case 6:while(stack.length&gt;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&gt;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&gt;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()+subrsBias;subrCode=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)&gt;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&gt;0&amp;&amp;!haveWidth){width=stack.shift()+nominalWidthX;haveWidth=true}if(open){p.closePath();open=false}break;case 18:parseStems();break;case 19:case 20:parseStems();i+=nStems+7&gt;&gt;3;break;case 21:if(stack.length&gt;2&amp;&amp;!haveWidth){width=stack.shift()+nominalWidthX;haveWidth=true}y+=stack.pop();x+=stack.pop();newContour(x,y);break;case 22:if(stack.length&gt;1&amp;&amp;!haveWidth){width=stack.shift()+nominalWidthX;haveWidth=true}x+=stack.pop();newContour(x,y);break;case 23:parseStems();break;case 24:while(stack.length&gt;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&gt;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&gt;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&gt;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&lt;&lt;24|b2&lt;&lt;16)&gt;&gt;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&gt;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&gt;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&lt;32){console.log("Glyph "+glyph.index+": unknown operator "+v)}else if(v&lt;247){stack.push(v-139)}else if(v&lt;251){b1=code[i];i+=1;stack.push((v-247)*256+b1+108)}else if(v&lt;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&lt;&lt;24|b2&lt;&lt;16|b3&lt;&lt;8|b4)/65536)}}}}parse(code);glyph.advanceWidth=width;return p}function parseCFFFDSelect(data,start,nGlyphs,fdArrayCount){var fdSelect=[];var fdIndex;var parser=new parse.Parser(data,start);var format=parser.parseCard8();if(format===0){for(var iGid=0;iGid&lt;nGlyphs;iGid++){fdIndex=parser.parseCard8();if(fdIndex&gt;=fdArrayCount){throw new Error("CFF table CID Font FDSelect has bad FD index value "+fdIndex+" (FD count "+fdArrayCount+")")}fdSelect.push(fdIndex)}}else if(format===3){var nRanges=parser.parseCard16();var first=parser.parseCard16();if(first!==0){throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID "+first)}var next;for(var iRange=0;iRange&lt;nRanges;iRange++){fdIndex=parser.parseCard8();next=parser.parseCard16();if(fdIndex&gt;=fdArrayCount){throw new Error("CFF table CID Font FDSelect has bad FD index value "+fdIndex+" (FD count "+fdArrayCount+")")}if(next&gt;nGlyphs){throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID "+next)}for(;first&lt;next;first++){fdSelect.push(fdIndex)}first=next}if(next!==nGlyphs){throw new Error("CFF Table CID Font FDSelect format 3 range has bad final GID "+next)}}else{throw new Error("CFF Table CID Font FDSelect table has unsupported format "+format)}return fdSelect}function parseCFFTable(data,start,font,opt){font.tables.cff={};var header=parseCFFHeader(data,start);var nameIndex=parseCFFIndex(data,header.endOffset,parse.bytesToString);var topDictIndex=parseCFFIndex(data,nameIndex.endOffset);var stringIndex=parseCFFIndex(data,topDictIndex.endOffset,parse.bytesToString);var globalSubrIndex=parseCFFIndex(data,stringIndex.endOffset);font.gsubrs=globalSubrIndex.objects;font.gsubrsBias=calcCFFSubroutineBias(font.gsubrs);var topDictArray=gatherCFFTopDicts(data,start,topDictIndex.objects,stringIndex.objects);if(topDictArray.length!==1){throw new Error("CFF table has too many fonts in 'FontSet' - count of fonts NameIndex.length = "+topDictArray.length)}var topDict=topDictArray[0];font.tables.cff.topDict=topDict;if(topDict._privateDict){font.defaultWidthX=topDict._privateDict.defaultWidthX;font.nominalWidthX=topDict._privateDict.nominalWidthX}if(topDict.ros[0]!==undefined&amp;&amp;topDict.ros[1]!==undefined){font.isCIDFont=true}if(font.isCIDFont){var fdArrayOffset=topDict.fdArray;var fdSelectOffset=topDict.fdSelect;if(fdArrayOffset===0||fdSelectOffset===0){throw new Error("Font is marked as a CID font, but FDArray and/or FDSelect information is missing")}fdArrayOffset+=start;var fdArrayIndex=parseCFFIndex(data,fdArrayOffset);var fdArray=gatherCFFTopDicts(data,start,fdArrayIndex.objects,stringIndex.objects);topDict._fdArray=fdArray;fdSelectOffset+=start;topDict._fdSelect=parseCFFFDSelect(data,fdSelectOffset,font.numGlyphs,fdArray.length)}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;if(opt.lowMemory){charStringsIndex=parseCFFIndexLowMemory(data,start+topDict.charStrings);font.nGlyphs=charStringsIndex.offsets.length}else{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.GlyphSet(font);if(opt.lowMemory){font._push=function(i){var charString=getCffIndexObject(i,charStringsIndex.offsets,data,start+topDict.charStrings);font.glyphs.push(i,glyphset.cffGlyphLoader(font,i,parseCFFCharstring,charString))}}else{for(var i=0;i&lt;font.nGlyphs;i+=1){var charString=charStringsIndex.objects[i];font.glyphs.push(i,glyphset.cffGlyphLoader(font,i,parseCFFCharstring,charString))}}}function encodeString(s,strings){var sid;var i=cffStandardStrings.indexOf(s);if(i&gt;=0){sid=i}i=strings.indexOf(s);if(i&gt;=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&lt;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&lt;meta.length;i+=1){var entry=meta[i];var value=attrs[entry.name];if(value!==undefined&amp;&amp;!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&lt;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&lt;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&lt;path.commands.length;i+=1){var dx=void 0;var dy=void 0;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&lt;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&lt;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}var cff={parse:parseCFFTable,make:makeCFFTable};function parseHeadTable(data,start){var head={};var p=new parse.Parser(data,start);head.version=p.parseVersion();head.fontRevision=Math.round(p.parseFixed()*1e3)/1e3;head.checkSumAdjustment=p.parseULong();head.magicNumber=p.parseULong();check.argument(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){var timestamp=Math.round((new Date).getTime()/1e3)+2082844800;var createdTimestamp=timestamp;if(options.createdTimestamp){createdTimestamp=options.createdTimestamp+2082844800}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:createdTimestamp},{name:"modified",type:"LONGDATETIME",value:timestamp},{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)}var head={parse:parseHeadTable,make:makeHeadTable};function parseHheaTable(data,start){var hhea={};var p=new parse.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)}var hhea={parse:parseHheaTable,make:makeHheaTable};function parseHmtxTableAll(data,start,numMetrics,numGlyphs,glyphs){var advanceWidth;var leftSideBearing;var p=new parse.Parser(data,start);for(var i=0;i&lt;numGlyphs;i+=1){if(i&lt;numMetrics){advanceWidth=p.parseUShort();leftSideBearing=p.parseShort()}var glyph=glyphs.get(i);glyph.advanceWidth=advanceWidth;glyph.leftSideBearing=leftSideBearing}}function parseHmtxTableOnLowMemory(font,data,start,numMetrics,numGlyphs){font._hmtxTableData={};var advanceWidth;var leftSideBearing;var p=new parse.Parser(data,start);for(var i=0;i&lt;numGlyphs;i+=1){if(i&lt;numMetrics){advanceWidth=p.parseUShort();leftSideBearing=p.parseShort()}font._hmtxTableData[i]={advanceWidth:advanceWidth,leftSideBearing:leftSideBearing}}}function parseHmtxTable(font,data,start,numMetrics,numGlyphs,glyphs,opt){if(opt.lowMemory){parseHmtxTableOnLowMemory(font,data,start,numMetrics,numGlyphs)}else{parseHmtxTableAll(data,start,numMetrics,numGlyphs,glyphs)}}function makeHmtxTable(glyphs){var t=new table.Table("hmtx",[]);for(var i=0;i&lt;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}var hmtx={parse:parseHmtxTable,make:makeHmtxTable};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&lt;tags.length;++i){var pos=stringPool.indexOf(tags[i]);if(pos&lt;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 parse.Parser(data,start);var tableVersion=p.parseULong();check.argument(tableVersion===1,"Unsupported ltag table version.");p.skip("uLong",1);var numTags=p.parseULong();var tags=[];for(var i=0;i&lt;numTags;i++){var tag="";var offset=start+p.parseUShort();var length=p.parseUShort();for(var j=offset;j&lt;offset+length;++j){tag+=String.fromCharCode(data.getInt8(j))}tags.push(tag)}return tags}var ltag={make:makeLtagTable,parse:parseLtagTable};function parseMaxpTable(data,start){var maxp={};var p=new parse.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 maxp={parse:parseMaxpTable,make:makeMaxpTable};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 parse.Parser(data,start);var format=p.parseUShort();var count=p.parseUShort();var stringOffset=p.offset+p.parseUShort();for(var i=0;i&lt;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&amp;&amp;language!==undefined){var text=void 0;if(encoding===utf16){text=decode.UTF16(data,stringOffset+offset,byteLength)}else{text=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&lt;limit;pos++){for(;pos&lt;limit;pos++){for(var k=0;k&lt;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&lt;0){offset=pool.length;var i=0;var len=s.length;for(;i&lt;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);if(isNaN(nameID)){throw new Error('Name table entry "'+key+'" does not exist, see nameTableNames for complete list.')}namesWithNumericKeys[nameID]=names[key];nameIDs.push(nameID)}var macLanguageIds=reverseDict(macLanguages);var windowsLanguageIds=reverseDict(windowsLanguages);var nameRecords=[];var stringPool=[];for(var i=0;i&lt;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&lt;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&lt;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 _name={parse:parseNameTable,make:makeNameTable};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&lt;unicodeRanges.length;i+=1){var range=unicodeRanges[i];if(unicode&gt;=range.begin&amp;&amp;unicode&lt;range.end){return i}}return-1}function parseOS2Table(data,start){var os2={};var p=new parse.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&lt;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&gt;=1){os2.ulCodePageRange1=p.parseULong();os2.ulCodePageRange2=p.parseULong()}if(os2.version&gt;=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)}var os2={parse:parseOS2Table,make:makeOS2Table,unicodeRanges:unicodeRanges,getUnicodeRange:getUnicodeRange};function parsePostTable(data,start){var post={};var p=new parse.Parser(data,start);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(var i=0;i&lt;post.numberOfGlyphs;i++){post.glyphNameIndex[i]=p.parseUShort()}post.names=[];for(var i$1=0;i$1&lt;post.numberOfGlyphs;i$1++){if(post.glyphNameIndex[i$1]&gt;=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(var i$2=0;i$2&lt;post.numberOfGlyphs;i$2++){post.offset[i$2]=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}])}var post={parse:parsePostTable,make:makePostTable};var subtableParsers=new Array(9);subtableParsers[1]=function parseLookup1(){var start=this.offset+this.relativeOffset;var substFormat=this.parseUShort();if(substFormat===1){return{substFormat:1,coverage:this.parsePointer(Parser.coverage),deltaGlyphId:this.parseUShort()}}else if(substFormat===2){return{substFormat:2,coverage:this.parsePointer(Parser.coverage),substitute:this.parseOffset16List()}}check.assert(false,"0x"+start.toString(16)+": lookup type 1 format must be 1 or 2.")};subtableParsers[2]=function parseLookup2(){var substFormat=this.parseUShort();check.argument(substFormat===1,"GSUB Multiple Substitution Subtable identifier-format must be 1");return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),sequences:this.parseListOfLists()}};subtableParsers[3]=function parseLookup3(){var substFormat=this.parseUShort();check.argument(substFormat===1,"GSUB Alternate Substitution Subtable identifier-format must be 1");return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),alternateSets:this.parseListOfLists()}};subtableParsers[4]=function parseLookup4(){var substFormat=this.parseUShort();check.argument(substFormat===1,"GSUB ligature table identifier-format must be 1");return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),ligatureSets:this.parseListOfLists(function(){return{ligGlyph:this.parseUShort(),components:this.parseUShortList(this.parseUShort()-1)}})}};var lookupRecordDesc={sequenceIndex:Parser.uShort,lookupListIndex:Parser.uShort};subtableParsers[5]=function parseLookup5(){var start=this.offset+this.relativeOffset;var substFormat=this.parseUShort();if(substFormat===1){return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),ruleSets:this.parseListOfLists(function(){var glyphCount=this.parseUShort();var substCount=this.parseUShort();return{input:this.parseUShortList(glyphCount-1),lookupRecords:this.parseRecordList(substCount,lookupRecordDesc)}})}}else if(substFormat===2){return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),classDef:this.parsePointer(Parser.classDef),classSets:this.parseListOfLists(function(){var glyphCount=this.parseUShort();var substCount=this.parseUShort();return{classes:this.parseUShortList(glyphCount-1),lookupRecords:this.parseRecordList(substCount,lookupRecordDesc)}})}}else if(substFormat===3){var glyphCount=this.parseUShort();var substCount=this.parseUShort();return{substFormat:substFormat,coverages:this.parseList(glyphCount,Parser.pointer(Parser.coverage)),lookupRecords:this.parseRecordList(substCount,lookupRecordDesc)}}check.assert(false,"0x"+start.toString(16)+": lookup type 5 format must be 1, 2 or 3.")};subtableParsers[6]=function parseLookup6(){var start=this.offset+this.relativeOffset;var substFormat=this.parseUShort();if(substFormat===1){return{substFormat:1,coverage:this.parsePointer(Parser.coverage),chainRuleSets:this.parseListOfLists(function(){return{backtrack:this.parseUShortList(),input:this.parseUShortList(this.parseShort()-1),lookahead:this.parseUShortList(),lookupRecords:this.parseRecordList(lookupRecordDesc)}})}}else if(substFormat===2){return{substFormat:2,coverage:this.parsePointer(Parser.coverage),backtrackClassDef:this.parsePointer(Parser.classDef),inputClassDef:this.parsePointer(Parser.classDef),lookaheadClassDef:this.parsePointer(Parser.classDef),chainClassSet:this.parseListOfLists(function(){return{backtrack:this.parseUShortList(),input:this.parseUShortList(this.parseShort()-1),lookahead:this.parseUShortList(),lookupRecords:this.parseRecordList(lookupRecordDesc)}})}}else if(substFormat===3){return{substFormat:3,backtrackCoverage:this.parseList(Parser.pointer(Parser.coverage)),inputCoverage:this.parseList(Parser.pointer(Parser.coverage)),lookaheadCoverage:this.parseList(Parser.pointer(Parser.coverage)),lookupRecords:this.parseRecordList(lookupRecordDesc)}}check.assert(false,"0x"+start.toString(16)+": lookup type 6 format must be 1, 2 or 3.")};subtableParsers[7]=function parseLookup7(){var substFormat=this.parseUShort();check.argument(substFormat===1,"GSUB Extension Substitution subtable identifier-format must be 1");var extensionLookupType=this.parseUShort();var extensionParser=new Parser(this.data,this.offset+this.parseULong());return{substFormat:1,lookupType:extensionLookupType,extension:subtableParsers[extensionLookupType].call(extensionParser)}};subtableParsers[8]=function parseLookup8(){var substFormat=this.parseUShort();check.argument(substFormat===1,"GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1");return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),backtrackCoverage:this.parseList(Parser.pointer(Parser.coverage)),lookaheadCoverage:this.parseList(Parser.pointer(Parser.coverage)),substitutes:this.parseUShortList()}};function parseGsubTable(data,start){start=start||0;var p=new Parser(data,start);var tableVersion=p.parseVersion(1);check.argument(tableVersion===1||tableVersion===1.1,"Unsupported GSUB table version.");if(tableVersion===1){return{version:tableVersion,scripts:p.parseScriptList(),features:p.parseFeatureList(),lookups:p.parseLookupList(subtableParsers)}}else{return{version:tableVersion,scripts:p.parseScriptList(),features:p.parseFeatureList(),lookups:p.parseLookupList(subtableParsers),variations:p.parseFeatureVariationsList()}}}var subtableMakers=new Array(9);subtableMakers[1]=function makeLookup1(subtable){if(subtable.substFormat===1){return new table.Table("substitutionTable",[{name:"substFormat",type:"USHORT",value:1},{name:"coverage",type:"TABLE",value:new table.Coverage(subtable.coverage)},{name:"deltaGlyphID",type:"USHORT",value:subtable.deltaGlyphId}])}else{return new table.Table("substitutionTable",[{name:"substFormat",type:"USHORT",value:2},{name:"coverage",type:"TABLE",value:new table.Coverage(subtable.coverage)}].concat(table.ushortList("substitute",subtable.substitute)))}};subtableMakers[3]=function makeLookup3(subtable){check.assert(subtable.substFormat===1,"Lookup type 3 substFormat must be 1.");return new table.Table("substitutionTable",[{name:"substFormat",type:"USHORT",value:1},{name:"coverage",type:"TABLE",value:new table.Coverage(subtable.coverage)}].concat(table.tableList("altSet",subtable.alternateSets,function(alternateSet){return new table.Table("alternateSetTable",table.ushortList("alternate",alternateSet))})))};subtableMakers[4]=function makeLookup4(subtable){check.assert(subtable.substFormat===1,"Lookup type 4 substFormat must be 1.");return new table.Table("substitutionTable",[{name:"substFormat",type:"USHORT",value:1},{name:"coverage",type:"TABLE",value:new table.Coverage(subtable.coverage)}].concat(table.tableList("ligSet",subtable.ligatureSets,function(ligatureSet){return new table.Table("ligatureSetTable",table.tableList("ligature",ligatureSet,function(ligature){return new table.Table("ligatureTable",[{name:"ligGlyph",type:"USHORT",value:ligature.ligGlyph}].concat(table.ushortList("component",ligature.components,ligature.components.length+1)))}))})))};function makeGsubTable(gsub){return new table.Table("GSUB",[{name:"version",type:"ULONG",value:65536},{name:"scripts",type:"TABLE",value:new table.ScriptList(gsub.scripts)},{name:"features",type:"TABLE",value:new table.FeatureList(gsub.features)},{name:"lookups",type:"TABLE",value:new table.LookupList(gsub.lookups,subtableMakers)}])}var gsub={parse:parseGsubTable,make:makeGsubTable};function parseMetaTable(data,start){var p=new parse.Parser(data,start);var tableVersion=p.parseULong();check.argument(tableVersion===1,"Unsupported META table version.");p.parseULong();p.parseULong();var numDataMaps=p.parseULong();var tags={};for(var i=0;i&lt;numDataMaps;i++){var tag=p.parseTag();var dataOffset=p.parseULong();var dataLength=p.parseULong();var text=decode.UTF8(data,start+dataOffset,dataLength);tags[tag]=text}return tags}function makeMetaTable(tags){var numTags=Object.keys(tags).length;var stringPool="";var stringPoolOffset=16+numTags*12;var result=new table.Table("meta",[{name:"version",type:"ULONG",value:1},{name:"flags",type:"ULONG",value:0},{name:"offset",type:"ULONG",value:stringPoolOffset},{name:"numTags",type:"ULONG",value:numTags}]);for(var tag in tags){var pos=stringPool.length;stringPool+=tags[tag];result.fields.push({name:"tag "+tag,type:"TAG",value:tag});result.fields.push({name:"offset "+tag,type:"ULONG",value:stringPoolOffset+pos});result.fields.push({name:"length "+tag,type:"ULONG",value:tags[tag].length})}result.fields.push({name:"stringPool",type:"CHARARRAY",value:stringPool});return result}var meta={parse:parseMetaTable,make:makeMetaTable};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&lt;bytes.length;i+=4){sum+=(bytes[i]&lt;&lt;24)+(bytes[i+1]&lt;&lt;16)+(bytes[i+2]&lt;&lt;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&lt;tables.length;i+=1){var t=tables[i];check.argument(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;check.argument(!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&gt;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&lt;chars.length;i+=1){var glyphIndex=font.charToGlyphIndex(chars[i]);if(glyphIndex&gt;0){var glyph=font.glyphs.get(glyphIndex);return glyph.getMetrics()}}return notFoundMetrics}function average(vs){var sum=0;for(var i=0;i&lt;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&lt;font.glyphs.length;i+=1){var glyph=font.glyphs.get(i);var unicode=glyph.unicode|0;if(isNaN(glyph.advanceWidth)){throw new Error("Glyph "+glyph.name+" ("+i+"): advanceWidth is not a number.")}if(firstCharIndex&gt;unicode||firstCharIndex===undefined){if(unicode&gt;0){firstCharIndex=unicode}}if(lastCharIndex&lt;unicode){lastCharIndex=unicode}var position=os2.getUnicodeRange(unicode);if(position&lt;32){ulUnicodeRange1|=1&lt;&lt;position}else if(position&lt;64){ulUnicodeRange2|=1&lt;&lt;position-32}else if(position&lt;96){ulUnicodeRange3|=1&lt;&lt;position-64}else if(position&lt;123){ulUnicodeRange4|=1&lt;&lt;position-96}else{throw new Error("Unicode ranges bits &gt; 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,createdTimestamp:font.createdTimestamp});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(Object.assign({xAvgCharWidth:Math.round(globals.advanceWidthAvg),usFirstCharIndex:firstCharIndex,usLastCharIndex:lastCharIndex,ulUnicodeRange1:ulUnicodeRange1,ulUnicodeRange2:ulUnicodeRange2,ulUnicodeRange3:ulUnicodeRange3,ulUnicodeRange4:ulUnicodeRange4,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},font.tables.os2));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=_name.make(names,languageTags);var ltagTable=languageTags.length&gt;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 metaTable=font.metas&amp;&amp;Object.keys(font.metas).length&gt;0?meta.make(font.metas):undefined;var tables=[headTable,hheaTable,maxpTable,os2Table,nameTable,cmapTable,postTable,cffTable,hmtxTable];if(ltagTable){tables.push(ltagTable)}if(font.tables.gsub){tables.push(gsub.make(font.tables.gsub))}if(metaTable){tables.push(metaTable)}var sfntTable=makeSfntTable(tables);var bytes=sfntTable.encode();var checkSum=computeCheckSum(bytes);var tableFields=sfntTable.fields;var checkSumAdjusted=false;for(var i$1=0;i$1&lt;tableFields.length;i$1+=1){if(tableFields[i$1].name==="head table"){tableFields[i$1].value.checkSumAdjustment=2981146554-checkSum;checkSumAdjusted=true;break}}if(!checkSumAdjusted){throw new Error("Could not find head table with checkSum to adjust.")}return sfntTable}var sfnt={make:makeSfntTable,fontToTable:fontToSfntTable,computeCheckSum:computeCheckSum};function searchTag(arr,tag){var imin=0;var imax=arr.length-1;while(imin&lt;=imax){var imid=imin+imax&gt;&gt;&gt;1;var val=arr[imid].tag;if(val===tag){return imid}else if(val&lt;tag){imin=imid+1}else{imax=imid-1}}return-imin-1}function binSearch(arr,value){var imin=0;var imax=arr.length-1;while(imin&lt;=imax){var imid=imin+imax&gt;&gt;&gt;1;var val=arr[imid];if(val===value){return imid}else if(val&lt;value){imin=imid+1}else{imax=imid-1}}return-imin-1}function searchRange(ranges,value){var range;var imin=0;var imax=ranges.length-1;while(imin&lt;=imax){var imid=imin+imax&gt;&gt;&gt;1;range=ranges[imid];var start=range.start;if(start===value){return range}else if(start&lt;value){imin=imid+1}else{imax=imid-1}}if(imin&gt;0){range=ranges[imin-1];if(value&gt;range.end){return 0}return range}}function Layout(font,tableName){this.font=font;this.tableName=tableName}Layout.prototype={searchTag:searchTag,binSearch:binSearch,getTable:function(create){var layout=this.font.tables[this.tableName];if(!layout&amp;&amp;create){layout=this.font.tables[this.tableName]=this.createDefaultTable()}return layout},getScriptNames:function(){var layout=this.getTable();if(!layout){return[]}return layout.scripts.map(function(script){return script.tag})},getDefaultScriptName:function(){var layout=this.getTable();if(!layout){return}var hasLatn=false;for(var i=0;i&lt;layout.scripts.length;i++){var name=layout.scripts[i].tag;if(name==="DFLT"){return name}if(name==="latn"){hasLatn=true}}if(hasLatn){return"latn"}},getScriptTable:function(script,create){var layout=this.getTable(create);if(layout){script=script||"DFLT";var scripts=layout.scripts;var pos=searchTag(layout.scripts,script);if(pos&gt;=0){return scripts[pos].script}else if(create){var scr={tag:script,script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}};scripts.splice(-1-pos,0,scr);return scr.script}}},getLangSysTable:function(script,language,create){var scriptTable=this.getScriptTable(script,create);if(scriptTable){if(!language||language==="dflt"||language==="DFLT"){return scriptTable.defaultLangSys}var pos=searchTag(scriptTable.langSysRecords,language);if(pos&gt;=0){return scriptTable.langSysRecords[pos].langSys}else if(create){var langSysRecord={tag:language,langSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]}};scriptTable.langSysRecords.splice(-1-pos,0,langSysRecord);return langSysRecord.langSys}}},getFeatureTable:function(script,language,feature,create){var langSysTable=this.getLangSysTable(script,language,create);if(langSysTable){var featureRecord;var featIndexes=langSysTable.featureIndexes;var allFeatures=this.font.tables[this.tableName].features;for(var i=0;i&lt;featIndexes.length;i++){featureRecord=allFeatures[featIndexes[i]];if(featureRecord.tag===feature){return featureRecord.feature}}if(create){var index=allFeatures.length;check.assert(index===0||feature&gt;=allFeatures[index-1].tag,"Features must be added in alphabetical order.");featureRecord={tag:feature,feature:{params:0,lookupListIndexes:[]}};allFeatures.push(featureRecord);featIndexes.push(index);return featureRecord.feature}}},getLookupTables:function(script,language,feature,lookupType,create){var featureTable=this.getFeatureTable(script,language,feature,create);var tables=[];if(featureTable){var lookupTable;var lookupListIndexes=featureTable.lookupListIndexes;var allLookups=this.font.tables[this.tableName].lookups;for(var i=0;i&lt;lookupListIndexes.length;i++){lookupTable=allLookups[lookupListIndexes[i]];if(lookupTable.lookupType===lookupType){tables.push(lookupTable)}}if(tables.length===0&amp;&amp;create){lookupTable={lookupType:lookupType,lookupFlag:0,subtables:[],markFilteringSet:undefined};var index=allLookups.length;allLookups.push(lookupTable);lookupListIndexes.push(index);return[lookupTable]}}return tables},getGlyphClass:function(classDefTable,glyphIndex){switch(classDefTable.format){case 1:if(classDefTable.startGlyph&lt;=glyphIndex&amp;&amp;glyphIndex&lt;classDefTable.startGlyph+classDefTable.classes.length){return classDefTable.classes[glyphIndex-classDefTable.startGlyph]}return 0;case 2:var range=searchRange(classDefTable.ranges,glyphIndex);return range?range.classId:0}},getCoverageIndex:function(coverageTable,glyphIndex){switch(coverageTable.format){case 1:var index=binSearch(coverageTable.glyphs,glyphIndex);return index&gt;=0?index:-1;case 2:var range=searchRange(coverageTable.ranges,glyphIndex);return range?range.index+glyphIndex-range.start:-1}},expandCoverage:function(coverageTable){if(coverageTable.format===1){return coverageTable.glyphs}else{var glyphs=[];var ranges=coverageTable.ranges;for(var i=0;i&lt;ranges.length;i++){var range=ranges[i];var start=range.start;var end=range.end;for(var j=start;j&lt;=end;j++){glyphs.push(j)}}return glyphs}}};function Position(font){Layout.call(this,font,"gpos")}Position.prototype=Layout.prototype;Position.prototype.init=function(){var script=this.getDefaultScriptName();this.defaultKerningTables=this.getKerningTables(script)};Position.prototype.getKerningValue=function(kerningLookups,leftIndex,rightIndex){for(var i=0;i&lt;kerningLookups.length;i++){var subtables=kerningLookups[i].subtables;for(var j=0;j&lt;subtables.length;j++){var subtable=subtables[j];var covIndex=this.getCoverageIndex(subtable.coverage,leftIndex);if(covIndex&lt;0){continue}switch(subtable.posFormat){case 1:var pairSet=subtable.pairSets[covIndex];for(var k=0;k&lt;pairSet.length;k++){var pair=pairSet[k];if(pair.secondGlyph===rightIndex){return pair.value1&amp;&amp;pair.value1.xAdvance||0}}break;case 2:var class1=this.getGlyphClass(subtable.classDef1,leftIndex);var class2=this.getGlyphClass(subtable.classDef2,rightIndex);var pair$1=subtable.classRecords[class1][class2];return pair$1.value1&amp;&amp;pair$1.value1.xAdvance||0}}}return 0};Position.prototype.getKerningTables=function(script,language){if(this.font.tables.gpos){return this.getLookupTables(script,language,"kern",2)}};function Substitution(font){Layout.call(this,font,"gsub")}function arraysEqual(ar1,ar2){var n=ar1.length;if(n!==ar2.length){return false}for(var i=0;i&lt;n;i++){if(ar1[i]!==ar2[i]){return false}}return true}function getSubstFormat(lookupTable,format,defaultSubtable){var subtables=lookupTable.subtables;for(var i=0;i&lt;subtables.length;i++){var subtable=subtables[i];if(subtable.substFormat===format){return subtable}}if(defaultSubtable){subtables.push(defaultSubtable);return defaultSubtable}return undefined}Substitution.prototype=Layout.prototype;Substitution.prototype.createDefaultTable=function(){return{version:1,scripts:[{tag:"DFLT",script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}}],features:[],lookups:[]}};Substitution.prototype.getSingle=function(feature,script,language){var substitutions=[];var lookupTables=this.getLookupTables(script,language,feature,1);for(var idx=0;idx&lt;lookupTables.length;idx++){var subtables=lookupTables[idx].subtables;for(var i=0;i&lt;subtables.length;i++){var subtable=subtables[i];var glyphs=this.expandCoverage(subtable.coverage);var j=void 0;if(subtable.substFormat===1){var delta=subtable.deltaGlyphId;for(j=0;j&lt;glyphs.length;j++){var glyph=glyphs[j];substitutions.push({sub:glyph,by:glyph+delta})}}else{var substitute=subtable.substitute;for(j=0;j&lt;glyphs.length;j++){substitutions.push({sub:glyphs[j],by:substitute[j]})}}}}return substitutions};Substitution.prototype.getAlternates=function(feature,script,language){var alternates=[];var lookupTables=this.getLookupTables(script,language,feature,3);for(var idx=0;idx&lt;lookupTables.length;idx++){var subtables=lookupTables[idx].subtables;for(var i=0;i&lt;subtables.length;i++){var subtable=subtables[i];var glyphs=this.expandCoverage(subtable.coverage);var alternateSets=subtable.alternateSets;for(var j=0;j&lt;glyphs.length;j++){alternates.push({sub:glyphs[j],by:alternateSets[j]})}}}return alternates};Substitution.prototype.getLigatures=function(feature,script,language){var ligatures=[];var lookupTables=this.getLookupTables(script,language,feature,4);for(var idx=0;idx&lt;lookupTables.length;idx++){var subtables=lookupTables[idx].subtables;for(var i=0;i&lt;subtables.length;i++){var subtable=subtables[i];var glyphs=this.expandCoverage(subtable.coverage);var ligatureSets=subtable.ligatureSets;for(var j=0;j&lt;glyphs.length;j++){var startGlyph=glyphs[j];var ligSet=ligatureSets[j];for(var k=0;k&lt;ligSet.length;k++){var lig=ligSet[k];ligatures.push({sub:[startGlyph].concat(lig.components),by:lig.ligGlyph})}}}}return ligatures};Substitution.prototype.addSingle=function(feature,substitution,script,language){var lookupTable=this.getLookupTables(script,language,feature,1,true)[0];var subtable=getSubstFormat(lookupTable,2,{substFormat:2,coverage:{format:1,glyphs:[]},substitute:[]});check.assert(subtable.coverage.format===1,"Ligature: unable to modify coverage table format "+subtable.coverage.format);var coverageGlyph=substitution.sub;var pos=this.binSearch(subtable.coverage.glyphs,coverageGlyph);if(pos&lt;0){pos=-1-pos;subtable.coverage.glyphs.splice(pos,0,coverageGlyph);subtable.substitute.splice(pos,0,0)}subtable.substitute[pos]=substitution.by};Substitution.prototype.addAlternate=function(feature,substitution,script,language){var lookupTable=this.getLookupTables(script,language,feature,3,true)[0];var subtable=getSubstFormat(lookupTable,1,{substFormat:1,coverage:{format:1,glyphs:[]},alternateSets:[]});check.assert(subtable.coverage.format===1,"Ligature: unable to modify coverage table format "+subtable.coverage.format);var coverageGlyph=substitution.sub;var pos=this.binSearch(subtable.coverage.glyphs,coverageGlyph);if(pos&lt;0){pos=-1-pos;subtable.coverage.glyphs.splice(pos,0,coverageGlyph);subtable.alternateSets.splice(pos,0,0)}subtable.alternateSets[pos]=substitution.by};Substitution.prototype.addLigature=function(feature,ligature,script,language){var lookupTable=this.getLookupTables(script,language,feature,4,true)[0];var subtable=lookupTable.subtables[0];if(!subtable){subtable={substFormat:1,coverage:{format:1,glyphs:[]},ligatureSets:[]};lookupTable.subtables[0]=subtable}check.assert(subtable.coverage.format===1,"Ligature: unable to modify coverage table format "+subtable.coverage.format);var coverageGlyph=ligature.sub[0];var ligComponents=ligature.sub.slice(1);var ligatureTable={ligGlyph:ligature.by,components:ligComponents};var pos=this.binSearch(subtable.coverage.glyphs,coverageGlyph);if(pos&gt;=0){var ligatureSet=subtable.ligatureSets[pos];for(var i=0;i&lt;ligatureSet.length;i++){if(arraysEqual(ligatureSet[i].components,ligComponents)){return}}ligatureSet.push(ligatureTable)}else{pos=-1-pos;subtable.coverage.glyphs.splice(pos,0,coverageGlyph);subtable.ligatureSets.splice(pos,0,[ligatureTable])}};Substitution.prototype.getFeature=function(feature,script,language){if(/ss\d\d/.test(feature)){return this.getSingle(feature,script,language)}switch(feature){case"aalt":case"salt":return this.getSingle(feature,script,language).concat(this.getAlternates(feature,script,language));case"dlig":case"liga":case"rlig":return this.getLigatures(feature,script,language)}return undefined};Substitution.prototype.add=function(feature,sub,script,language){if(/ss\d\d/.test(feature)){return this.addSingle(feature,sub,script,language)}switch(feature){case"aalt":case"salt":if(typeof sub.by==="number"){return this.addSingle(feature,sub,script,language)}return this.addAlternate(feature,sub,script,language);case"dlig":case"liga":case"rlig":return this.addLigature(feature,sub,script,language)}return undefined};function isBrowser(){return typeof window!=="undefined"}function nodeBufferToArrayBuffer(buffer){var ab=new ArrayBuffer(buffer.length);var view=new Uint8Array(ab);for(var i=0;i&lt;buffer.length;++i){view[i]=buffer[i]}return ab}function arrayBufferToNodeBuffer(ab){var buffer=new Buffer(ab.byteLength);var view=new Uint8Array(ab);for(var i=0;i&lt;buffer.length;++i){buffer[i]=view[i]}return buffer}function checkArgument(expression,message){if(!expression){throw message}}function parseGlyphCoordinate(p,flag,previousValue,shortVectorBitMask,sameBitMask){var v;if((flag&amp;shortVectorBitMask)&gt;0){v=p.parseByte();if((flag&amp;sameBitMask)===0){v=-v}v=previousValue+v}else{if((flag&amp;sameBitMask)&gt;0){v=previousValue}else{v=previousValue+p.parseShort()}}return v}function parseGlyph(glyph,data,start){var p=new parse.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&gt;0){var endPointIndices=glyph.endPointIndices=[];for(var i=0;i&lt;glyph.numberOfContours;i+=1){endPointIndices.push(p.parseUShort())}glyph.instructionLength=p.parseUShort();glyph.instructions=[];for(var i$1=0;i$1&lt;glyph.instructionLength;i$1+=1){glyph.instructions.push(p.parseByte())}var numberOfCoordinates=endPointIndices[endPointIndices.length-1]+1;flags=[];for(var i$2=0;i$2&lt;numberOfCoordinates;i$2+=1){flag=p.parseByte();flags.push(flag);if((flag&amp;8)&gt;0){var repeatCount=p.parseByte();for(var j=0;j&lt;repeatCount;j+=1){flags.push(flag);i$2+=1}}}check.argument(flags.length===numberOfCoordinates,"Bad flags.");if(endPointIndices.length&gt;0){var points=[];var point;if(numberOfCoordinates&gt;0){for(var i$3=0;i$3&lt;numberOfCoordinates;i$3+=1){flag=flags[i$3];point={};point.onCurve=!!(flag&amp;1);point.lastPointOfContour=endPointIndices.indexOf(i$3)&gt;=0;points.push(point)}var px=0;for(var i$4=0;i$4&lt;numberOfCoordinates;i$4+=1){flag=flags[i$4];point=points[i$4];point.x=parseGlyphCoordinate(p,flag,px,2,16);px=point.x}var py=0;for(var i$5=0;i$5&lt;numberOfCoordinates;i$5+=1){flag=flags[i$5];point=points[i$5];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&amp;1)&gt;0){if((flags&amp;2)&gt;0){component.dx=p.parseShort();component.dy=p.parseShort()}else{component.matchedPoints=[p.parseUShort(),p.parseUShort()]}}else{if((flags&amp;2)&gt;0){component.dx=p.parseChar();component.dy=p.parseChar()}else{component.matchedPoints=[p.parseByte(),p.parseByte()]}}if((flags&amp;8)&gt;0){component.xScale=component.yScale=p.parseF2Dot14()}else if((flags&amp;64)&gt;0){component.xScale=p.parseF2Dot14();component.yScale=p.parseF2Dot14()}else if((flags&amp;128)&gt;0){component.xScale=p.parseF2Dot14();component.scale01=p.parseF2Dot14();component.scale10=p.parseF2Dot14();component.yScale=p.parseF2Dot14()}glyph.components.push(component);moreComponents=!!(flags&amp;32)}if(flags&amp;256){glyph.instructionLength=p.parseUShort();glyph.instructions=[];for(var i$6=0;i$6&lt;glyph.instructionLength;i$6+=1){glyph.instructions.push(p.parseByte())}}}}function transformPoints(points,transform){var newPoints=[];for(var i=0;i&lt;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&lt;points.length;i+=1){var pt=points[i];currentContour.push(pt);if(pt.lastPointOfContour){contours.push(currentContour);currentContour=[]}}check.argument(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 contourIndex=0;contourIndex&lt;contours.length;++contourIndex){var contour=contours[contourIndex];var prev=null;var curr=contour[contour.length-1];var next=contour[0];if(curr.onCurve){p.moveTo(curr.x,curr.y)}else{if(next.onCurve){p.moveTo(next.x,next.y)}else{var start={x:(curr.x+next.x)*.5,y:(curr.y+next.y)*.5};p.moveTo(start.x,start.y)}}for(var i=0;i&lt;contour.length;++i){prev=curr;curr=next;next=contour[(i+1)%contour.length];if(curr.onCurve){p.lineTo(curr.x,curr.y)}else{var prev2=prev;var next2=next;if(!prev.onCurve){prev2={x:(curr.x+prev.x)*.5,y:(curr.y+prev.y)*.5}}if(!next.onCurve){next2={x:(curr.x+next.x)*.5,y:(curr.y+next.y)*.5}}p.quadraticCurveTo(curr.x,curr.y,next2.x,next2.y)}}p.closePath()}return p}function buildPath(glyphs,glyph){if(glyph.isComposite){for(var j=0;j&lt;glyph.components.length;j+=1){var component=glyph.components[j];var componentGlyph=glyphs.get(component.glyphIndex);componentGlyph.getPath();if(componentGlyph.points){var transformedPoints=void 0;if(component.matchedPoints===undefined){transformedPoints=transformPoints(componentGlyph.points,component)}else{if(component.matchedPoints[0]&gt;glyph.points.length-1||component.matchedPoints[1]&gt;componentGlyph.points.length-1){throw Error("Matched points out of range in "+glyph.name)}var firstPt=glyph.points[component.matchedPoints[0]];var secondPt=componentGlyph.points[component.matchedPoints[1]];var transform={xScale:component.xScale,scale01:component.scale01,scale10:component.scale10,yScale:component.yScale,dx:0,dy:0};secondPt=transformPoints([secondPt],transform)[0];transform.dx=firstPt.x-secondPt.x;transform.dy=firstPt.y-secondPt.y;transformedPoints=transformPoints(componentGlyph.points,transform)}glyph.points=glyph.points.concat(transformedPoints)}}}return getPath(glyph.points)}function parseGlyfTableAll(data,start,loca,font){var glyphs=new glyphset.GlyphSet(font);for(var i=0;i&lt;loca.length-1;i+=1){var offset=loca[i];var nextOffset=loca[i+1];if(offset!==nextOffset){glyphs.push(i,glyphset.ttfGlyphLoader(font,i,parseGlyph,data,start+offset,buildPath))}else{glyphs.push(i,glyphset.glyphLoader(font,i))}}return glyphs}function parseGlyfTableOnLowMemory(data,start,loca,font){var glyphs=new glyphset.GlyphSet(font);font._push=function(i){var offset=loca[i];var nextOffset=loca[i+1];if(offset!==nextOffset){glyphs.push(i,glyphset.ttfGlyphLoader(font,i,parseGlyph,data,start+offset,buildPath))}else{glyphs.push(i,glyphset.glyphLoader(font,i))}};return glyphs}function parseGlyfTable(data,start,loca,font,opt){if(opt.lowMemory){return parseGlyfTableOnLowMemory(data,start,loca,font)}else{return parseGlyfTableAll(data,start,loca,font)}}var glyf={getPath:getPath,parse:parseGlyfTable};var instructionTable;var exec;var execGlyph;var execComponent;function Hinting(font){this.font=font;this.getCommands=function(hPoints){return glyf.getPath(hPoints).commands};this._fpgmState=this._prepState=undefined;this._errorState=0}function roundOff(v){return v}function roundToGrid(v){return Math.sign(v)*Math.round(Math.abs(v))}function roundToDoubleGrid(v){return Math.sign(v)*Math.round(Math.abs(v*2))/2}function roundToHalfGrid(v){return Math.sign(v)*(Math.round(Math.abs(v)+.5)-.5)}function roundUpToGrid(v){return Math.sign(v)*Math.ceil(Math.abs(v))}function roundDownToGrid(v){return Math.sign(v)*Math.floor(Math.abs(v))}var roundSuper=function(v){var period=this.srPeriod;var phase=this.srPhase;var threshold=this.srThreshold;var sign=1;if(v&lt;0){v=-v;sign=-1}v+=threshold-phase;v=Math.trunc(v/period)*period;v+=phase;if(v&lt;0){return phase*sign}return v*sign};var xUnitVector={x:1,y:0,axis:"x",distance:function(p1,p2,o1,o2){return(o1?p1.xo:p1.x)-(o2?p2.xo:p2.x)},interpolate:function(p,rp1,rp2,pv){var do1;var do2;var doa1;var doa2;var dm1;var dm2;var dt;if(!pv||pv===this){do1=p.xo-rp1.xo;do2=p.xo-rp2.xo;dm1=rp1.x-rp1.xo;dm2=rp2.x-rp2.xo;doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){p.x=p.xo+(dm1+dm2)/2;return}p.x=p.xo+(dm1*doa2+dm2*doa1)/dt;return}do1=pv.distance(p,rp1,true,true);do2=pv.distance(p,rp2,true,true);dm1=pv.distance(rp1,rp1,false,true);dm2=pv.distance(rp2,rp2,false,true);doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){xUnitVector.setRelative(p,p,(dm1+dm2)/2,pv,true);return}xUnitVector.setRelative(p,p,(dm1*doa2+dm2*doa1)/dt,pv,true)},normalSlope:Number.NEGATIVE_INFINITY,setRelative:function(p,rp,d,pv,org){if(!pv||pv===this){p.x=(org?rp.xo:rp.x)+d;return}var rpx=org?rp.xo:rp.x;var rpy=org?rp.yo:rp.y;var rpdx=rpx+d*pv.x;var rpdy=rpy+d*pv.y;p.x=rpdx+(p.y-rpdy)/pv.normalSlope},slope:0,touch:function(p){p.xTouched=true},touched:function(p){return p.xTouched},untouch:function(p){p.xTouched=false}};var yUnitVector={x:0,y:1,axis:"y",distance:function(p1,p2,o1,o2){return(o1?p1.yo:p1.y)-(o2?p2.yo:p2.y)},interpolate:function(p,rp1,rp2,pv){var do1;var do2;var doa1;var doa2;var dm1;var dm2;var dt;if(!pv||pv===this){do1=p.yo-rp1.yo;do2=p.yo-rp2.yo;dm1=rp1.y-rp1.yo;dm2=rp2.y-rp2.yo;doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){p.y=p.yo+(dm1+dm2)/2;return}p.y=p.yo+(dm1*doa2+dm2*doa1)/dt;return}do1=pv.distance(p,rp1,true,true);do2=pv.distance(p,rp2,true,true);dm1=pv.distance(rp1,rp1,false,true);dm2=pv.distance(rp2,rp2,false,true);doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){yUnitVector.setRelative(p,p,(dm1+dm2)/2,pv,true);return}yUnitVector.setRelative(p,p,(dm1*doa2+dm2*doa1)/dt,pv,true)},normalSlope:0,setRelative:function(p,rp,d,pv,org){if(!pv||pv===this){p.y=(org?rp.yo:rp.y)+d;return}var rpx=org?rp.xo:rp.x;var rpy=org?rp.yo:rp.y;var rpdx=rpx+d*pv.x;var rpdy=rpy+d*pv.y;p.y=rpdy+pv.normalSlope*(p.x-rpdx)},slope:Number.POSITIVE_INFINITY,touch:function(p){p.yTouched=true},touched:function(p){return p.yTouched},untouch:function(p){p.yTouched=false}};Object.freeze(xUnitVector);Object.freeze(yUnitVector);function UnitVector(x,y){this.x=x;this.y=y;this.axis=undefined;this.slope=y/x;this.normalSlope=-x/y;Object.freeze(this)}UnitVector.prototype.distance=function(p1,p2,o1,o2){return this.x*xUnitVector.distance(p1,p2,o1,o2)+this.y*yUnitVector.distance(p1,p2,o1,o2)};UnitVector.prototype.interpolate=function(p,rp1,rp2,pv){var dm1;var dm2;var do1;var do2;var doa1;var doa2;var dt;do1=pv.distance(p,rp1,true,true);do2=pv.distance(p,rp2,true,true);dm1=pv.distance(rp1,rp1,false,true);dm2=pv.distance(rp2,rp2,false,true);doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){this.setRelative(p,p,(dm1+dm2)/2,pv,true);return}this.setRelative(p,p,(dm1*doa2+dm2*doa1)/dt,pv,true)};UnitVector.prototype.setRelative=function(p,rp,d,pv,org){pv=pv||this;var rpx=org?rp.xo:rp.x;var rpy=org?rp.yo:rp.y;var rpdx=rpx+d*pv.x;var rpdy=rpy+d*pv.y;var pvns=pv.normalSlope;var fvs=this.slope;var px=p.x;var py=p.y;p.x=(fvs*px-pvns*rpdx+rpdy-py)/(fvs-pvns);p.y=fvs*(p.x-px)+py};UnitVector.prototype.touch=function(p){p.xTouched=true;p.yTouched=true};function getUnitVector(x,y){var d=Math.sqrt(x*x+y*y);x/=d;y/=d;if(x===1&amp;&amp;y===0){return xUnitVector}else if(x===0&amp;&amp;y===1){return yUnitVector}else{return new UnitVector(x,y)}}function HPoint(x,y,lastPointOfContour,onCurve){this.x=this.xo=Math.round(x*64)/64;this.y=this.yo=Math.round(y*64)/64;this.lastPointOfContour=lastPointOfContour;this.onCurve=onCurve;this.prevPointOnContour=undefined;this.nextPointOnContour=undefined;this.xTouched=false;this.yTouched=false;Object.preventExtensions(this)}HPoint.prototype.nextTouched=function(v){var p=this.nextPointOnContour;while(!v.touched(p)&amp;&amp;p!==this){p=p.nextPointOnContour}return p};HPoint.prototype.prevTouched=function(v){var p=this.prevPointOnContour;while(!v.touched(p)&amp;&amp;p!==this){p=p.prevPointOnContour}return p};var HPZero=Object.freeze(new HPoint(0,0));var defaultState={cvCutIn:17/16,deltaBase:9,deltaShift:.125,loop:1,minDis:1,autoFlip:true};function State(env,prog){this.env=env;this.stack=[];this.prog=prog;switch(env){case"glyf":this.zp0=this.zp1=this.zp2=1;this.rp0=this.rp1=this.rp2=0;case"prep":this.fv=this.pv=this.dpv=xUnitVector;this.round=roundToGrid}}Hinting.prototype.exec=function(glyph,ppem){if(typeof ppem!=="number"){throw new Error("Point size is not a number!")}if(this._errorState&gt;2){return}var font=this.font;var prepState=this._prepState;if(!prepState||prepState.ppem!==ppem){var fpgmState=this._fpgmState;if(!fpgmState){State.prototype=defaultState;fpgmState=this._fpgmState=new State("fpgm",font.tables.fpgm);fpgmState.funcs=[];fpgmState.font=font;if(exports.DEBUG){console.log("---EXEC FPGM---");fpgmState.step=-1}try{exec(fpgmState)}catch(e){console.log("Hinting error in FPGM:"+e);this._errorState=3;return}}State.prototype=fpgmState;prepState=this._prepState=new State("prep",font.tables.prep);prepState.ppem=ppem;var oCvt=font.tables.cvt;if(oCvt){var cvt=prepState.cvt=new Array(oCvt.length);var scale=ppem/font.unitsPerEm;for(var c=0;c&lt;oCvt.length;c++){cvt[c]=oCvt[c]*scale}}else{prepState.cvt=[]}if(exports.DEBUG){console.log("---EXEC PREP---");prepState.step=-1}try{exec(prepState)}catch(e){if(this._errorState&lt;2){console.log("Hinting error in PREP:"+e)}this._errorState=2}}if(this._errorState&gt;1){return}try{return execGlyph(glyph,prepState)}catch(e){if(this._errorState&lt;1){console.log("Hinting error:"+e);console.log("Note: further hinting errors are silenced")}this._errorState=1;return undefined}};execGlyph=function(glyph,prepState){var xScale=prepState.ppem/prepState.font.unitsPerEm;var yScale=xScale;var components=glyph.components;var contours;var gZone;var state;State.prototype=prepState;if(!components){state=new State("glyf",glyph.instructions);if(exports.DEBUG){console.log("---EXEC GLYPH---");state.step=-1}execComponent(glyph,state,xScale,yScale);gZone=state.gZone}else{var font=prepState.font;gZone=[];contours=[];for(var i=0;i&lt;components.length;i++){var c=components[i];var cg=font.glyphs.get(c.glyphIndex);state=new State("glyf",cg.instructions);if(exports.DEBUG){console.log("---EXEC COMP "+i+"---");state.step=-1}execComponent(cg,state,xScale,yScale);var dx=Math.round(c.dx*xScale);var dy=Math.round(c.dy*yScale);var gz=state.gZone;var cc=state.contours;for(var pi=0;pi&lt;gz.length;pi++){var p=gz[pi];p.xTouched=p.yTouched=false;p.xo=p.x=p.x+dx;p.yo=p.y=p.y+dy}var gLen=gZone.length;gZone.push.apply(gZone,gz);for(var j=0;j&lt;cc.length;j++){contours.push(cc[j]+gLen)}}if(glyph.instructions&amp;&amp;!state.inhibitGridFit){state=new State("glyf",glyph.instructions);state.gZone=state.z0=state.z1=state.z2=gZone;state.contours=contours;gZone.push(new HPoint(0,0),new HPoint(Math.round(glyph.advanceWidth*xScale),0));if(exports.DEBUG){console.log("---EXEC COMPOSITE---");state.step=-1}exec(state);gZone.length-=2}}return gZone};execComponent=function(glyph,state,xScale,yScale){var points=glyph.points||[];var pLen=points.length;var gZone=state.gZone=state.z0=state.z1=state.z2=[];var contours=state.contours=[];var cp;for(var i=0;i&lt;pLen;i++){cp=points[i];gZone[i]=new HPoint(cp.x*xScale,cp.y*yScale,cp.lastPointOfContour,cp.onCurve)}var sp;var np;for(var i$1=0;i$1&lt;pLen;i$1++){cp=gZone[i$1];if(!sp){sp=cp;contours.push(i$1)}if(cp.lastPointOfContour){cp.nextPointOnContour=sp;sp.prevPointOnContour=cp;sp=undefined}else{np=gZone[i$1+1];cp.nextPointOnContour=np;np.prevPointOnContour=cp}}if(state.inhibitGridFit){return}if(exports.DEBUG){console.log("PROCESSING GLYPH",state.stack);for(var i$2=0;i$2&lt;pLen;i$2++){console.log(i$2,gZone[i$2].x,gZone[i$2].y)}}gZone.push(new HPoint(0,0),new HPoint(Math.round(glyph.advanceWidth*xScale),0));exec(state);gZone.length-=2;if(exports.DEBUG){console.log("FINISHED GLYPH",state.stack);for(var i$3=0;i$3&lt;pLen;i$3++){console.log(i$3,gZone[i$3].x,gZone[i$3].y)}}};exec=function(state){var prog=state.prog;if(!prog){return}var pLen=prog.length;var ins;for(state.ip=0;state.ip&lt;pLen;state.ip++){if(exports.DEBUG){state.step++}ins=instructionTable[prog[state.ip]];if(!ins){throw new Error("unknown instruction: 0x"+Number(prog[state.ip]).toString(16))}ins(state)}};function initTZone(state){var tZone=state.tZone=new Array(state.gZone.length);for(var i=0;i&lt;tZone.length;i++){tZone[i]=new HPoint(0,0)}}function skip(state,handleElse){var prog=state.prog;var ip=state.ip;var nesting=1;var ins;do{ins=prog[++ip];if(ins===88){nesting++}else if(ins===89){nesting--}else if(ins===64){ip+=prog[ip+1]+1}else if(ins===65){ip+=2*prog[ip+1]+1}else if(ins&gt;=176&amp;&amp;ins&lt;=183){ip+=ins-176+1}else if(ins&gt;=184&amp;&amp;ins&lt;=191){ip+=(ins-184+1)*2}else if(handleElse&amp;&amp;nesting===1&amp;&amp;ins===27){break}}while(nesting&gt;0);state.ip=ip}function SVTCA(v,state){if(exports.DEBUG){console.log(state.step,"SVTCA["+v.axis+"]")}state.fv=state.pv=state.dpv=v}function SPVTCA(v,state){if(exports.DEBUG){console.log(state.step,"SPVTCA["+v.axis+"]")}state.pv=state.dpv=v}function SFVTCA(v,state){if(exports.DEBUG){console.log(state.step,"SFVTCA["+v.axis+"]")}state.fv=v}function SPVTL(a,state){var stack=state.stack;var p2i=stack.pop();var p1i=stack.pop();var p2=state.z2[p2i];var p1=state.z1[p1i];if(exports.DEBUG){console.log("SPVTL["+a+"]",p2i,p1i)}var dx;var dy;if(!a){dx=p1.x-p2.x;dy=p1.y-p2.y}else{dx=p2.y-p1.y;dy=p1.x-p2.x}state.pv=state.dpv=getUnitVector(dx,dy)}function SFVTL(a,state){var stack=state.stack;var p2i=stack.pop();var p1i=stack.pop();var p2=state.z2[p2i];var p1=state.z1[p1i];if(exports.DEBUG){console.log("SFVTL["+a+"]",p2i,p1i)}var dx;var dy;if(!a){dx=p1.x-p2.x;dy=p1.y-p2.y}else{dx=p2.y-p1.y;dy=p1.x-p2.x}state.fv=getUnitVector(dx,dy)}function SPVFS(state){var stack=state.stack;var y=stack.pop();var x=stack.pop();if(exports.DEBUG){console.log(state.step,"SPVFS[]",y,x)}state.pv=state.dpv=getUnitVector(x,y)}function SFVFS(state){var stack=state.stack;var y=stack.pop();var x=stack.pop();if(exports.DEBUG){console.log(state.step,"SPVFS[]",y,x)}state.fv=getUnitVector(x,y)}function GPV(state){var stack=state.stack;var pv=state.pv;if(exports.DEBUG){console.log(state.step,"GPV[]")}stack.push(pv.x*16384);stack.push(pv.y*16384)}function GFV(state){var stack=state.stack;var fv=state.fv;if(exports.DEBUG){console.log(state.step,"GFV[]")}stack.push(fv.x*16384);stack.push(fv.y*16384)}function SFVTPV(state){state.fv=state.pv;if(exports.DEBUG){console.log(state.step,"SFVTPV[]")}}function ISECT(state){var stack=state.stack;var pa0i=stack.pop();var pa1i=stack.pop();var pb0i=stack.pop();var pb1i=stack.pop();var pi=stack.pop();var z0=state.z0;var z1=state.z1;var pa0=z0[pa0i];var pa1=z0[pa1i];var pb0=z1[pb0i];var pb1=z1[pb1i];var p=state.z2[pi];if(exports.DEBUG){console.log("ISECT[], ",pa0i,pa1i,pb0i,pb1i,pi)}var x1=pa0.x;var y1=pa0.y;var x2=pa1.x;var y2=pa1.y;var x3=pb0.x;var y3=pb0.y;var x4=pb1.x;var y4=pb1.y;var div=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4);var f1=x1*y2-y1*x2;var f2=x3*y4-y3*x4;p.x=(f1*(x3-x4)-f2*(x1-x2))/div;p.y=(f1*(y3-y4)-f2*(y1-y2))/div}function SRP0(state){state.rp0=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SRP0[]",state.rp0)}}function SRP1(state){state.rp1=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SRP1[]",state.rp1)}}function SRP2(state){state.rp2=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SRP2[]",state.rp2)}}function SZP0(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SZP0[]",n)}state.zp0=n;switch(n){case 0:if(!state.tZone){initTZone(state)}state.z0=state.tZone;break;case 1:state.z0=state.gZone;break;default:throw new Error("Invalid zone pointer")}}function SZP1(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SZP1[]",n)}state.zp1=n;switch(n){case 0:if(!state.tZone){initTZone(state)}state.z1=state.tZone;break;case 1:state.z1=state.gZone;break;default:throw new Error("Invalid zone pointer")}}function SZP2(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SZP2[]",n)}state.zp2=n;switch(n){case 0:if(!state.tZone){initTZone(state)}state.z2=state.tZone;break;case 1:state.z2=state.gZone;break;default:throw new Error("Invalid zone pointer")}}function SZPS(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SZPS[]",n)}state.zp0=state.zp1=state.zp2=n;switch(n){case 0:if(!state.tZone){initTZone(state)}state.z0=state.z1=state.z2=state.tZone;break;case 1:state.z0=state.z1=state.z2=state.gZone;break;default:throw new Error("Invalid zone pointer")}}function SLOOP(state){state.loop=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SLOOP[]",state.loop)}}function RTG(state){if(exports.DEBUG){console.log(state.step,"RTG[]")}state.round=roundToGrid}function RTHG(state){if(exports.DEBUG){console.log(state.step,"RTHG[]")}state.round=roundToHalfGrid}function SMD(state){var d=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SMD[]",d)}state.minDis=d/64}function ELSE(state){if(exports.DEBUG){console.log(state.step,"ELSE[]")}skip(state,false)}function JMPR(state){var o=state.stack.pop();if(exports.DEBUG){console.log(state.step,"JMPR[]",o)}state.ip+=o-1}function SCVTCI(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SCVTCI[]",n)}state.cvCutIn=n/64}function DUP(state){var stack=state.stack;if(exports.DEBUG){console.log(state.step,"DUP[]")}stack.push(stack[stack.length-1])}function POP(state){if(exports.DEBUG){console.log(state.step,"POP[]")}state.stack.pop()}function CLEAR(state){if(exports.DEBUG){console.log(state.step,"CLEAR[]")}state.stack.length=0}function SWAP(state){var stack=state.stack;var a=stack.pop();var b=stack.pop();if(exports.DEBUG){console.log(state.step,"SWAP[]")}stack.push(a);stack.push(b)}function DEPTH(state){var stack=state.stack;if(exports.DEBUG){console.log(state.step,"DEPTH[]")}stack.push(stack.length)}function LOOPCALL(state){var stack=state.stack;var fn=stack.pop();var c=stack.pop();if(exports.DEBUG){console.log(state.step,"LOOPCALL[]",fn,c)}var cip=state.ip;var cprog=state.prog;state.prog=state.funcs[fn];for(var i=0;i&lt;c;i++){exec(state);if(exports.DEBUG){console.log(++state.step,i+1&lt;c?"next loopcall":"done loopcall",i)}}state.ip=cip;state.prog=cprog}function CALL(state){var fn=state.stack.pop();if(exports.DEBUG){console.log(state.step,"CALL[]",fn)}var cip=state.ip;var cprog=state.prog;state.prog=state.funcs[fn];exec(state);state.ip=cip;state.prog=cprog;if(exports.DEBUG){console.log(++state.step,"returning from",fn)}}function CINDEX(state){var stack=state.stack;var k=stack.pop();if(exports.DEBUG){console.log(state.step,"CINDEX[]",k)}stack.push(stack[stack.length-k])}function MINDEX(state){var stack=state.stack;var k=stack.pop();if(exports.DEBUG){console.log(state.step,"MINDEX[]",k)}stack.push(stack.splice(stack.length-k,1)[0])}function FDEF(state){if(state.env!=="fpgm"){throw new Error("FDEF not allowed here")}var stack=state.stack;var prog=state.prog;var ip=state.ip;var fn=stack.pop();var ipBegin=ip;if(exports.DEBUG){console.log(state.step,"FDEF[]",fn)}while(prog[++ip]!==45){}state.ip=ip;state.funcs[fn]=prog.slice(ipBegin+1,ip)}function MDAP(round,state){var pi=state.stack.pop();var p=state.z0[pi];var fv=state.fv;var pv=state.pv;if(exports.DEBUG){console.log(state.step,"MDAP["+round+"]",pi)}var d=pv.distance(p,HPZero);if(round){d=state.round(d)}fv.setRelative(p,HPZero,d,pv);fv.touch(p);state.rp0=state.rp1=pi}function IUP(v,state){var z2=state.z2;var pLen=z2.length-2;var cp;var pp;var np;if(exports.DEBUG){console.log(state.step,"IUP["+v.axis+"]")}for(var i=0;i&lt;pLen;i++){cp=z2[i];if(v.touched(cp)){continue}pp=cp.prevTouched(v);if(pp===cp){continue}np=cp.nextTouched(v);if(pp===np){v.setRelative(cp,cp,v.distance(pp,pp,false,true),v,true)}v.interpolate(cp,pp,np,v)}}function SHP(a,state){var stack=state.stack;var rpi=a?state.rp1:state.rp2;var rp=(a?state.z0:state.z1)[rpi];var fv=state.fv;var pv=state.pv;var loop=state.loop;var z2=state.z2;while(loop--){var pi=stack.pop();var p=z2[pi];var d=pv.distance(rp,rp,false,true);fv.setRelative(p,p,d,pv);fv.touch(p);if(exports.DEBUG){console.log(state.step,(state.loop&gt;1?"loop "+(state.loop-loop)+": ":"")+"SHP["+(a?"rp1":"rp2")+"]",pi)}}state.loop=1}function SHC(a,state){var stack=state.stack;var rpi=a?state.rp1:state.rp2;var rp=(a?state.z0:state.z1)[rpi];var fv=state.fv;var pv=state.pv;var ci=stack.pop();var sp=state.z2[state.contours[ci]];var p=sp;if(exports.DEBUG){console.log(state.step,"SHC["+a+"]",ci)}var d=pv.distance(rp,rp,false,true);do{if(p!==rp){fv.setRelative(p,p,d,pv)}p=p.nextPointOnContour}while(p!==sp)}function SHZ(a,state){var stack=state.stack;var rpi=a?state.rp1:state.rp2;var rp=(a?state.z0:state.z1)[rpi];var fv=state.fv;var pv=state.pv;var e=stack.pop();if(exports.DEBUG){console.log(state.step,"SHZ["+a+"]",e)}var z;switch(e){case 0:z=state.tZone;break;case 1:z=state.gZone;break;default:throw new Error("Invalid zone")}var p;var d=pv.distance(rp,rp,false,true);var pLen=z.length-2;for(var i=0;i&lt;pLen;i++){p=z[i];fv.setRelative(p,p,d,pv)}}function SHPIX(state){var stack=state.stack;var loop=state.loop;var fv=state.fv;var d=stack.pop()/64;var z2=state.z2;while(loop--){var pi=stack.pop();var p=z2[pi];if(exports.DEBUG){console.log(state.step,(state.loop&gt;1?"loop "+(state.loop-loop)+": ":"")+"SHPIX[]",pi,d)}fv.setRelative(p,p,d);fv.touch(p)}state.loop=1}function IP(state){var stack=state.stack;var rp1i=state.rp1;var rp2i=state.rp2;var loop=state.loop;var rp1=state.z0[rp1i];var rp2=state.z1[rp2i];var fv=state.fv;var pv=state.dpv;var z2=state.z2;while(loop--){var pi=stack.pop();var p=z2[pi];if(exports.DEBUG){console.log(state.step,(state.loop&gt;1?"loop "+(state.loop-loop)+": ":"")+"IP[]",pi,rp1i,"&lt;-&gt;",rp2i)}fv.interpolate(p,rp1,rp2,pv);fv.touch(p)}state.loop=1}function MSIRP(a,state){var stack=state.stack;var d=stack.pop()/64;var pi=stack.pop();var p=state.z1[pi];var rp0=state.z0[state.rp0];var fv=state.fv;var pv=state.pv;fv.setRelative(p,rp0,d,pv);fv.touch(p);if(exports.DEBUG){console.log(state.step,"MSIRP["+a+"]",d,pi)}state.rp1=state.rp0;state.rp2=pi;if(a){state.rp0=pi}}function ALIGNRP(state){var stack=state.stack;var rp0i=state.rp0;var rp0=state.z0[rp0i];var loop=state.loop;var fv=state.fv;var pv=state.pv;var z1=state.z1;while(loop--){var pi=stack.pop();var p=z1[pi];if(exports.DEBUG){console.log(state.step,(state.loop&gt;1?"loop "+(state.loop-loop)+": ":"")+"ALIGNRP[]",pi)}fv.setRelative(p,rp0,0,pv);fv.touch(p)}state.loop=1}function RTDG(state){if(exports.DEBUG){console.log(state.step,"RTDG[]")}state.round=roundToDoubleGrid}function MIAP(round,state){var stack=state.stack;var n=stack.pop();var pi=stack.pop();var p=state.z0[pi];var fv=state.fv;var pv=state.pv;var cv=state.cvt[n];if(exports.DEBUG){console.log(state.step,"MIAP["+round+"]",n,"(",cv,")",pi)}var d=pv.distance(p,HPZero);if(round){if(Math.abs(d-cv)&lt;state.cvCutIn){d=cv}d=state.round(d)}fv.setRelative(p,HPZero,d,pv);if(state.zp0===0){p.xo=p.x;p.yo=p.y}fv.touch(p);state.rp0=state.rp1=pi}function NPUSHB(state){var prog=state.prog;var ip=state.ip;var stack=state.stack;var n=prog[++ip];if(exports.DEBUG){console.log(state.step,"NPUSHB[]",n)}for(var i=0;i&lt;n;i++){stack.push(prog[++ip])}state.ip=ip}function NPUSHW(state){var ip=state.ip;var prog=state.prog;var stack=state.stack;var n=prog[++ip];if(exports.DEBUG){console.log(state.step,"NPUSHW[]",n)}for(var i=0;i&lt;n;i++){var w=prog[++ip]&lt;&lt;8|prog[++ip];if(w&amp;32768){w=-((w^65535)+1)}stack.push(w)}state.ip=ip}function WS(state){var stack=state.stack;var store=state.store;if(!store){store=state.store=[]}var v=stack.pop();var l=stack.pop();if(exports.DEBUG){console.log(state.step,"WS",v,l)}store[l]=v}function RS(state){var stack=state.stack;var store=state.store;var l=stack.pop();if(exports.DEBUG){console.log(state.step,"RS",l)}var v=store&amp;&amp;store[l]||0;stack.push(v)}function WCVTP(state){var stack=state.stack;var v=stack.pop();var l=stack.pop();if(exports.DEBUG){console.log(state.step,"WCVTP",v,l)}state.cvt[l]=v/64}function RCVT(state){var stack=state.stack;var cvte=stack.pop();if(exports.DEBUG){console.log(state.step,"RCVT",cvte)}stack.push(state.cvt[cvte]*64)}function GC(a,state){var stack=state.stack;var pi=stack.pop();var p=state.z2[pi];if(exports.DEBUG){console.log(state.step,"GC["+a+"]",pi)}stack.push(state.dpv.distance(p,HPZero,a,false)*64)}function MD(a,state){var stack=state.stack;var pi2=stack.pop();var pi1=stack.pop();var p2=state.z1[pi2];var p1=state.z0[pi1];var d=state.dpv.distance(p1,p2,a,a);if(exports.DEBUG){console.log(state.step,"MD["+a+"]",pi2,pi1,"-&gt;",d)}state.stack.push(Math.round(d*64))}function MPPEM(state){if(exports.DEBUG){console.log(state.step,"MPPEM[]")}state.stack.push(state.ppem)}function FLIPON(state){if(exports.DEBUG){console.log(state.step,"FLIPON[]")}state.autoFlip=true}function LT(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"LT[]",e2,e1)}stack.push(e1&lt;e2?1:0)}function LTEQ(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"LTEQ[]",e2,e1)}stack.push(e1&lt;=e2?1:0)}function GT(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"GT[]",e2,e1)}stack.push(e1&gt;e2?1:0)}function GTEQ(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"GTEQ[]",e2,e1)}stack.push(e1&gt;=e2?1:0)}function EQ(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"EQ[]",e2,e1)}stack.push(e2===e1?1:0)}function NEQ(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"NEQ[]",e2,e1)}stack.push(e2!==e1?1:0)}function ODD(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,"ODD[]",n)}stack.push(Math.trunc(n)%2?1:0)}function EVEN(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,"EVEN[]",n)}stack.push(Math.trunc(n)%2?0:1)}function IF(state){var test=state.stack.pop();if(exports.DEBUG){console.log(state.step,"IF[]",test)}if(!test){skip(state,true);if(exports.DEBUG){console.log(state.step,"EIF[]")}}}function EIF(state){if(exports.DEBUG){console.log(state.step,"EIF[]")}}function AND(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"AND[]",e2,e1)}stack.push(e2&amp;&amp;e1?1:0)}function OR(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"OR[]",e2,e1)}stack.push(e2||e1?1:0)}function NOT(state){var stack=state.stack;var e=stack.pop();if(exports.DEBUG){console.log(state.step,"NOT[]",e)}stack.push(e?0:1)}function DELTAP123(b,state){var stack=state.stack;var n=stack.pop();var fv=state.fv;var pv=state.pv;var ppem=state.ppem;var base=state.deltaBase+(b-1)*16;var ds=state.deltaShift;var z0=state.z0;if(exports.DEBUG){console.log(state.step,"DELTAP["+b+"]",n,stack)}for(var i=0;i&lt;n;i++){var pi=stack.pop();var arg=stack.pop();var appem=base+((arg&amp;240)&gt;&gt;4);if(appem!==ppem){continue}var mag=(arg&amp;15)-8;if(mag&gt;=0){mag++}if(exports.DEBUG){console.log(state.step,"DELTAPFIX",pi,"by",mag*ds)}var p=z0[pi];fv.setRelative(p,p,mag*ds,pv)}}function SDB(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,"SDB[]",n)}state.deltaBase=n}function SDS(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,"SDS[]",n)}state.deltaShift=Math.pow(.5,n)}function ADD(state){var stack=state.stack;var n2=stack.pop();var n1=stack.pop();if(exports.DEBUG){console.log(state.step,"ADD[]",n2,n1)}stack.push(n1+n2)}function SUB(state){var stack=state.stack;var n2=stack.pop();var n1=stack.pop();if(exports.DEBUG){console.log(state.step,"SUB[]",n2,n1)}stack.push(n1-n2)}function DIV(state){var stack=state.stack;var n2=stack.pop();var n1=stack.pop();if(exports.DEBUG){console.log(state.step,"DIV[]",n2,n1)}stack.push(n1*64/n2)}function MUL(state){var stack=state.stack;var n2=stack.pop();var n1=stack.pop();if(exports.DEBUG){console.log(state.step,"MUL[]",n2,n1)}stack.push(n1*n2/64)}function ABS(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,"ABS[]",n)}stack.push(Math.abs(n))}function NEG(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,"NEG[]",n)}stack.push(-n)}function FLOOR(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,"FLOOR[]",n)}stack.push(Math.floor(n/64)*64)}function CEILING(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,"CEILING[]",n)}stack.push(Math.ceil(n/64)*64)}function ROUND(dt,state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,"ROUND[]")}stack.push(state.round(n/64)*64)}function WCVTF(state){var stack=state.stack;var v=stack.pop();var l=stack.pop();if(exports.DEBUG){console.log(state.step,"WCVTF[]",v,l)}state.cvt[l]=v*state.ppem/state.font.unitsPerEm}function DELTAC123(b,state){var stack=state.stack;var n=stack.pop();var ppem=state.ppem;var base=state.deltaBase+(b-1)*16;var ds=state.deltaShift;if(exports.DEBUG){console.log(state.step,"DELTAC["+b+"]",n,stack)}for(var i=0;i&lt;n;i++){var c=stack.pop();var arg=stack.pop();var appem=base+((arg&amp;240)&gt;&gt;4);if(appem!==ppem){continue}var mag=(arg&amp;15)-8;if(mag&gt;=0){mag++}var delta=mag*ds;if(exports.DEBUG){console.log(state.step,"DELTACFIX",c,"by",delta)}state.cvt[c]+=delta}}function SROUND(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SROUND[]",n)}state.round=roundSuper;var period;switch(n&amp;192){case 0:period=.5;break;case 64:period=1;break;case 128:period=2;break;default:throw new Error("invalid SROUND value")}state.srPeriod=period;switch(n&amp;48){case 0:state.srPhase=0;break;case 16:state.srPhase=.25*period;break;case 32:state.srPhase=.5*period;break;case 48:state.srPhase=.75*period;break;default:throw new Error("invalid SROUND value")}n&amp;=15;if(n===0){state.srThreshold=0}else{state.srThreshold=(n/8-.5)*period}}function S45ROUND(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,"S45ROUND[]",n)}state.round=roundSuper;var period;switch(n&amp;192){case 0:period=Math.sqrt(2)/2;break;case 64:period=Math.sqrt(2);break;case 128:period=2*Math.sqrt(2);break;default:throw new Error("invalid S45ROUND value")}state.srPeriod=period;switch(n&amp;48){case 0:state.srPhase=0;break;case 16:state.srPhase=.25*period;break;case 32:state.srPhase=.5*period;break;case 48:state.srPhase=.75*period;break;default:throw new Error("invalid S45ROUND value")}n&amp;=15;if(n===0){state.srThreshold=0}else{state.srThreshold=(n/8-.5)*period}}function ROFF(state){if(exports.DEBUG){console.log(state.step,"ROFF[]")}state.round=roundOff}function RUTG(state){if(exports.DEBUG){console.log(state.step,"RUTG[]")}state.round=roundUpToGrid}function RDTG(state){if(exports.DEBUG){console.log(state.step,"RDTG[]")}state.round=roundDownToGrid}function SCANCTRL(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SCANCTRL[]",n)}}function SDPVTL(a,state){var stack=state.stack;var p2i=stack.pop();var p1i=stack.pop();var p2=state.z2[p2i];var p1=state.z1[p1i];if(exports.DEBUG){console.log(state.step,"SDPVTL["+a+"]",p2i,p1i)}var dx;var dy;if(!a){dx=p1.x-p2.x;dy=p1.y-p2.y}else{dx=p2.y-p1.y;dy=p1.x-p2.x}state.dpv=getUnitVector(dx,dy)}function GETINFO(state){var stack=state.stack;var sel=stack.pop();var r=0;if(exports.DEBUG){console.log(state.step,"GETINFO[]",sel)}if(sel&amp;1){r=35}if(sel&amp;32){r|=4096}stack.push(r)}function ROLL(state){var stack=state.stack;var a=stack.pop();var b=stack.pop();var c=stack.pop();if(exports.DEBUG){console.log(state.step,"ROLL[]")}stack.push(b);stack.push(a);stack.push(c)}function MAX(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"MAX[]",e2,e1)}stack.push(Math.max(e1,e2))}function MIN(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,"MIN[]",e2,e1)}stack.push(Math.min(e1,e2))}function SCANTYPE(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,"SCANTYPE[]",n)}}function INSTCTRL(state){var s=state.stack.pop();var v=state.stack.pop();if(exports.DEBUG){console.log(state.step,"INSTCTRL[]",s,v)}switch(s){case 1:state.inhibitGridFit=!!v;return;case 2:state.ignoreCvt=!!v;return;default:throw new Error("invalid INSTCTRL[] selector")}}function PUSHB(n,state){var stack=state.stack;var prog=state.prog;var ip=state.ip;if(exports.DEBUG){console.log(state.step,"PUSHB["+n+"]")}for(var i=0;i&lt;n;i++){stack.push(prog[++ip])}state.ip=ip}function PUSHW(n,state){var ip=state.ip;var prog=state.prog;var stack=state.stack;if(exports.DEBUG){console.log(state.ip,"PUSHW["+n+"]")}for(var i=0;i&lt;n;i++){var w=prog[++ip]&lt;&lt;8|prog[++ip];if(w&amp;32768){w=-((w^65535)+1)}stack.push(w)}state.ip=ip}function MDRP_MIRP(indirect,setRp0,keepD,ro,dt,state){var stack=state.stack;var cvte=indirect&amp;&amp;stack.pop();var pi=stack.pop();var rp0i=state.rp0;var rp=state.z0[rp0i];var p=state.z1[pi];var md=state.minDis;var fv=state.fv;var pv=state.dpv;var od;var d;var sign;var cv;d=od=pv.distance(p,rp,true,true);sign=d&gt;=0?1:-1;d=Math.abs(d);if(indirect){cv=state.cvt[cvte];if(ro&amp;&amp;Math.abs(d-cv)&lt;state.cvCutIn){d=cv}}if(keepD&amp;&amp;d&lt;md){d=md}if(ro){d=state.round(d)}fv.setRelative(p,rp,sign*d,pv);fv.touch(p);if(exports.DEBUG){console.log(state.step,(indirect?"MIRP[":"MDRP[")+(setRp0?"M":"m")+(keepD?"&gt;":"_")+(ro?"R":"_")+(dt===0?"Gr":dt===1?"Bl":dt===2?"Wh":"")+"]",indirect?cvte+"("+state.cvt[cvte]+","+cv+")":"",pi,"(d =",od,"-&gt;",sign*d,")")}state.rp1=state.rp0;state.rp2=pi;if(setRp0){state.rp0=pi}}instructionTable=[SVTCA.bind(undefined,yUnitVector),SVTCA.bind(undefined,xUnitVector),SPVTCA.bind(undefined,yUnitVector),SPVTCA.bind(undefined,xUnitVector),SFVTCA.bind(undefined,yUnitVector),SFVTCA.bind(undefined,xUnitVector),SPVTL.bind(undefined,0),SPVTL.bind(undefined,1),SFVTL.bind(undefined,0),SFVTL.bind(undefined,1),SPVFS,SFVFS,GPV,GFV,SFVTPV,ISECT,SRP0,SRP1,SRP2,SZP0,SZP1,SZP2,SZPS,SLOOP,RTG,RTHG,SMD,ELSE,JMPR,SCVTCI,undefined,undefined,DUP,POP,CLEAR,SWAP,DEPTH,CINDEX,MINDEX,undefined,undefined,undefined,LOOPCALL,CALL,FDEF,undefined,MDAP.bind(undefined,0),MDAP.bind(undefined,1),IUP.bind(undefined,yUnitVector),IUP.bind(undefined,xUnitVector),SHP.bind(undefined,0),SHP.bind(undefined,1),SHC.bind(undefined,0),SHC.bind(undefined,1),SHZ.bind(undefined,0),SHZ.bind(undefined,1),SHPIX,IP,MSIRP.bind(undefined,0),MSIRP.bind(undefined,1),ALIGNRP,RTDG,MIAP.bind(undefined,0),MIAP.bind(undefined,1),NPUSHB,NPUSHW,WS,RS,WCVTP,RCVT,GC.bind(undefined,0),GC.bind(undefined,1),undefined,MD.bind(undefined,0),MD.bind(undefined,1),MPPEM,undefined,FLIPON,undefined,undefined,LT,LTEQ,GT,GTEQ,EQ,NEQ,ODD,EVEN,IF,EIF,AND,OR,NOT,DELTAP123.bind(undefined,1),SDB,SDS,ADD,SUB,DIV,MUL,ABS,NEG,FLOOR,CEILING,ROUND.bind(undefined,0),ROUND.bind(undefined,1),ROUND.bind(undefined,2),ROUND.bind(undefined,3),undefined,undefined,undefined,undefined,WCVTF,DELTAP123.bind(undefined,2),DELTAP123.bind(undefined,3),DELTAC123.bind(undefined,1),DELTAC123.bind(undefined,2),DELTAC123.bind(undefined,3),SROUND,S45ROUND,undefined,undefined,ROFF,undefined,RUTG,RDTG,POP,POP,undefined,undefined,undefined,undefined,undefined,SCANCTRL,SDPVTL.bind(undefined,0),SDPVTL.bind(undefined,1),GETINFO,undefined,ROLL,MAX,MIN,SCANTYPE,INSTCTRL,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,PUSHB.bind(undefined,1),PUSHB.bind(undefined,2),PUSHB.bind(undefined,3),PUSHB.bind(undefined,4),PUSHB.bind(undefined,5),PUSHB.bind(undefined,6),PUSHB.bind(undefined,7),PUSHB.bind(undefined,8),PUSHW.bind(undefined,1),PUSHW.bind(undefined,2),PUSHW.bind(undefined,3),PUSHW.bind(undefined,4),PUSHW.bind(undefined,5),PUSHW.bind(undefined,6),PUSHW.bind(undefined,7),PUSHW.bind(undefined,8),MDRP_MIRP.bind(undefined,0,0,0,0,0),MDRP_MIRP.bind(undefined,0,0,0,0,1),MDRP_MIRP.bind(undefined,0,0,0,0,2),MDRP_MIRP.bind(undefined,0,0,0,0,3),MDRP_MIRP.bind(undefined,0,0,0,1,0),MDRP_MIRP.bind(undefined,0,0,0,1,1),MDRP_MIRP.bind(undefined,0,0,0,1,2),MDRP_MIRP.bind(undefined,0,0,0,1,3),MDRP_MIRP.bind(undefined,0,0,1,0,0),MDRP_MIRP.bind(undefined,0,0,1,0,1),MDRP_MIRP.bind(undefined,0,0,1,0,2),MDRP_MIRP.bind(undefined,0,0,1,0,3),MDRP_MIRP.bind(undefined,0,0,1,1,0),MDRP_MIRP.bind(undefined,0,0,1,1,1),MDRP_MIRP.bind(undefined,0,0,1,1,2),MDRP_MIRP.bind(undefined,0,0,1,1,3),MDRP_MIRP.bind(undefined,0,1,0,0,0),MDRP_MIRP.bind(undefined,0,1,0,0,1),MDRP_MIRP.bind(undefined,0,1,0,0,2),MDRP_MIRP.bind(undefined,0,1,0,0,3),MDRP_MIRP.bind(undefined,0,1,0,1,0),MDRP_MIRP.bind(undefined,0,1,0,1,1),MDRP_MIRP.bind(undefined,0,1,0,1,2),MDRP_MIRP.bind(undefined,0,1,0,1,3),MDRP_MIRP.bind(undefined,0,1,1,0,0),MDRP_MIRP.bind(undefined,0,1,1,0,1),MDRP_MIRP.bind(undefined,0,1,1,0,2),MDRP_MIRP.bind(undefined,0,1,1,0,3),MDRP_MIRP.bind(undefined,0,1,1,1,0),MDRP_MIRP.bind(undefined,0,1,1,1,1),MDRP_MIRP.bind(undefined,0,1,1,1,2),MDRP_MIRP.bind(undefined,0,1,1,1,3),MDRP_MIRP.bind(undefined,1,0,0,0,0),MDRP_MIRP.bind(undefined,1,0,0,0,1),MDRP_MIRP.bind(undefined,1,0,0,0,2),MDRP_MIRP.bind(undefined,1,0,0,0,3),MDRP_MIRP.bind(undefined,1,0,0,1,0),MDRP_MIRP.bind(undefined,1,0,0,1,1),MDRP_MIRP.bind(undefined,1,0,0,1,2),MDRP_MIRP.bind(undefined,1,0,0,1,3),MDRP_MIRP.bind(undefined,1,0,1,0,0),MDRP_MIRP.bind(undefined,1,0,1,0,1),MDRP_MIRP.bind(undefined,1,0,1,0,2),MDRP_MIRP.bind(undefined,1,0,1,0,3),MDRP_MIRP.bind(undefined,1,0,1,1,0),MDRP_MIRP.bind(undefined,1,0,1,1,1),MDRP_MIRP.bind(undefined,1,0,1,1,2),MDRP_MIRP.bind(undefined,1,0,1,1,3),MDRP_MIRP.bind(undefined,1,1,0,0,0),MDRP_MIRP.bind(undefined,1,1,0,0,1),MDRP_MIRP.bind(undefined,1,1,0,0,2),MDRP_MIRP.bind(undefined,1,1,0,0,3),MDRP_MIRP.bind(undefined,1,1,0,1,0),MDRP_MIRP.bind(undefined,1,1,0,1,1),MDRP_MIRP.bind(undefined,1,1,0,1,2),MDRP_MIRP.bind(undefined,1,1,0,1,3),MDRP_MIRP.bind(undefined,1,1,1,0,0),MDRP_MIRP.bind(undefined,1,1,1,0,1),MDRP_MIRP.bind(undefined,1,1,1,0,2),MDRP_MIRP.bind(undefined,1,1,1,0,3),MDRP_MIRP.bind(undefined,1,1,1,1,0),MDRP_MIRP.bind(undefined,1,1,1,1,1),MDRP_MIRP.bind(undefined,1,1,1,1,2),MDRP_MIRP.bind(undefined,1,1,1,1,3)];function Token(char){this.char=char;this.state={};this.activeState=null}function ContextRange(startIndex,endOffset,contextName){this.contextName=contextName;this.startIndex=startIndex;this.endOffset=endOffset}function ContextChecker(contextName,checkStart,checkEnd){this.contextName=contextName;this.openRange=null;this.ranges=[];this.checkStart=checkStart;this.checkEnd=checkEnd}function ContextParams(context,currentIndex){this.context=context;this.index=currentIndex;this.length=context.length;this.current=context[currentIndex];this.backtrack=context.slice(0,currentIndex);this.lookahead=context.slice(currentIndex+1)}function Event(eventId){this.eventId=eventId;this.subscribers=[]}function initializeCoreEvents(events){var this$1=this;var coreEvents=["start","end","next","newToken","contextStart","contextEnd","insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD","updateContextsRanges"];coreEvents.forEach(function(eventId){Object.defineProperty(this$1.events,eventId,{value:new Event(eventId)})});if(!!events){coreEvents.forEach(function(eventId){var event=events[eventId];if(typeof event==="function"){this$1.events[eventId].subscribe(event)}})}var requiresContextUpdate=["insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD"];requiresContextUpdate.forEach(function(eventId){this$1.events[eventId].subscribe(this$1.updateContextsRanges)})}function Tokenizer(events){this.tokens=[];this.registeredContexts={};this.contextCheckers=[];this.events={};this.registeredModifiers=[];initializeCoreEvents.call(this,events)}Token.prototype.setState=function(key,value){this.state[key]=value;this.activeState={key:key,value:this.state[key]};return this.activeState};Token.prototype.getState=function(stateId){return this.state[stateId]||null};Tokenizer.prototype.inboundIndex=function(index){return index&gt;=0&amp;&amp;index&lt;this.tokens.length};Tokenizer.prototype.composeRUD=function(RUDs){var this$1=this;var silent=true;var state=RUDs.map(function(RUD){return this$1[RUD[0]].apply(this$1,RUD.slice(1).concat(silent))});var hasFAILObject=function(obj){return typeof obj==="object"&amp;&amp;obj.hasOwnProperty("FAIL")};if(state.every(hasFAILObject)){return{FAIL:"composeRUD: one or more operations hasn't completed successfully",report:state.filter(hasFAILObject)}}this.dispatch("composeRUD",[state.filter(function(op){return!hasFAILObject(op)})])};Tokenizer.prototype.replaceRange=function(startIndex,offset,tokens,silent){offset=offset!==null?offset:this.tokens.length;var isTokenType=tokens.every(function(token){return token instanceof Token});if(!isNaN(startIndex)&amp;&amp;this.inboundIndex(startIndex)&amp;&amp;isTokenType){var replaced=this.tokens.splice.apply(this.tokens,[startIndex,offset].concat(tokens));if(!silent){this.dispatch("replaceToken",[startIndex,offset,tokens])}return[replaced,tokens]}else{return{FAIL:"replaceRange: invalid tokens or startIndex."}}};Tokenizer.prototype.replaceToken=function(index,token,silent){if(!isNaN(index)&amp;&amp;this.inboundIndex(index)&amp;&amp;token instanceof Token){var replaced=this.tokens.splice(index,1,token);if(!silent){this.dispatch("replaceToken",[index,token])}return[replaced[0],token]}else{return{FAIL:"replaceToken: invalid token or index."}}};Tokenizer.prototype.removeRange=function(startIndex,offset,silent){offset=!isNaN(offset)?offset:this.tokens.length;var tokens=this.tokens.splice(startIndex,offset);if(!silent){this.dispatch("removeRange",[tokens,startIndex,offset])}return tokens};Tokenizer.prototype.removeToken=function(index,silent){if(!isNaN(index)&amp;&amp;this.inboundIndex(index)){var token=this.tokens.splice(index,1);if(!silent){this.dispatch("removeToken",[token,index])}return token}else{return{FAIL:"removeToken: invalid token index."}}};Tokenizer.prototype.insertToken=function(tokens,index,silent){var tokenType=tokens.every(function(token){return token instanceof Token});if(tokenType){this.tokens.splice.apply(this.tokens,[index,0].concat(tokens));if(!silent){this.dispatch("insertToken",[tokens,index])}return tokens}else{return{FAIL:"insertToken: invalid token(s)."}}};Tokenizer.prototype.registerModifier=function(modifierId,condition,modifier){this.events.newToken.subscribe(function(token,contextParams){var conditionParams=[token,contextParams];var canApplyModifier=condition===null||condition.apply(this,conditionParams)===true;var modifierParams=[token,contextParams];if(canApplyModifier){var newStateValue=modifier.apply(this,modifierParams);token.setState(modifierId,newStateValue)}});this.registeredModifiers.push(modifierId)};Event.prototype.subscribe=function(eventHandler){if(typeof eventHandler==="function"){return this.subscribers.push(eventHandler)-1}else{return{FAIL:"invalid '"+this.eventId+"' event handler"}}};Event.prototype.unsubscribe=function(subsId){this.subscribers.splice(subsId,1)};ContextParams.prototype.setCurrentIndex=function(index){this.index=index;this.current=this.context[index];this.backtrack=this.context.slice(0,index);this.lookahead=this.context.slice(index+1)};ContextParams.prototype.get=function(offset){switch(true){case offset===0:return this.current;case offset&lt;0&amp;&amp;Math.abs(offset)&lt;=this.backtrack.length:return this.backtrack.slice(offset)[0];case offset&gt;0&amp;&amp;offset&lt;=this.lookahead.length:return this.lookahead[offset-1];default:return null}};Tokenizer.prototype.rangeToText=function(range){if(range instanceof ContextRange){return this.getRangeTokens(range).map(function(token){return token.char}).join("")}};Tokenizer.prototype.getText=function(){return this.tokens.map(function(token){return token.char}).join("")};Tokenizer.prototype.getContext=function(contextName){var context=this.registeredContexts[contextName];return!!context?context:null};Tokenizer.prototype.on=function(eventName,eventHandler){var event=this.events[eventName];if(!!event){return event.subscribe(eventHandler)}else{return null}};Tokenizer.prototype.dispatch=function(eventName,args){var this$1=this;var event=this.events[eventName];if(event instanceof Event){event.subscribers.forEach(function(subscriber){subscriber.apply(this$1,args||[])})}};Tokenizer.prototype.registerContextChecker=function(contextName,contextStartCheck,contextEndCheck){if(!!this.getContext(contextName)){return{FAIL:"context name '"+contextName+"' is already registered."}}if(typeof contextStartCheck!=="function"){return{FAIL:"missing context start check."}}if(typeof contextEndCheck!=="function"){return{FAIL:"missing context end check."}}var contextCheckers=new ContextChecker(contextName,contextStartCheck,contextEndCheck);this.registeredContexts[contextName]=contextCheckers;this.contextCheckers.push(contextCheckers);return contextCheckers};Tokenizer.prototype.getRangeTokens=function(range){var endIndex=range.startIndex+range.endOffset;return[].concat(this.tokens.slice(range.startIndex,endIndex))};Tokenizer.prototype.getContextRanges=function(contextName){var context=this.getContext(contextName);if(!!context){return context.ranges}else{return{FAIL:"context checker '"+contextName+"' is not registered."}}};Tokenizer.prototype.resetContextsRanges=function(){var registeredContexts=this.registeredContexts;for(var contextName in registeredContexts){if(registeredContexts.hasOwnProperty(contextName)){var context=registeredContexts[contextName];context.ranges=[]}}};Tokenizer.prototype.updateContextsRanges=function(){this.resetContextsRanges();var chars=this.tokens.map(function(token){return token.char});for(var i=0;i&lt;chars.length;i++){var contextParams=new ContextParams(chars,i);this.runContextCheck(contextParams)}this.dispatch("updateContextsRanges",[this.registeredContexts])};Tokenizer.prototype.setEndOffset=function(offset,contextName){var startIndex=this.getContext(contextName).openRange.startIndex;var range=new ContextRange(startIndex,offset,contextName);var ranges=this.getContext(contextName).ranges;range.rangeId=contextName+"."+ranges.length;ranges.push(range);this.getContext(contextName).openRange=null;return range};Tokenizer.prototype.runContextCheck=function(contextParams){var this$1=this;var index=contextParams.index;this.contextCheckers.forEach(function(contextChecker){var contextName=contextChecker.contextName;var openRange=this$1.getContext(contextName).openRange;if(!openRange&amp;&amp;contextChecker.checkStart(contextParams)){openRange=new ContextRange(index,null,contextName);this$1.getContext(contextName).openRange=openRange;this$1.dispatch("contextStart",[contextName,index])}if(!!openRange&amp;&amp;contextChecker.checkEnd(contextParams)){var offset=index-openRange.startIndex+1;var range=this$1.setEndOffset(offset,contextName);this$1.dispatch("contextEnd",[contextName,range])}})};Tokenizer.prototype.tokenize=function(text){this.tokens=[];this.resetContextsRanges();var chars=Array.from(text);this.dispatch("start");for(var i=0;i&lt;chars.length;i++){var char=chars[i];var contextParams=new ContextParams(chars,i);this.dispatch("next",[contextParams]);this.runContextCheck(contextParams);var token=new Token(char);this.tokens.push(token);this.dispatch("newToken",[token,contextParams])}this.dispatch("end",[this.tokens]);return this.tokens};function isArabicChar(c){return/[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c)}function isIsolatedArabicChar(char){return/[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(char)}function isTashkeelArabicChar(char){return/[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(char)}function isLatinChar(c){return/[A-z]/.test(c)}function isWhiteSpace(c){return/\s/.test(c)}function FeatureQuery(font){this.font=font;this.features={}}function SubstitutionAction(action){this.id=action.id;this.tag=action.tag;this.substitution=action.substitution}function lookupCoverage(glyphIndex,coverage){if(!glyphIndex){return-1}switch(coverage.format){case 1:return coverage.glyphs.indexOf(glyphIndex);case 2:var ranges=coverage.ranges;for(var i=0;i&lt;ranges.length;i++){var range=ranges[i];if(glyphIndex&gt;=range.start&amp;&amp;glyphIndex&lt;=range.end){var offset=glyphIndex-range.start;return range.index+offset}}break;default:return-1}return-1}function singleSubstitutionFormat1(glyphIndex,subtable){var substituteIndex=lookupCoverage(glyphIndex,subtable.coverage);if(substituteIndex===-1){return null}return glyphIndex+subtable.deltaGlyphId}function singleSubstitutionFormat2(glyphIndex,subtable){var substituteIndex=lookupCoverage(glyphIndex,subtable.coverage);if(substituteIndex===-1){return null}return subtable.substitute[substituteIndex]}function lookupCoverageList(coverageList,contextParams){var lookupList=[];for(var i=0;i&lt;coverageList.length;i++){var coverage=coverageList[i];var glyphIndex=contextParams.current;glyphIndex=Array.isArray(glyphIndex)?glyphIndex[0]:glyphIndex;var lookupIndex=lookupCoverage(glyphIndex,coverage);if(lookupIndex!==-1){lookupList.push(lookupIndex)}}if(lookupList.length!==coverageList.length){return-1}return lookupList}function chainingSubstitutionFormat3(contextParams,subtable){var lookupsCount=subtable.inputCoverage.length+subtable.lookaheadCoverage.length+subtable.backtrackCoverage.length;if(contextParams.context.length&lt;lookupsCount){return[]}var inputLookups=lookupCoverageList(subtable.inputCoverage,contextParams);if(inputLookups===-1){return[]}var lookaheadOffset=subtable.inputCoverage.length-1;if(contextParams.lookahead.length&lt;subtable.lookaheadCoverage.length){return[]}var lookaheadContext=contextParams.lookahead.slice(lookaheadOffset);while(lookaheadContext.length&amp;&amp;isTashkeelArabicChar(lookaheadContext[0].char)){lookaheadContext.shift()}var lookaheadParams=new ContextParams(lookaheadContext,0);var lookaheadLookups=lookupCoverageList(subtable.lookaheadCoverage,lookaheadParams);var backtrackContext=[].concat(contextParams.backtrack);backtrackContext.reverse();while(backtrackContext.length&amp;&amp;isTashkeelArabicChar(backtrackContext[0].char)){backtrackContext.shift()}if(backtrackContext.length&lt;subtable.backtrackCoverage.length){return[]}var backtrackParams=new ContextParams(backtrackContext,0);var backtrackLookups=lookupCoverageList(subtable.backtrackCoverage,backtrackParams);var contextRulesMatch=inputLookups.length===subtable.inputCoverage.length&amp;&amp;lookaheadLookups.length===subtable.lookaheadCoverage.length&amp;&amp;backtrackLookups.length===subtable.backtrackCoverage.length;var substitutions=[];if(contextRulesMatch){for(var i=0;i&lt;subtable.lookupRecords.length;i++){var lookupRecord=subtable.lookupRecords[i];var lookupListIndex=lookupRecord.lookupListIndex;var lookupTable=this.getLookupByIndex(lookupListIndex);for(var s=0;s&lt;lookupTable.subtables.length;s++){var subtable$1=lookupTable.subtables[s];var lookup=this.getLookupMethod(lookupTable,subtable$1);var substitutionType=this.getSubstitutionType(lookupTable,subtable$1);if(substitutionType==="12"){for(var n=0;n&lt;inputLookups.length;n++){var glyphIndex=contextParams.get(n);var substitution=lookup(glyphIndex);if(substitution){substitutions.push(substitution)}}}}}}return substitutions}function ligatureSubstitutionFormat1(contextParams,subtable){var glyphIndex=contextParams.current;var ligSetIndex=lookupCoverage(glyphIndex,subtable.coverage);if(ligSetIndex===-1){return null}var ligature;var ligatureSet=subtable.ligatureSets[ligSetIndex];for(var s=0;s&lt;ligatureSet.length;s++){ligature=ligatureSet[s];for(var l=0;l&lt;ligature.components.length;l++){var lookaheadItem=contextParams.lookahead[l];var component=ligature.components[l];if(lookaheadItem!==component){break}if(l===ligature.components.length-1){return ligature}}}return null}function decompositionSubstitutionFormat1(glyphIndex,subtable){var substituteIndex=lookupCoverage(glyphIndex,subtable.coverage);if(substituteIndex===-1){return null}return subtable.sequences[substituteIndex]}FeatureQuery.prototype.getDefaultScriptFeaturesIndexes=function(){var scripts=this.font.tables.gsub.scripts;for(var s=0;s&lt;scripts.length;s++){var script=scripts[s];if(script.tag==="DFLT"){return script.script.defaultLangSys.featureIndexes}}return[]};FeatureQuery.prototype.getScriptFeaturesIndexes=function(scriptTag){var tables=this.font.tables;if(!tables.gsub){return[]}if(!scriptTag){return this.getDefaultScriptFeaturesIndexes()}var scripts=this.font.tables.gsub.scripts;for(var i=0;i&lt;scripts.length;i++){var script=scripts[i];if(script.tag===scriptTag&amp;&amp;script.script.defaultLangSys){return script.script.defaultLangSys.featureIndexes}else{var langSysRecords=script.langSysRecords;if(!!langSysRecords){for(var j=0;j&lt;langSysRecords.length;j++){var langSysRecord=langSysRecords[j];if(langSysRecord.tag===scriptTag){var langSys=langSysRecord.langSys;return langSys.featureIndexes}}}}}return this.getDefaultScriptFeaturesIndexes()};FeatureQuery.prototype.mapTagsToFeatures=function(features,scriptTag){var tags={};for(var i=0;i&lt;features.length;i++){var tag=features[i].tag;var feature=features[i].feature;tags[tag]=feature}this.features[scriptTag].tags=tags};FeatureQuery.prototype.getScriptFeatures=function(scriptTag){var features=this.features[scriptTag];if(this.features.hasOwnProperty(scriptTag)){return features}var featuresIndexes=this.getScriptFeaturesIndexes(scriptTag);if(!featuresIndexes){return null}var gsub=this.font.tables.gsub;features=featuresIndexes.map(function(index){return gsub.features[index]});this.features[scriptTag]=features;this.mapTagsToFeatures(features,scriptTag);return features};FeatureQuery.prototype.getSubstitutionType=function(lookupTable,subtable){var lookupType=lookupTable.lookupType.toString();var substFormat=subtable.substFormat.toString();return lookupType+substFormat};FeatureQuery.prototype.getLookupMethod=function(lookupTable,subtable){var this$1=this;var substitutionType=this.getSubstitutionType(lookupTable,subtable);switch(substitutionType){case"11":return function(glyphIndex){return singleSubstitutionFormat1.apply(this$1,[glyphIndex,subtable])};case"12":return function(glyphIndex){return singleSubstitutionFormat2.apply(this$1,[glyphIndex,subtable])};case"63":return function(contextParams){return chainingSubstitutionFormat3.apply(this$1,[contextParams,subtable])};case"41":return function(contextParams){return ligatureSubstitutionFormat1.apply(this$1,[contextParams,subtable])};case"21":return function(glyphIndex){return decompositionSubstitutionFormat1.apply(this$1,[glyphIndex,subtable])};default:throw new Error("lookupType: "+lookupTable.lookupType+" - "+"substFormat: "+subtable.substFormat+" "+"is not yet supported")}};FeatureQuery.prototype.lookupFeature=function(query){var contextParams=query.contextParams;var currentIndex=contextParams.index;var feature=this.getFeature({tag:query.tag,script:query.script});if(!feature){return new Error("font '"+this.font.names.fullName.en+"' "+"doesn't support feature '"+query.tag+"' "+"for script '"+query.script+"'.")}var lookups=this.getFeatureLookups(feature);var substitutions=[].concat(contextParams.context);for(var l=0;l&lt;lookups.length;l++){var lookupTable=lookups[l];var subtables=this.getLookupSubtables(lookupTable);for(var s=0;s&lt;subtables.length;s++){var subtable=subtables[s];var substType=this.getSubstitutionType(lookupTable,subtable);var lookup=this.getLookupMethod(lookupTable,subtable);var substitution=void 0;switch(substType){case"11":substitution=lookup(contextParams.current);if(substitution){substitutions.splice(currentIndex,1,new SubstitutionAction({id:11,tag:query.tag,substitution:substitution}))}break;case"12":substitution=lookup(contextParams.current);if(substitution){substitutions.splice(currentIndex,1,new SubstitutionAction({id:12,tag:query.tag,substitution:substitution}))}break;case"63":substitution=lookup(contextParams);if(Array.isArray(substitution)&amp;&amp;substitution.length){substitutions.splice(currentIndex,1,new SubstitutionAction({id:63,tag:query.tag,substitution:substitution}))}break;case"41":substitution=lookup(contextParams);if(substitution){substitutions.splice(currentIndex,1,new SubstitutionAction({id:41,tag:query.tag,substitution:substitution}))}break;case"21":substitution=lookup(contextParams.current);if(substitution){substitutions.splice(currentIndex,1,new SubstitutionAction({id:21,tag:query.tag,substitution:substitution}))}break}contextParams=new ContextParams(substitutions,currentIndex);if(Array.isArray(substitution)&amp;&amp;!substitution.length){continue}substitution=null}}return substitutions.length?substitutions:null};FeatureQuery.prototype.supports=function(query){if(!query.script){return false}this.getScriptFeatures(query.script);var supportedScript=this.features.hasOwnProperty(query.script);if(!query.tag){return supportedScript}var supportedFeature=this.features[query.script].some(function(feature){return feature.tag===query.tag});return supportedScript&amp;&amp;supportedFeature};FeatureQuery.prototype.getLookupSubtables=function(lookupTable){return lookupTable.subtables||null};FeatureQuery.prototype.getLookupByIndex=function(index){var lookups=this.font.tables.gsub.lookups;return lookups[index]||null};FeatureQuery.prototype.getFeatureLookups=function(feature){return feature.lookupListIndexes.map(this.getLookupByIndex.bind(this))};FeatureQuery.prototype.getFeature=function getFeature(query){if(!this.font){return{FAIL:"No font was found"}}if(!this.features.hasOwnProperty(query.script)){this.getScriptFeatures(query.script)}var scriptFeatures=this.features[query.script];if(!scriptFeatures){return{FAIL:"No feature for script "+query.script}}if(!scriptFeatures.tags[query.tag]){return null}return this.features[query.script].tags[query.tag]};function arabicWordStartCheck(contextParams){var char=contextParams.current;var prevChar=contextParams.get(-1);return prevChar===null&amp;&amp;isArabicChar(char)||!isArabicChar(prevChar)&amp;&amp;isArabicChar(char)}function arabicWordEndCheck(contextParams){var nextChar=contextParams.get(1);return nextChar===null||!isArabicChar(nextChar)}var arabicWordCheck={startCheck:arabicWordStartCheck,endCheck:arabicWordEndCheck};function arabicSentenceStartCheck(contextParams){var char=contextParams.current;var prevChar=contextParams.get(-1);return(isArabicChar(char)||isTashkeelArabicChar(char))&amp;&amp;!isArabicChar(prevChar)}function arabicSentenceEndCheck(contextParams){var nextChar=contextParams.get(1);switch(true){case nextChar===null:return true;case!isArabicChar(nextChar)&amp;&amp;!isTashkeelArabicChar(nextChar):var nextIsWhitespace=isWhiteSpace(nextChar);if(!nextIsWhitespace){return true}if(nextIsWhitespace){var arabicCharAhead=false;arabicCharAhead=contextParams.lookahead.some(function(c){return isArabicChar(c)||isTashkeelArabicChar(c)});if(!arabicCharAhead){return true}}break;default:return false}}var arabicSentenceCheck={startCheck:arabicSentenceStartCheck,endCheck:arabicSentenceEndCheck};function singleSubstitutionFormat1$1(action,tokens,index){tokens[index].setState(action.tag,action.substitution)}function singleSubstitutionFormat2$1(action,tokens,index){tokens[index].setState(action.tag,action.substitution)}function chainingSubstitutionFormat3$1(action,tokens,index){action.substitution.forEach(function(subst,offset){var token=tokens[index+offset];token.setState(action.tag,subst)})}function ligatureSubstitutionFormat1$1(action,tokens,index){var token=tokens[index];token.setState(action.tag,action.substitution.ligGlyph);var compsCount=action.substitution.components.length;for(var i=0;i&lt;compsCount;i++){token=tokens[index+i+1];token.setState("deleted",true)}}var SUBSTITUTIONS={11:singleSubstitutionFormat1$1,12:singleSubstitutionFormat2$1,63:chainingSubstitutionFormat3$1,41:ligatureSubstitutionFormat1$1};function applySubstitution(action,tokens,index){if(action instanceof SubstitutionAction&amp;&amp;SUBSTITUTIONS[action.id]){SUBSTITUTIONS[action.id](action,tokens,index)}}function willConnectPrev(charContextParams){var backtrack=[].concat(charContextParams.backtrack);for(var i=backtrack.length-1;i&gt;=0;i--){var prevChar=backtrack[i];var isolated=isIsolatedArabicChar(prevChar);var tashkeel=isTashkeelArabicChar(prevChar);if(!isolated&amp;&amp;!tashkeel){return true}if(isolated){return false}}return false}function willConnectNext(charContextParams){if(isIsolatedArabicChar(charContextParams.current)){return false}for(var i=0;i&lt;charContextParams.lookahead.length;i++){var nextChar=charContextParams.lookahead[i];var tashkeel=isTashkeelArabicChar(nextChar);if(!tashkeel){return true}}return false}function arabicPresentationForms(range){var this$1=this;var script="arab";var tags=this.featuresTags[script];var tokens=this.tokenizer.getRangeTokens(range);if(tokens.length===1){return}var contextParams=new ContextParams(tokens.map(function(token){return token.getState("glyphIndex")}),0);var charContextParams=new ContextParams(tokens.map(function(token){return token.char}),0);tokens.forEach(function(token,index){if(isTashkeelArabicChar(token.char)){return}contextParams.setCurrentIndex(index);charContextParams.setCurrentIndex(index);var CONNECT=0;if(willConnectPrev(charContextParams)){CONNECT|=1}if(willConnectNext(charContextParams)){CONNECT|=2}var tag;switch(CONNECT){case 1:tag="fina";break;case 2:tag="init";break;case 3:tag="medi";break}if(tags.indexOf(tag)===-1){return}var substitutions=this$1.query.lookupFeature({tag:tag,script:script,contextParams:contextParams});if(substitutions instanceof Error){return console.info(substitutions.message)}substitutions.forEach(function(action,index){if(action instanceof SubstitutionAction){applySubstitution(action,tokens,index);contextParams.context[index]=action.substitution}})})}function getContextParams(tokens,index){var context=tokens.map(function(token){return token.activeState.value});return new ContextParams(context,index||0)}function arabicRequiredLigatures(range){var this$1=this;var script="arab";var tokens=this.tokenizer.getRangeTokens(range);var contextParams=getContextParams(tokens);contextParams.context.forEach(function(glyphIndex,index){contextParams.setCurrentIndex(index);var substitutions=this$1.query.lookupFeature({tag:"rlig",script:script,contextParams:contextParams});if(substitutions.length){substitutions.forEach(function(action){return applySubstitution(action,tokens,index)});contextParams=getContextParams(tokens)}})}function latinWordStartCheck(contextParams){var char=contextParams.current;var prevChar=contextParams.get(-1);return prevChar===null&amp;&amp;isLatinChar(char)||!isLatinChar(prevChar)&amp;&amp;isLatinChar(char)}function latinWordEndCheck(contextParams){var nextChar=contextParams.get(1);return nextChar===null||!isLatinChar(nextChar)}var latinWordCheck={startCheck:latinWordStartCheck,endCheck:latinWordEndCheck};function getContextParams$1(tokens,index){var context=tokens.map(function(token){return token.activeState.value});return new ContextParams(context,index||0)}function latinLigature(range){var this$1=this;var script="latn";var tokens=this.tokenizer.getRangeTokens(range);var contextParams=getContextParams$1(tokens);contextParams.context.forEach(function(glyphIndex,index){contextParams.setCurrentIndex(index);var substitutions=this$1.query.lookupFeature({tag:"liga",script:script,contextParams:contextParams});if(substitutions.length){substitutions.forEach(function(action){return applySubstitution(action,tokens,index)});contextParams=getContextParams$1(tokens)}})}function Bidi(baseDir){this.baseDir=baseDir||"ltr";this.tokenizer=new Tokenizer;this.featuresTags={}}Bidi.prototype.setText=function(text){this.text=text};Bidi.prototype.contextChecks={latinWordCheck:latinWordCheck,arabicWordCheck:arabicWordCheck,arabicSentenceCheck:arabicSentenceCheck};function registerContextChecker(checkId){var check=this.contextChecks[checkId+"Check"];return this.tokenizer.registerContextChecker(checkId,check.startCheck,check.endCheck)}function tokenizeText(){registerContextChecker.call(this,"latinWord");registerContextChecker.call(this,"arabicWord");registerContextChecker.call(this,"arabicSentence");return this.tokenizer.tokenize(this.text)}function reverseArabicSentences(){var this$1=this;var ranges=this.tokenizer.getContextRanges("arabicSentence");ranges.forEach(function(range){var rangeTokens=this$1.tokenizer.getRangeTokens(range);this$1.tokenizer.replaceRange(range.startIndex,range.endOffset,rangeTokens.reverse())})}Bidi.prototype.registerFeatures=function(script,tags){var this$1=this;var supportedTags=tags.filter(function(tag){return this$1.query.supports({script:script,tag:tag})});if(!this.featuresTags.hasOwnProperty(script)){this.featuresTags[script]=supportedTags}else{this.featuresTags[script]=this.featuresTags[script].concat(supportedTags)}};Bidi.prototype.applyFeatures=function(font,features){if(!font){throw new Error("No valid font was provided to apply features")}if(!this.query){this.query=new FeatureQuery(font)}for(var f=0;f&lt;features.length;f++){var feature=features[f];if(!this.query.supports({script:feature.script})){continue}this.registerFeatures(feature.script,feature.tags)}};Bidi.prototype.registerModifier=function(modifierId,condition,modifier){this.tokenizer.registerModifier(modifierId,condition,modifier)};function checkGlyphIndexStatus(){if(this.tokenizer.registeredModifiers.indexOf("glyphIndex")===-1){throw new Error("glyphIndex modifier is required to apply "+"arabic presentation features.")}}function applyArabicPresentationForms(){var this$1=this;var script="arab";if(!this.featuresTags.hasOwnProperty(script)){return}checkGlyphIndexStatus.call(this);var ranges=this.tokenizer.getContextRanges("arabicWord");ranges.forEach(function(range){arabicPresentationForms.call(this$1,range)})}function applyArabicRequireLigatures(){var this$1=this;var script="arab";if(!this.featuresTags.hasOwnProperty(script)){return}var tags=this.featuresTags[script];if(tags.indexOf("rlig")===-1){return}checkGlyphIndexStatus.call(this);var ranges=this.tokenizer.getContextRanges("arabicWord");ranges.forEach(function(range){arabicRequiredLigatures.call(this$1,range)})}function applyLatinLigatures(){var this$1=this;var script="latn";if(!this.featuresTags.hasOwnProperty(script)){return}var tags=this.featuresTags[script];if(tags.indexOf("liga")===-1){return}checkGlyphIndexStatus.call(this);var ranges=this.tokenizer.getContextRanges("latinWord");ranges.forEach(function(range){latinLigature.call(this$1,range)})}Bidi.prototype.checkContextReady=function(contextId){return!!this.tokenizer.getContext(contextId)};Bidi.prototype.applyFeaturesToContexts=function(){if(this.checkContextReady("arabicWord")){applyArabicPresentationForms.call(this);applyArabicRequireLigatures.call(this)}if(this.checkContextReady("latinWord")){applyLatinLigatures.call(this)}if(this.checkContextReady("arabicSentence")){reverseArabicSentences.call(this)}};Bidi.prototype.processText=function(text){if(!this.text||this.text!==text){this.setText(text);tokenizeText.call(this);this.applyFeaturesToContexts()}};Bidi.prototype.getBidiText=function(text){this.processText(text);return this.tokenizer.getText()};Bidi.prototype.getTextGlyphs=function(text){this.processText(text);var indexes=[];for(var i=0;i&lt;this.tokenizer.tokens.length;i++){var token=this.tokenizer.tokens[i];if(token.state.deleted){continue}var index=token.activeState.value;indexes.push(Array.isArray(index)?index[0]:index)}return indexes};function Font(options){options=options||{};options.tables=options.tables||{};if(!options.empty){checkArgument(options.familyName,"When creating a new Font object, familyName is required.");checkArgument(options.styleName,"When creating a new Font object, styleName is required.");checkArgument(options.unitsPerEm,"When creating a new Font object, unitsPerEm is required.");checkArgument(options.ascender,"When creating a new Font object, ascender is required.");checkArgument(options.descender&lt;=0,"When creating a new Font object, negative descender value is required.");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).replace(/\s/g,"")},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.createdTimestamp=options.createdTimestamp;this.tables=Object.assign(options.tables,{os2:Object.assign({usWeightClass:options.weightClass||this.usWeightClasses.MEDIUM,usWidthClass:options.widthClass||this.usWidthClasses.MEDIUM,fsSelection:options.fsSelection||this.fsSelectionValues.REGULAR},options.tables.os2)})}this.supported=true;this.glyphs=new glyphset.GlyphSet(this,options.glyphs||[]);this.encoding=new DefaultEncoding(this);this.position=new Position(this);this.substitution=new Substitution(this);this.tables=this.tables||{};this._push=null;this._hmtxTableData={};Object.defineProperty(this,"hinting",{get:function(){if(this._hinting){return this._hinting}if(this.outlinesFormat==="truetype"){return this._hinting=new Hinting(this)}}})}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.updateFeatures=function(options){return this.defaultRenderOptions.features.map(function(feature){if(feature.script==="latn"){return{script:"latn",tags:feature.tags.filter(function(tag){return options[tag]})}}else{return feature}})};Font.prototype.stringToGlyphs=function(s,options){var this$1=this;var bidi=new Bidi;var charToGlyphIndexMod=function(token){return this$1.charToGlyphIndex(token.char)};bidi.registerModifier("glyphIndex",null,charToGlyphIndexMod);var features=options?this.updateFeatures(options.features):this.defaultRenderOptions.features;bidi.applyFeatures(this,features);var indexes=bidi.getTextGlyphs(s);var length=indexes.length;var glyphs=new Array(length);var notdef=this.glyphs.get(0);for(var i=0;i&lt;length;i+=1){glyphs[i]=this.glyphs.get(indexes[i])||notdef}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.position.defaultKerningTables;if(gposKerning){return this.position.getKerningValue(gposKerning,leftGlyph,rightGlyph)}return this.kerningPairs[leftGlyph+","+rightGlyph]||0};Font.prototype.defaultRenderOptions={kerning:true,features:[{script:"arab",tags:["init","medi","fina","rlig"]},{script:"latn",tags:["liga","rlig"]}]};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=Object.assign({},this.defaultRenderOptions,options);var fontScale=1/this.unitsPerEm*fontSize;var glyphs=this.stringToGlyphs(text,options);var kerningLookups;if(options.kerning){var script=options.script||this.position.getDefaultScriptName();kerningLookups=this.position.getKerningTables(script,options.language)}for(var i=0;i&lt;glyphs.length;i+=1){var glyph=glyphs[i];callback.call(this,glyph,x,y,fontSize,options);if(glyph.advanceWidth){x+=glyph.advanceWidth*fontScale}if(options.kerning&amp;&amp;i&lt;glyphs.length-1){var kerningValue=kerningLookups?this.position.getKerningValue(kerningLookups,glyph.index,glyphs[i+1].index):this.getKerningValue(glyph,glyphs[i+1]);x+=kerningValue*fontScale}if(options.letterSpacing){x+=options.letterSpacing*fontSize}else if(options.tracking){x+=options.tracking/1e3*fontSize}}return x};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,options,this);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,options,this);glyphPaths.push(glyphPath)});return glyphPaths};Font.prototype.getAdvanceWidth=function(text,fontSize,options){return this.forEachGlyph(text,0,0,fontSize,options,function(){})};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 _this=this;function assert(predicate,message){}function assertNamePresent(name){var englishName=_this.getEnglishName(name);assert(englishName&amp;&amp;englishName.trim().length&gt;0)}assertNamePresent("fontFamily");assertNamePresent("weightName");assertNamePresent("manufacturer");assertNamePresent("copyright");assertNamePresent("version");assert(this.unitsPerEm&gt;0)};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&lt;bytes.length;i++){intArray[i]=bytes[i]}return buffer};Font.prototype.download=function(fileName){var familyName=this.getEnglishName("fontFamily");var styleName=this.getEnglishName("fontSubfamily");fileName=fileName||familyName.replace(/\s/g,"")+"-"+styleName+".otf";var arrayBuffer=this.toArrayBuffer();if(isBrowser()){window.URL=window.URL||window.webkitURL;if(window.URL){var dataView=new DataView(arrayBuffer);var blob=new Blob([dataView],{type:"font/opentype"});var link=document.createElement("a");link.href=window.URL.createObjectURL(blob);link.download=fileName;var event=document.createEvent("MouseEvents");event.initEvent("click",true,false);link.dispatchEvent(event)}else{console.warn("Font file could not be downloaded. Try using a different browser.")}}else{var fs=require("fs");var buffer=arrayBufferToNodeBuffer(arrayBuffer);fs.writeFileSync(fileName,buffer)}};Font.prototype.fsSelectionValues={ITALIC:1,UNDERSCORE:2,NEGATIVE:4,OUTLINED:8,STRIKEOUT:16,BOLD:32,REGULAR:64,USER_TYPO_METRICS:128,WWS:256,OBLIQUE:512};Font.prototype.usWidthClasses={ULTRA_CONDENSED:1,EXTRA_CONDENSED:2,CONDENSED:3,SEMI_CONDENSED:4,MEDIUM:5,SEMI_EXPANDED:6,EXPANDED:7,EXTRA_EXPANDED:8,ULTRA_EXPANDED:9};Font.prototype.usWeightClasses={THIN:100,EXTRA_LIGHT:200,LIGHT:300,NORMAL:400,MEDIUM:500,SEMI_BOLD:600,BOLD:700,EXTRA_BOLD:800,BLACK:900};function addName(name,names){var nameString=JSON.stringify(name);var nameID=256;for(var nameKey in names){var n=parseInt(nameKey);if(!n||n&lt;256){continue}if(JSON.stringify(names[nameKey])===nameString){return n}if(nameID&lt;=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&lt;&lt;16},{name:"defaultValue_"+n,type:"FIXED",value:axis.defaultValue&lt;&lt;16},{name:"maxValue_"+n,type:"FIXED",value:axis.maxValue&lt;&lt;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 parse.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&lt;axes.length;++i){var axisTag=axes[i].tag;fields.push({name:"axis_"+n+" "+axisTag,type:"FIXED",value:inst.coordinates[axisTag]&lt;&lt;16})}return fields}function parseFvarInstance(data,start,axes,names){var inst={};var p=new parse.Parser(data,start);inst.name=names[p.parseUShort()]||{};p.skip("uShort",1);inst.coordinates={};for(var i=0;i&lt;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&lt;fvar.axes.length;i++){result.fields=result.fields.concat(makeFvarAxis(i,fvar.axes[i],names))}for(var j=0;j&lt;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 parse.Parser(data,start);var tableVersion=p.parseULong();check.argument(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&lt;axisCount;i++){axes.push(parseFvarAxis(data,start+offsetToData+i*axisSize,names))}var instances=[];var instanceStart=start+offsetToData+axisCount*axisSize;for(var j=0;j&lt;instanceCount;j++){instances.push(parseFvarInstance(data,instanceStart+j*instanceSize,axes,names))}return{axes:axes,instances:instances}}var fvar={make:makeFvarTable,parse:parseFvarTable};var subtableParsers$1=new Array(10);subtableParsers$1[1]=function parseLookup1(){var start=this.offset+this.relativeOffset;var posformat=this.parseUShort();if(posformat===1){return{posFormat:1,coverage:this.parsePointer(Parser.coverage),value:this.parseValueRecord()}}else if(posformat===2){return{posFormat:2,coverage:this.parsePointer(Parser.coverage),values:this.parseValueRecordList()}}check.assert(false,"0x"+start.toString(16)+": GPOS lookup type 1 format must be 1 or 2.")};subtableParsers$1[2]=function parseLookup2(){var start=this.offset+this.relativeOffset;var posFormat=this.parseUShort();check.assert(posFormat===1||posFormat===2,"0x"+start.toString(16)+": GPOS lookup type 2 format must be 1 or 2.");var coverage=this.parsePointer(Parser.coverage);var valueFormat1=this.parseUShort();var valueFormat2=this.parseUShort();if(posFormat===1){return{posFormat:posFormat,coverage:coverage,valueFormat1:valueFormat1,valueFormat2:valueFormat2,pairSets:this.parseList(Parser.pointer(Parser.list(function(){return{secondGlyph:this.parseUShort(),value1:this.parseValueRecord(valueFormat1),value2:this.parseValueRecord(valueFormat2)}})))}}else if(posFormat===2){var classDef1=this.parsePointer(Parser.classDef);var classDef2=this.parsePointer(Parser.classDef);var class1Count=this.parseUShort();var class2Count=this.parseUShort();return{posFormat:posFormat,coverage:coverage,valueFormat1:valueFormat1,valueFormat2:valueFormat2,classDef1:classDef1,classDef2:classDef2,class1Count:class1Count,class2Count:class2Count,classRecords:this.parseList(class1Count,Parser.list(class2Count,function(){return{value1:this.parseValueRecord(valueFormat1),value2:this.parseValueRecord(valueFormat2)}}))}}};subtableParsers$1[3]=function parseLookup3(){return{error:"GPOS Lookup 3 not supported"}};subtableParsers$1[4]=function parseLookup4(){return{error:"GPOS Lookup 4 not supported"}};subtableParsers$1[5]=function parseLookup5(){return{error:"GPOS Lookup 5 not supported"}};subtableParsers$1[6]=function parseLookup6(){return{error:"GPOS Lookup 6 not supported"}};subtableParsers$1[7]=function parseLookup7(){return{error:"GPOS Lookup 7 not supported"}};subtableParsers$1[8]=function parseLookup8(){return{error:"GPOS Lookup 8 not supported"}};subtableParsers$1[9]=function parseLookup9(){return{error:"GPOS Lookup 9 not supported"}};function parseGposTable(data,start){start=start||0;var p=new Parser(data,start);var tableVersion=p.parseVersion(1);check.argument(tableVersion===1||tableVersion===1.1,"Unsupported GPOS table version "+tableVersion);if(tableVersion===1){return{version:tableVersion,scripts:p.parseScriptList(),features:p.parseFeatureList(),lookups:p.parseLookupList(subtableParsers$1)}}else{return{version:tableVersion,scripts:p.parseScriptList(),features:p.parseFeatureList(),lookups:p.parseLookupList(subtableParsers$1),variations:p.parseFeatureVariationsList()}}}var subtableMakers$1=new Array(10);function makeGposTable(gpos){return new table.Table("GPOS",[{name:"version",type:"ULONG",value:65536},{name:"scripts",type:"TABLE",value:new table.ScriptList(gpos.scripts)},{name:"features",type:"TABLE",value:new table.FeatureList(gpos.features)},{name:"lookups",type:"TABLE",value:new table.LookupList(gpos.lookups,subtableMakers$1)}])}var gpos={parse:parseGposTable,make:makeGposTable};function parseWindowsKernTable(p){var pairs={};p.skip("uShort");var subtableVersion=p.parseUShort();check.argument(subtableVersion===0,"Unsupported kern sub-table version.");p.skip("uShort",2);var nPairs=p.parseUShort();p.skip("uShort",3);for(var i=0;i&lt;nPairs;i+=1){var leftIndex=p.parseUShort();var rightIndex=p.parseUShort();var value=p.parseShort();pairs[leftIndex+","+rightIndex]=value}return pairs}function parseMacKernTable(p){var pairs={};p.skip("uShort");var nTables=p.parseULong();if(nTables&gt;1){console.warn("Only the first kern subtable is supported.")}p.skip("uLong");var coverage=p.parseUShort();var subtableVersion=coverage&amp;255;p.skip("uShort");if(subtableVersion===0){var nPairs=p.parseUShort();p.skip("uShort",3);for(var i=0;i&lt;nPairs;i+=1){var leftIndex=p.parseUShort();var rightIndex=p.parseUShort();var value=p.parseShort();pairs[leftIndex+","+rightIndex]=value}}return pairs}function parseKernTable(data,start){var p=new parse.Parser(data,start);var tableVersion=p.parseUShort();if(tableVersion===0){return parseWindowsKernTable(p)}else if(tableVersion===1){return parseMacKernTable(p)}else{throw new Error("Unsupported kern table version ("+tableVersion+").")}}var kern={parse:parseKernTable};function parseLocaTable(data,start,numGlyphs,shortVersion){var p=new parse.Parser(data,start);var parseFn=shortVersion?p.parseUShort:p.parseULong;var glyphOffsets=[];for(var i=0;i&lt;numGlyphs+1;i+=1){var glyphOffset=parseFn.call(p);if(shortVersion){glyphOffset*=2}glyphOffsets.push(glyphOffset)}return glyphOffsets}var loca={parse:parseLocaTable};function loadFromFile(path,callback){var fs=require("fs");fs.readFile(path,function(err,buffer){if(err){return callback(err.message)}callback(null,nodeBufferToArrayBuffer(buffer))})}function loadFromUrl(url,callback){var request=new XMLHttpRequest;request.open("get",url,true);request.responseType="arraybuffer";request.onload=function(){if(request.response){return callback(null,request.response)}else{return callback("Font could not be loaded: "+request.statusText)}};request.onerror=function(){callback("Font could not be loaded")};request.send()}function parseOpenTypeTableEntries(data,numTables){var tableEntries=[];var p=12;for(var i=0;i&lt;numTables;i+=1){var tag=parse.getTag(data,p);var checksum=parse.getULong(data,p+4);var offset=parse.getULong(data,p+8);var length=parse.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&lt;numTables;i+=1){var tag=parse.getTag(data,p);var offset=parse.getULong(data,p+4);var compLength=parse.getULong(data,p+8);var origLength=parse.getULong(data,p+12);var compression=void 0;if(compLength&lt;origLength){compression="WOFF"}else{compression=false}tableEntries.push({tag:tag,offset:offset,compression:compression,compressedLength:compLength,length: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.length);tinyInflate(inBuffer,outBuffer);if(outBuffer.byteLength!==tableEntry.length){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,opt){opt=opt===undefined||opt===null?{}:opt;var indexToLocFormat;var ltagTable;var font=new Font({empty:true});var data=new DataView(buffer,0);var numTables;var tableEntries=[];var signature=parse.getTag(data,0);if(signature===String.fromCharCode(0,1,0,0)||signature==="true"||signature==="typ1"){font.outlinesFormat="truetype";numTables=parse.getUShort(data,4);tableEntries=parseOpenTypeTableEntries(data,numTables)}else if(signature==="OTTO"){font.outlinesFormat="cff";numTables=parse.getUShort(data,4);tableEntries=parseOpenTypeTableEntries(data,numTables)}else if(signature==="wOFF"){var flavor=parse.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=parse.getUShort(data,12);tableEntries=parseWOFFTableEntries(data,numTables)}else{throw new Error("Unsupported OpenType signature "+signature)}var cffTableEntry;var fvarTableEntry;var glyfTableEntry;var gposTableEntry;var gsubTableEntry;var hmtxTableEntry;var kernTableEntry;var locaTableEntry;var nameTableEntry;var metaTableEntry;var p;for(var i=0;i&lt;numTables;i+=1){var tableEntry=tableEntries[i];var table=void 0;switch(tableEntry.tag){case"cmap":table=uncompressTable(data,tableEntry);font.tables.cmap=cmap.parse(table.data,table.offset);font.encoding=new CmapEncoding(font.tables.cmap);break;case"cvt ":table=uncompressTable(data,tableEntry);p=new parse.Parser(table.data,table.offset);font.tables.cvt=p.parseShortList(tableEntry.length/2);break;case"fvar":fvarTableEntry=tableEntry;break;case"fpgm":table=uncompressTable(data,tableEntry);p=new parse.Parser(table.data,table.offset);font.tables.fpgm=p.parseByteList(tableEntry.length);break;case"head":table=uncompressTable(data,tableEntry);font.tables.head=head.parse(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=hhea.parse(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=maxp.parse(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=os2.parse(table.data,table.offset);break;case"post":table=uncompressTable(data,tableEntry);font.tables.post=post.parse(table.data,table.offset);font.glyphNames=new GlyphNames(font.tables.post);break;case"prep":table=uncompressTable(data,tableEntry);p=new parse.Parser(table.data,table.offset);font.tables.prep=p.parseByteList(tableEntry.length);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;case"GSUB":gsubTableEntry=tableEntry;break;case"meta":metaTableEntry=tableEntry;break}}var nameTable=uncompressTable(data,nameTableEntry);font.tables.name=_name.parse(nameTable.data,nameTable.offset,ltagTable);font.names=font.tables.name;if(glyfTableEntry&amp;&amp;locaTableEntry){var shortVersion=indexToLocFormat===0;var locaTable=uncompressTable(data,locaTableEntry);var locaOffsets=loca.parse(locaTable.data,locaTable.offset,font.numGlyphs,shortVersion);var glyfTable=uncompressTable(data,glyfTableEntry);font.glyphs=glyf.parse(glyfTable.data,glyfTable.offset,locaOffsets,font,opt)}else if(cffTableEntry){var cffTable=uncompressTable(data,cffTableEntry);cff.parse(cffTable.data,cffTable.offset,font,opt)}else{throw new Error("Font doesn't contain TrueType or CFF outlines.")}var hmtxTable=uncompressTable(data,hmtxTableEntry);hmtx.parse(font,hmtxTable.data,hmtxTable.offset,font.numberOfHMetrics,font.numGlyphs,font.glyphs,opt);addGlyphNames(font,opt);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);font.tables.gpos=gpos.parse(gposTable.data,gposTable.offset);font.position.init()}if(gsubTableEntry){var gsubTable=uncompressTable(data,gsubTableEntry);font.tables.gsub=gsub.parse(gsubTable.data,gsubTable.offset)}if(fvarTableEntry){var fvarTable=uncompressTable(data,fvarTableEntry);font.tables.fvar=fvar.parse(fvarTable.data,fvarTable.offset,font.names)}if(metaTableEntry){var metaTable=uncompressTable(data,metaTableEntry);font.tables.meta=meta.parse(metaTable.data,metaTable.offset);font.metas=font.tables.meta}return font}function load(url,callback,opt){var isNode=typeof window==="undefined";var loadFn=isNode?loadFromFile:loadFromUrl;return new Promise(function(resolve,reject){loadFn(url,function(err,arrayBuffer){if(err){if(callback){return callback(err)}else{reject(err)}}var font;try{font=parseBuffer(arrayBuffer,opt)}catch(e){if(callback){return callback(e,null)}else{reject(e)}}if(callback){return callback(null,font)}else{resolve(font)}})})}function loadSync(url,opt){var fs=require("fs");var buffer=fs.readFileSync(url);return parseBuffer(nodeBufferToArrayBuffer(buffer),opt)}var opentype=Object.freeze({__proto__:null,Font:Font,Glyph:Glyph,Path:Path,BoundingBox:BoundingBox,_parse:parse,parse:parseBuffer,load:load,loadSync:loadSync});exports.BoundingBox=BoundingBox;exports.Font=Font;exports.Glyph=Glyph;exports.Path=Path;exports._parse=parse;exports.default=opentype;exports.load=load;exports.loadSync=loadSync;exports.parse=parseBuffer;Object.defineProperty(exports,"__esModule",{value:true})});(function(global){"use strict";if(!global["console"]){global.console={}}var console=global.console;if(!console["log"]){console.log=function(args){}}if(!console["debug"]){console.debug=console.log}if(!console["info"]){console.info=console.log}if(!console["warn"]){console.warn=console.log}if(!console["error"]){console.error=console.log}if(!window.requestAnimationFrame){window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame;window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.msCancelAnimationFrame}try{global.Float32Array;if(!global.Float32Array){global.Float32Array=Array}}catch(exception){global.Float32Array=WebGLFloatArray||Array}})(window);(function(define,global){"use strict";define(["module"],function(module){var freeze,reduceArray,slice,envFreeze,falseRx,undef;falseRx=/^false$/i;envFreeze="WHEN_PARANOID";if(module&amp;&amp;typeof module.config==="function"){freeze=module.config().paranoid!==false}else if(typeof process=="object"){freeze=!falseRx.test(process.env[envFreeze])}else if(typeof system=="object"){freeze=!falseRx.test(system.env[envFreeze])}else{freeze=!(global&amp;&amp;global.when_config&amp;&amp;global.when_config.paranoid===false)}freeze=freeze&amp;&amp;Object.freeze||identity;when.defer=defer;when.resolve=resolve;when.reject=reject;when.all=all;when.some=some;when.any=any;when.map=map;when.reduce=reduce;when.chain=chain;when.isPromise=isPromise;function when(promiseOrValue,callback,errback,progressHandler){return resolve(promiseOrValue).then(callback,errback,progressHandler)}function resolve(promiseOrValue){var promise,deferred;if(promiseOrValue instanceof Promise){promise=promiseOrValue}else{if(promiseOrValue!=null&amp;&amp;typeof promiseOrValue.valueOf==="function"){promiseOrValue=promiseOrValue.valueOf()}if(isPromise(promiseOrValue)){deferred=defer();promiseOrValue.then(deferred.resolve,deferred.reject,deferred.progress);promise=deferred.promise}else{promise=resolved(promiseOrValue)}}return promise}function reject(promiseOrValue){return when(promiseOrValue,function(value){return rejected(value)})}function Promise(then){this.then=then}Promise.prototype=freeze({always:function(alwaysback,progback){return this.then(alwaysback,alwaysback,progback)},otherwise:function(errback){return this.then(undef,errback)}});function resolved(value){var p=new Promise(function(callback){try{return resolve(callback?callback(value):value)}catch(e){return rejected(e)}});return freeze(p)}function rejected(reason){console.error(reason);var p=new Promise(function(callback,errback){try{return errback?resolve(errback(reason)):rejected(reason)}catch(e){return rejected(e)}});return freeze(p)}function defer(){var deferred,promise,listeners,progressHandlers,_then,_progress,_resolve;promise=new Promise(then);deferred={then:then,resolve:promiseResolve,reject:promiseReject,progress:promiseProgress,promise:freeze(promise),resolver:freeze({resolve:promiseResolve,reject:promiseReject,progress:promiseProgress})};listeners=[];progressHandlers=[];_then=function(callback,errback,progback){var deferred=defer();listeners.push(function(promise){promise.then(callback,errback).then(deferred.resolve,deferred.reject,deferred.progress)});progback&amp;&amp;progressHandlers.push(progback);return deferred.promise};_progress=function(update){var progress,i=0;while(progress=progressHandlers[i++]){progress(update)}};_resolve=function(completed){var listener,i=0;completed=resolve(completed);_then=completed.then;_resolve=resolve;_progress=noop;while(listener=listeners[i++]){listener(completed)}progressHandlers=listeners=undef;return completed};return deferred;function then(callback,errback,progback){return _then(callback,errback,progback)}function promiseResolve(val){return _resolve(val)}function promiseReject(err){return _resolve(rejected(err))}function promiseProgress(update){_progress(update)}}function isPromise(promiseOrValue){return promiseOrValue&amp;&amp;typeof promiseOrValue.then==="function"}function some(promisesOrValues,howMany,callback,errback,progressHandler){checkCallbacks(2,arguments);return when(promisesOrValues,function(promisesOrValues){var toResolve,results,deferred,resolve,reject,progress,len,i;len=promisesOrValues.length&gt;&gt;&gt;0;toResolve=Math.max(0,Math.min(howMany,len));results=[];deferred=defer();if(!toResolve){deferred.resolve(results)}else{reject=deferred.reject;progress=deferred.progress;resolve=function(val){results.push(val);if(!--toResolve){resolve=noop;deferred.resolve(results)}};for(i=0;i&lt;len;++i){if(i in promisesOrValues){when(promisesOrValues[i],resolve,reject,progress)}}}return deferred.then(callback,errback,progressHandler)})}function all(promisesOrValues,callback,errback,progressHandler){checkCallbacks(1,arguments);return map(promisesOrValues,identity).then(callback,errback,progressHandler)}function any(promisesOrValues,callback,errback,progressHandler){function unwrapSingleResult(val){return callback?callback(val[0]):val[0]}return some(promisesOrValues,1,unwrapSingleResult,errback,progressHandler)}function map(promise,mapFunc){return when(promise,function(array){var results,len,toResolve,resolve,reject,i,d;toResolve=len=array.length&gt;&gt;&gt;0;results=[];d=defer();if(!toResolve){d.resolve(results)}else{reject=d.reject;resolve=function resolveOne(item,i){when(item,mapFunc).then(function(mapped){results[i]=mapped;if(!--toResolve){d.resolve(results)}},reject)};for(i=0;i&lt;len;i++){if(i in array){resolve(array[i],i)}else{--toResolve}}}return d.promise})}function reduce(promise,reduceFunc){var args=slice.call(arguments,1);return when(promise,function(array){var total;total=array.length;args[0]=function(current,val,i){return when(current,function(c){return when(val,function(value){return reduceFunc(c,value,i,total)})})};return reduceArray.apply(array,args)})}function chain(promiseOrValue,resolver,resolveValue){var useResolveValue=arguments.length&gt;2;return when(promiseOrValue,function(val){return resolver.resolve(useResolveValue?resolveValue:val)},resolver.reject,resolver.progress)}function checkCallbacks(start,arrayOfCallbacks){var arg,i=arrayOfCallbacks.length;while(i&gt;start){arg=arrayOfCallbacks[--i];if(arg!=null&amp;&amp;typeof arg!="function"){throw new Error("arg "+i+" must be a function")}}}function noop(){}slice=[].slice;reduceArray=[].reduce||function(reduceFunc){var arr,args,reduced,len,i;i=0;arr=Object(this);len=arr.length&gt;&gt;&gt;0;args=arguments;if(args.length&lt;=1){for(;;){if(i in arr){reduced=arr[i++];break}if(++i&gt;=len){throw new TypeError}}}else{reduced=args[1]}for(;i&lt;len;++i){if(i in arr){reduced=reduceFunc(reduced,arr[i],i,arr)}}return reduced};function identity(x){return x}return when})})(typeof define=="function"&amp;&amp;define.amd?define:function(deps,factory){typeof exports==="object"?module.exports=factory():window.when=factory()},this);(function(global){"use strict";function RotateLeft(lValue,iShiftBits){return lValue&lt;&lt;iShiftBits|lValue&gt;&gt;&gt;32-iShiftBits}function AddUnsigned(lX,lY){var lX4,lY4,lX8,lY8,lResult;lX8=lX&amp;2147483648;lY8=lY&amp;2147483648;lX4=lX&amp;1073741824;lY4=lY&amp;1073741824;lResult=(lX&amp;1073741823)+(lY&amp;1073741823);if(lX4&amp;lY4){return lResult^2147483648^lX8^lY8}if(lX4|lY4){if(lResult&amp;1073741824){return lResult^3221225472^lX8^lY8}else{return lResult^1073741824^lX8^lY8}}else{return lResult^lX8^lY8}}function _F(x,y,z){return x&amp;y|~x&amp;z}function _G(x,y,z){return x&amp;z|y&amp;~z}function _H(x,y,z){return x^y^z}function _I(x,y,z){return y^(x|~z)}function _FF(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(_F(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b)}function _GG(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(_G(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b)}function _HH(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(_H(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b)}function _II(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(_I(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b)}function ConvertToWordArray(string){var lWordCount;var lMessageLength=string.length;var lNumberOfWords_temp1=lMessageLength+8;var lNumberOfWords_temp2=(lNumberOfWords_temp1-lNumberOfWords_temp1%64)/64;var lNumberOfWords=(lNumberOfWords_temp2+1)*16;var lWordArray=new Array(lNumberOfWords-1);var lBytePosition=0;var lByteCount=0;while(lByteCount&lt;lMessageLength){lWordCount=(lByteCount-lByteCount%4)/4;lBytePosition=lByteCount%4*8;lWordArray[lWordCount]=lWordArray[lWordCount]|string.charCodeAt(lByteCount)&lt;&lt;lBytePosition;lByteCount++}lWordCount=(lByteCount-lByteCount%4)/4;lBytePosition=lByteCount%4*8;lWordArray[lWordCount]=lWordArray[lWordCount]|128&lt;&lt;lBytePosition;lWordArray[lNumberOfWords-2]=lMessageLength&lt;&lt;3;lWordArray[lNumberOfWords-1]=lMessageLength&gt;&gt;&gt;29;return lWordArray}function WordToHex(lValue){var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;for(lCount=0;lCount&lt;=3;lCount++){lByte=lValue&gt;&gt;&gt;lCount*8&amp;255;WordToHexValue_temp="0"+lByte.toString(16);WordToHexValue=WordToHexValue+WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2)}return WordToHexValue}function Utf8Encode(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n&lt;string.length;n++){var c=string.charCodeAt(n);if(c&lt;128){utftext+=String.fromCharCode(c)}else if(c&gt;127&amp;&amp;c&lt;2048){utftext+=String.fromCharCode(c&gt;&gt;6|192);utftext+=String.fromCharCode(c&amp;63|128)}else{utftext+=String.fromCharCode(c&gt;&gt;12|224);utftext+=String.fromCharCode(c&gt;&gt;6&amp;63|128);utftext+=String.fromCharCode(c&amp;63|128)}}return utftext}function MD5(string){var k,_AA,_BB,_CC,_DD,a,b,c,d;var S11=7,S12=12,S13=17,S14=22;var S21=5,S22=9,S23=14,S24=20;var S31=4,S32=11,S33=16,S34=23;var S41=6,S42=10,S43=15,S44=21;string=Utf8Encode(string);var x=ConvertToWordArray(string);a=1732584193;b=4023233417;c=2562383102;d=271733878;for(k=0;k&lt;x.length;k+=16){_AA=a;_BB=b;_CC=c;_DD=d;a=_FF(a,b,c,d,x[k+0],S11,3614090360);d=_FF(d,a,b,c,x[k+1],S12,3905402710);c=_FF(c,d,a,b,x[k+2],S13,606105819);b=_FF(b,c,d,a,x[k+3],S14,3250441966);a=_FF(a,b,c,d,x[k+4],S11,4118548399);d=_FF(d,a,b,c,x[k+5],S12,1200080426);c=_FF(c,d,a,b,x[k+6],S13,2821735955);b=_FF(b,c,d,a,x[k+7],S14,4249261313);a=_FF(a,b,c,d,x[k+8],S11,1770035416);d=_FF(d,a,b,c,x[k+9],S12,2336552879);c=_FF(c,d,a,b,x[k+10],S13,4294925233);b=_FF(b,c,d,a,x[k+11],S14,2304563134);a=_FF(a,b,c,d,x[k+12],S11,1804603682);d=_FF(d,a,b,c,x[k+13],S12,4254626195);c=_FF(c,d,a,b,x[k+14],S13,2792965006);b=_FF(b,c,d,a,x[k+15],S14,1236535329);a=_GG(a,b,c,d,x[k+1],S21,4129170786);d=_GG(d,a,b,c,x[k+6],S22,3225465664);c=_GG(c,d,a,b,x[k+11],S23,643717713);b=_GG(b,c,d,a,x[k+0],S24,3921069994);a=_GG(a,b,c,d,x[k+5],S21,3593408605);d=_GG(d,a,b,c,x[k+10],S22,38016083);c=_GG(c,d,a,b,x[k+15],S23,3634488961);b=_GG(b,c,d,a,x[k+4],S24,3889429448);a=_GG(a,b,c,d,x[k+9],S21,568446438);d=_GG(d,a,b,c,x[k+14],S22,3275163606);c=_GG(c,d,a,b,x[k+3],S23,4107603335);b=_GG(b,c,d,a,x[k+8],S24,1163531501);a=_GG(a,b,c,d,x[k+13],S21,2850285829);d=_GG(d,a,b,c,x[k+2],S22,4243563512);c=_GG(c,d,a,b,x[k+7],S23,1735328473);b=_GG(b,c,d,a,x[k+12],S24,2368359562);a=_HH(a,b,c,d,x[k+5],S31,4294588738);d=_HH(d,a,b,c,x[k+8],S32,2272392833);c=_HH(c,d,a,b,x[k+11],S33,1839030562);b=_HH(b,c,d,a,x[k+14],S34,4259657740);a=_HH(a,b,c,d,x[k+1],S31,2763975236);d=_HH(d,a,b,c,x[k+4],S32,1272893353);c=_HH(c,d,a,b,x[k+7],S33,4139469664);b=_HH(b,c,d,a,x[k+10],S34,3200236656);a=_HH(a,b,c,d,x[k+13],S31,681279174);d=_HH(d,a,b,c,x[k+0],S32,3936430074);c=_HH(c,d,a,b,x[k+3],S33,3572445317);b=_HH(b,c,d,a,x[k+6],S34,76029189);a=_HH(a,b,c,d,x[k+9],S31,3654602809);d=_HH(d,a,b,c,x[k+12],S32,3873151461);c=_HH(c,d,a,b,x[k+15],S33,530742520);b=_HH(b,c,d,a,x[k+2],S34,3299628645);a=_II(a,b,c,d,x[k+0],S41,4096336452);d=_II(d,a,b,c,x[k+7],S42,1126891415);c=_II(c,d,a,b,x[k+14],S43,2878612391);b=_II(b,c,d,a,x[k+5],S44,4237533241);a=_II(a,b,c,d,x[k+12],S41,1700485571);d=_II(d,a,b,c,x[k+3],S42,2399980690);c=_II(c,d,a,b,x[k+10],S43,4293915773);b=_II(b,c,d,a,x[k+1],S44,2240044497);a=_II(a,b,c,d,x[k+8],S41,1873313359);d=_II(d,a,b,c,x[k+15],S42,4264355552);c=_II(c,d,a,b,x[k+6],S43,2734768916);b=_II(b,c,d,a,x[k+13],S44,1309151649);a=_II(a,b,c,d,x[k+4],S41,4149444226);d=_II(d,a,b,c,x[k+11],S42,3174756917);c=_II(c,d,a,b,x[k+2],S43,718787259);b=_II(b,c,d,a,x[k+9],S44,3951481745);a=AddUnsigned(a,_AA);b=AddUnsigned(b,_BB);c=AddUnsigned(c,_CC);d=AddUnsigned(d,_DD)}var temp=WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);return temp.toLowerCase()}global.MD5=MD5})(window);function TinyQueue(data,compare){if(!(this instanceof TinyQueue))return new TinyQueue(data,compare);this.data=data||[];this.length=this.data.length;this.compare=compare||function defaultCompare(a,b){return a&lt;b?-1:a&gt;b?1:0};if(this.length&gt;0){for(var i=(this.length&gt;&gt;1)-1;i&gt;=0;i--)this._down(i)}}TinyQueue.prototype={push:function(item){this.data.push(item);this.length++;this._up(this.length-1)},pop:function(){if(this.length===0)return undefined;var top=this.data[0];this.length--;if(this.length&gt;0){this.data[0]=this.data[this.length];this._down(0)}this.data.pop();return top},peek:function(){return this.data[0]},_up:function(pos){var data=this.data;var compare=this.compare;var item=data[pos];while(pos&gt;0){var parent=pos-1&gt;&gt;1;var current=data[parent];if(compare(item,current)&gt;=0)break;data[pos]=current;pos=parent}data[pos]=item},_down:function(pos){var data=this.data;var compare=this.compare;var halfLength=this.length&gt;&gt;1;var item=data[pos];while(pos&lt;halfLength){var left=(pos&lt;&lt;1)+1;var right=left+1;var best=data[left];if(right&lt;this.length&amp;&amp;compare(data[right],best)&lt;0){left=right;best=data[right]}if(compare(best,item)&gt;=0)break;data[pos]=best;pos=left}data[pos]=item}};(function(global){function UnsortedSet(hashFunc){this.hashFunc=hashFunc;this.data={}}UnsortedSet.prototype.add=function(value){var key=this.hashFunc(value);this.data[key]=value};UnsortedSet.prototype.get=function(value){var key=this.hashFunc(value);return this.data[key]};UnsortedSet.prototype.remove=function(value){var key=this.hashFunc(value);delete this.data[key]};function SortedMap(sortFunc){this.sortFunc=sortFunc;this.sortedKeys=[];this.data={};this.dirty=false}SortedMap.prototype.set=function(key,value){var keyString=key.join(",");if(!(keyString in this.data)){this.data[keyString]=value;this.sortedKeys.push(key);this.dirty=true}};SortedMap.prototype.get=function(key){return this.data[key.join(",")]};SortedMap.prototype.empty=function(){return Object.keys(this.data).length===0};SortedMap.prototype.getSortedKeys=function(){if(this.dirty){this.sortedKeys.sort(this.sortFunc)}return this.sortedKeys};SortedMap.prototype.delete=function(key){if(key){var keyString=key.join(",");delete this.data[keyString];if(this.sortedKeys){var delIdx=this.sortedKeys.findIndex(function(k){return k[0]===key[0]&amp;&amp;k[1]===key[1]});this.sortedKeys.splice(delIdx,1)}}};var TOPOLOGIES=[[[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]],[[-1,0],[0,-1],[0,1],[1,0]],[[-2,0],[-1,0],[1,0],[2,0],[1,-1],[-1,-1]],[[-2,0],[-1,1],[1,1],[2,0],[1,0],[-1,0]]];function CellComparitor(columnCount){return function(lhs,rhs){return lhs[0]*columnCount+lhs[1]-(rhs[0]*columnCount+rhs[1])}}function PathCellComparitor(columnCount){return function(lhs,rhs){var lhsCell=lhs[0],lhsDist=lhs[1];var rhsCell=rhs[0],rhsDist=rhs[1];return lhsDist-rhsDist||lhsCell[0]*columnCount+lhsCell[1]-(rhsCell[0]*columnCount+rhsCell[1])}}function CellHasher(columnCount){return function(cell){return cell[1]*columnCount+cell[0]}}function unrollPath(cameFrom,currentNode,pathNodes){pathNodes=pathNodes||[];var found=cameFrom.get(currentNode);if(found){unrollPath(cameFrom,found,pathNodes)}pathNodes.push([currentNode[0],currentNode[1]]);return pathNodes}function cellCompare(cell1,cell2){if(!cell1||!cell2){return cell1===cell2}return cell1[0]===cell2[0]&amp;&amp;cell1[1]===cell2[1]}global.gsFindPath=function(map,startRow,startColumn,destRow,destColumn,topologyType){if(startColumn&lt;0||destColumn&lt;0||destRow&lt;0||destColumn&lt;0){return[]}var mapRows=map.length;if(startRow&gt;=mapRows||destRow&gt;=mapRows){return[]}var mapColumns=mapRows&gt;0?map[0].length:0;if(startColumn&gt;=mapColumns||destColumn&gt;=mapColumns){return[]}var dx=Math.abs(destColumn-startColumn);var dy=Math.abs(destRow-startRow);var distance=dx+dy;var startCell=[startRow,startColumn];var destCell=[destRow,destColumn];var cellMapCompare=CellComparitor(mapColumns);var pathCellCompare=PathCellComparitor(mapColumns);var cellMapHash=CellHasher(mapColumns);var gscore=new SortedMap(cellMapCompare);var openSet=new TinyQueue([],pathCellCompare);var closedSet=new UnsortedSet(cellMapHash);var cameFrom=new SortedMap(cellMapCompare);openSet.push([startCell,distance]);gscore.set(startCell,0);var adjacentOffsets=TOPOLOGIES[topologyType];while(openSet.length!==0){var currentNode=openSet.peek();var current=currentNode[0];var minDist=currentNode[1];if(cellCompare(current,destCell)){return unrollPath(cameFrom,destCell)}openSet.pop();closedSet.add(current);if(topologyType===2){adjacentOffsets=TOPOLOGIES[2+current[0]%2]}adjacentOffsets.forEach(function(offset){var neighborCell=[current[0]+offset[0],current[1]+offset[1]];if(neighborCell[0]&lt;0||neighborCell[0]&gt;=mapColumns||neighborCell[1]&lt;0||neighborCell[1]&gt;=mapRows){return}var neighborCellValue=map[neighborCell[0]]?map[neighborCell[0]][neighborCell[1]]:undefined;if(neighborCellValue&lt;0){return}if(!closedSet.get(neighborCell)){var currentScore=neighborCellValue+1;var cscoreFound=gscore.get(current);if(cscoreFound){currentScore+=cscoreFound}var neighborScore=Number.MAX_SAFE_INTEGER;var nscoreFound=gscore.get(neighborCell);if(nscoreFound){neighborScore=nscoreFound}if(!openSet.data.find(function(c){var cell=c[0];return cell[0]===neighborCell[0]&amp;&amp;cell[1]===neighborCell[1]})||currentScore&lt;neighborScore){cameFrom.set(neighborCell,current);gscore.set(neighborCell,currentScore);var fscore=currentScore+Math.abs(destColumn-neighborCell[0])+Math.abs(destRow-neighborCell[1]);openSet.push([neighborCell,fscore])}}})}return false}})(window);(function(global,pool,math){var width=256,chunks=6,digits=52,rngname="random",startdenom=math.pow(width,chunks),significance=math.pow(2,digits),overflow=significance*2,mask=width-1,nodecrypto;function seedrandom(seed,options,callback){var key=[];options=options==true?{entropy:true}:options||{};var shortseed=mixkey(flatten(options.entropy?[seed,tostring(pool)]:seed==null?autoseed():seed,3),key);var arc4=new ARC4(key);var prng=function(){var n=arc4.g(chunks),d=startdenom,x=0;while(n&lt;significance){n=(n+x)*width;d*=width;x=arc4.g(1)}while(n&gt;=overflow){n/=2;d/=2;x&gt;&gt;&gt;=1}return(n+x)/d};prng.int32=function(){return arc4.g(4)|0};prng.quick=function(){return arc4.g(4)/4294967296};prng.double=prng;mixkey(tostring(arc4.S),pool);return(options.pass||callback||function(prng,seed,is_math_call,state){if(state){if(state.S){copy(state,arc4)}prng.state=function(){return copy(arc4,{})}}if(is_math_call){math[rngname]=prng;return seed}else return prng})(prng,shortseed,"global"in options?options.global:this==math,options.state)}function ARC4(key){var t,keylen=key.length,me=this,i=0,j=me.i=me.j=0,s=me.S=[];if(!keylen){key=[keylen++]}while(i&lt;width){s[i]=i++}for(i=0;i&lt;width;i++){s[i]=s[j=mask&amp;j+key[i%keylen]+(t=s[i])];s[j]=t}(me.g=function(count){var t,r=0,i=me.i,j=me.j,s=me.S;while(count--){t=s[i=mask&amp;i+1];r=r*width+s[mask&amp;(s[i]=s[j=mask&amp;j+t])+(s[j]=t)]}me.i=i;me.j=j;return r})(width)}function copy(f,t){t.i=f.i;t.j=f.j;t.S=f.S.slice();return t}function flatten(obj,depth){var result=[],typ=typeof obj,prop;if(depth&amp;&amp;typ=="object"){for(prop in obj){try{result.push(flatten(obj[prop],depth-1))}catch(e){}}}return result.length?result:typ=="string"?obj:obj+"\0"}function mixkey(seed,key){var stringseed=seed+"",smear,j=0;while(j&lt;stringseed.length){key[mask&amp;j]=mask&amp;(smear^=key[mask&amp;j]*19)+stringseed.charCodeAt(j++)}return tostring(key)}function autoseed(){try{var out;if(nodecrypto&amp;&amp;(out=nodecrypto.randomBytes)){out=out(width)}else{out=new Uint8Array(width);(global.crypto||global.msCrypto).getRandomValues(out)}return tostring(out)}catch(e){var browser=global.navigator,plugins=browser&amp;&amp;browser.plugins;return[+new Date,global,plugins,global.screen,tostring(pool)]}}function tostring(a){return String.fromCharCode.apply(0,a)}mixkey(math.random(),pool);if(typeof module=="object"&amp;&amp;module.exports){module.exports=seedrandom;try{nodecrypto=require("crypto")}catch(ex){}}else if(typeof define=="function"&amp;&amp;define.amd){define(function(){return seedrandom})}else{math["seed"+rngname]=seedrandom}})(typeof self!=="undefined"?self:this,[],Math);var gs=gs||{};var gse=gs;var pgf=pgf||{};gs.version={number:"1.25.137",revision:"",date:"",platform:"core"};gs.debug={fps:false,profile:false,log:true,evaluate:true,physics:true,physicsHiFi:true,render:true,renderTextures:true,renderFlush:false,particles:true,text:true,audio:true};gs.globalOptions={format:"json",useBehaviorStubs:false,uploadAnalytics:false,useDynamicOverlayLayer:true,dynamicOverlayLayerInitiallyVisible:false,actorPrototypeBatchSize:64,imageRequestPoolSize:8,audioPoolSize:8,maxFontSheetTextureSize:0,spoofIOSScreenSize:true,forceViewportOrientationMatch:false,forceTexturePrimeFrames:false,forcePointerEvents:false,forceInputEventsOnCanvas:false,crossOriginImageLoading:false,supportsVibrate:false,exitOnBuzz:false,pauseOnVisibilityChange:false};gs.subclass=function(parentConstructor,propertyMap){for(var key in propertyMap){var value=propertyMap[key];propertyMap[key]={value:value,enumerable:false}}return Object.create(parentConstructor.prototype,propertyMap)};gs.inherits=function(childClass,baseClass){var childDeclarations=childClass.prototype;for(var key in childDeclarations){var value=childDeclarations[key];childDeclarations[key]={enumerable:false,value:value}}childDeclarations.__class={enumerable:false,value:childClass};childDeclarations.__superclass={enumerable:false,value:baseClass};childDeclarations.__super={enumerable:false,value:baseClass.prototype};Object.defineProperty(childClass,"__class",childDeclarations.__class);Object.defineProperty(childClass,"__superclass",childDeclarations.__superclass);Object.defineProperty(childClass,"__super",childDeclarations.__super);Object.defineProperty(childClass,"subclass",{enumerable:false,value:function(name,properties){var subclassConstructor=function(){childClass.call(this)};subclassConstructor.prototype=properties||{};gs.inherits(subclassConstructor,childClass);return subclassConstructor}});for(var key in gs){if(gs[key]===childClass){childDeclarations.__classname={enumerable:false,value:key};Object.defineProperty(childClass,"__classname",childDeclarations.__classname);break}}childClass.prototype=Object.create(baseClass.prototype,childDeclarations);if(!childClass.provide){childClass.provide=function(){return new childClass}}};gs.singleton=function(classConstructor){Object.defineProperty(classConstructor,"__singleton",{enumerable:false,writable:true,value:null});Object.defineProperty(classConstructor,"instance",{enumerable:false,value:function(){if(!classConstructor.__singleton){classConstructor.__singleton=new classConstructor}return classConstructor.__singleton}});Object.defineProperty(classConstructor,"provide",{enumerable:false,value:function(){if(!classConstructor.__singleton){classConstructor.__singleton=new classConstructor}return classConstructor.__singleton}})};gs.getSystemTime=function(){return Date.now()/1e3};gs.encodeURL=function(name){var i=name.lastIndexOf("/");return name.substring(0,i+1)+encodeURIComponent(name.substring(i+1,name.length))};gs.parseBoolean=function(input){if(typeof input==="boolean"){return input}if(typeof input==="string"){if(input.toLowerCase()==="false"||input.toLowerCase()=="0")return false;else return true}return false};gs.parseInteger=function(input){return parseInt(input,10)};gs.TIME_STEP_MS=16;gs.TIME_STEP_S=gs.TIME_STEP_MS/1e3;gs.FRAMERATE_FPS=1e3/gs.TIME_STEP_MS;gs.g_tempVec2d=[0,0];gs.minAllowedUpdateTimestepMS=gs.TIME_STEP_MS/4;gs.keyMap={17:"ctrl",18:"alt",38:"up",40:"down",37:"left",39:"right",32:"space",9:"tab",13:"return",27:"esc",8:"delete",46:"delete",93:"cmd",20:"tab",106:"*",107:"+",109:"-",110:".",111:"/",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down",ShiftLeft:"left shift",ShiftRight:"right shift",MetaLeft:"cmd",MetaRight:"cmd",ControlLeft:"ctrl",ControlRight:"ctrl",AltLeft:"alt",AltRight:"alt",Enter:"return",Tab:"tab",Space:"space",Backspace:"delete",CapsLock:"caps lock",Escape:"esc",Equal:"=",Minus:"-",BracketRight:"]",BracketLeft:"[",Quote:"'",Semicolon:";",Minus:"-",Period:".",Slash:"/",Comma:",",Backquote:"`",Backslash:"\\"};gs.mapKeyInput=function(event){var mappedKey=gs.keyMap[event.code||event.keyCode];if(mappedKey){return mappedKey}if(event.keyCode==16){try{if(event.location===KeyboardEvent.DOM_KEY_LOCATION_LEFT||event.shiftLeft){return"left shift"}else{return"right shift"}}catch(e){console.log(e);console.log("error trying to figure out right / left shift.");return"left shift"}}if(event.keyCode&gt;=96&amp;&amp;event.keyCode&lt;=105){return(event.keyCode-96).toString()}return String.fromCharCode(event.keyCode)};gs.getEngineContext=function(){return gs.EngineContext.current};gs.ready=function(callback){var engine=gs.EngineContext.instance();callback&amp;&amp;callback.call(null,engine)};gs._yield=function(callback){var minimumTimeout=10;var promise=new gs.Promise;window.setTimeout(function onYield(){callback&amp;&amp;callback.call(null);promise.resolve()},minimumTimeout);return promise};gs.pause=function(){gs.EngineContext.current.pause()};gs.unpause=function(){gs.EngineContext.current.unpause()};gs.suspend=function(){gs.EngineContext.current.suspend()};gs.unsuspend=function(){gs.EngineContext.current.unsuspend()};gs.relayout=function(){gs.EngineContext.current.relayout()};gs.postEvent=function(eventName){var eventCenter=gs.Game.current.eventCenter;var args=gs.array.provide();args[0]=eventName;args[1]=null;for(var i=1;i&lt;arguments.length;i++){args.push(arguments[i])}return eventCenter.postEvent.apply(eventCenter,args)};gs["ready"]=gs.ready;gs["_yield"]=gs._yield;gs["pause"]=gs.pause;gs["unpause"]=gs.unpause;gs["suspend"]=gs.suspend;gs["unsuspend"]=gs.unsuspend;gs["relayout"]=gs.relayout;gs["postEvent"]=gs.postEvent;gs.analytics=gs.analytics||{};gs.api=gs.api||{};gs.Log={level:0,delegate:null,LogLevel:{ALL:7,DEBUG:6,INFO:5,WARN:4,STRICT:3,ERROR:2,FATAL:1,OFF:0},strings:{DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",STRICT:"STRICT",ERROR:"ERROR",FATAL:"FATAL"},write:function(method,prefix,segments){try{var message="";var count=segments.length;if(prefix){message=prefix+":";while(message.length&lt;8){message+=" "}}if(count&gt;0){message+=segments[0]}for(var i=1;i&lt;count;i++){message+=" "+segments[i]}if(typeof method==="function"){method.call(console,message)}else{console.log(message)}if(this.delegate){this.delegate.onLogAll(message)}if(prefix==gs.Log.strings.FATAL){alert(message)}}catch(exception){}},writeIf:function(level,method,prefix,segments){if(gs.Log.level&gt;=level){gs.Log.write(method,prefix,segments)}},debug:function(){gs.Log.writeIf(gs.Log.LogLevel.DEBUG,console.debug,this.strings.DEBUG,arguments)},info:function(){gs.Log.writeIf(gs.Log.LogLevel.INFO,console.log,gs.Log.strings.INFO,arguments)},warn:function(){gs.Log.writeIf(gs.Log.LogLevel.WARN,console.warn,gs.Log.strings.WARN,arguments)},strict:function(){gs.Log.writeIf(gs.Log.LogLevel.STRICT,console.warn,gs.Log.strings.STRICT,arguments)},error:function(){gs.Log.writeIf(gs.Log.LogLevel.ERROR,console.error,gs.Log.strings.ERROR,arguments)},fatal:function(){gs.Log.writeIf(gs.Log.LogLevel.FATAL,console.error,gs.Log.strings.FATAL,arguments)},print:function(){gs.Log.write(console.log,null,arguments)}};gs.level=gs.Log.LogLevel.OFF;gs.util={getSecondsSinceUnixEpoch:function(){return Math.floor(Date.now()/1e3)},randomInteger:function(n){return Math.floor(Math.random()*n)},randomIntegerRange:function(m,n){return Math.floor(m+Math.random()*(m-n))},pickRandomCharacter:function(characters){var index=gs.util.randomInteger(characters.length);return characters.charAt(index)},generateRandomHexString:function(length){var s="";var hexCharacters="0123456789abcdef";for(var i=0;i&lt;length;i++){s+=gs.util.pickRandomCharacter(hexCharacters)}return s},generateUUID:function(){var s="";s+=gs.util.generateRandomHexString(8);s+="-";s+=gs.util.generateRandomHexString(4);s+="-4";s+=gs.util.generateRandomHexString(3);s+="-"+gs.util.pickRandomCharacter("89ab");s+=gs.util.generateRandomHexString(3);s+="-";s+=gs.util.generateRandomHexString(12);return s},reverseMap:function(map){var reversed={};for(var key in map){var value=map[key];reversed[value]=key}return reversed},createObfuscationLookup:function(map){return gs.util.reverseMap(map)},createMapFromURLString:function(URLString,defaultKey){var map={};var startIndex=URLString.indexOf("?")+1;if(startIndex===0){startIndex=URLString.indexOf("#")+1}if(URLString.length&gt;startIndex){var pairs=URLString.substring(startIndex).split("&amp;");pairs.forEach(function(element){var pair=element.split("=");if(pair.length===1){map[defaultKey]=pair[0]}else{var key=pair[0];if(/^gse-/.test(key)){key=key.substr(4)}map[key]=pair[1]}})}return map},lazySingleton:function(constructor){if(!constructor.lazySingleton){constructor.lazySingleton=new constructor}return constructor.lazySingleton}};gs.Promise=function(){this.deferred=when.defer()};gs.Promise.all=when.all;gs.Promise.prototype={then:function(success,failure,progress){return this.deferred.promise.then(success,failure,progress)},always:function(always,progress){return this.then(always,always,progress)},otherwise:function(failure){return this.then(undefined,failure)},resolve:function(promiseOrValue){return this.deferred.resolve(promiseOrValue)},reject:function(promiseOrValue){return this.deferred.reject(promiseOrValue)}};gs["Promise"]=gs.Promise;gs.dom={nodes:{CANVAS:"CANVAS",IMAGE:"IMG",AUDIO:"AUDIO"},getElement:function(elementOrId){if(typeof elementOrId==="string"){return document.getElementById(elementOrId)}else{return elementOrId}},resizeElement:function(element,width,height){element.style.width=width+"px";element.style.height=height+"px"},repositionElement:function(element,left,top){element.style.left=left+"px";element.style.top=top+"px"},getComputedStyle:function(element){return window.getComputedStyle(element)},getElementPosition:function(element){var x=0;var y=0;for(;element;element=element.offsetParent){x+=element.offsetLeft;y+=element.offsetTop}return[x,y]},setElementVisible:function(element,visible){element.style.visibility=visible?"visible":"hidden"},create:function(nodeName){return document.createElement(nodeName)},createFragment:function(){return document.createDocumentFragment()},createCanvas:function(){return gs.dom.create(gs.dom.nodes.CANVAS)},createImage:function(src){var element=gs.dom.create(gs.dom.nodes.IMAGE);var isDataURI=/^data:image/.test(src);if(!isDataURI&amp;&amp;gs.globalOptions.crossOriginImageLoading){element.crossOrigin="anonymous"}if(src){element.src=src}return element},createAudio:function(){return gs.dom.create(gs.dom.nodes.AUDIO)}};gs.math={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,equalityEpsilon:.1,clampf:function(x,lower,upper){x=x!=null?x:0;lower=lower!=null?lower:0;upper=upper!=null?upper:1;return Math.min(Math.max(x,lower),upper)},numberEquals:function(LHS,RHS){return Math.abs(LHS-RHS)&lt;gs.math.equalityEpsilon}};var gsMath=gs.math;gs.Pool={allConstructors:[],init:function(classConstructor){var owner=classConstructor;owner._recyclePool=[];owner._recyclePoolSize=0;gs.Pool.allConstructors.push(owner);owner.provide=function(){if(owner._recyclePoolSize&gt;0){var o=owner._recyclePool[--owner._recyclePoolSize];owner.call(o);return o}return new classConstructor};owner.recycle=function(o){owner._recyclePool[owner._recyclePoolSize++]=o};owner.primePool=function(n){if(owner._recyclePoolSize&lt;n){for(var i=owner._recyclePoolSize;i&lt;n;i++){owner.recycle(new classConstructor)}}}},debugReport:function(){for(var i=0;i&lt;gs.Pool.allConstructors.length;i++){var c=gs.Pool.allConstructors[i];if(c._recyclePoolSize&gt;0){var name=gs.getTypeName(c._recyclePool[0]);if(name){gs.Pool.debugLine(c,name)}}}},debugLine:function(owner,name){gs.Log.debug(owner._recyclePoolSize,name)}};gs.array={insert:function(array,index,element){array.splice(index,0,element)},remove:function(array,index,count){count=count||1;var element=array[index];array.splice(index,count);return element},_pool:[],provide:function(){if(gs.array._pool.length&gt;0){return Array.prototype.pop.call(gs.array._pool)}return[]},recycle:function(o){o.length=0;this._pool[this._pool.length]=o},primePool:function(n){if(this._pool.length&lt;n){for(var i=this._pool.length;i&lt;n;i++){this._pool[i]=[]}}},recycleJXONTree:function(node){if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){gs.array.recycleJXONTree(node[i])}gs.array.recycle(node)}else if(typeof node==="object"){for(var key in node){if(Array.isArray(node[key])){gs.array.recycleJXONTree(node[key]);delete node[key]}else if(typeof node[key]==="object"){gs.array.recycleJXONTree(node[key])}}}},recycleJXONArraysAndMaps:function(node){if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){gs.array.recycleJXONArraysAndMaps(node[i])}gs.array.recycle(node)}else if(typeof node==="object"){for(var key in node){if(Array.isArray(node[key])){gs.array.recycleJXONArraysAndMaps(node[key])}else if(typeof node[key]==="object"){gs.array.recycleJXONArraysAndMaps(node[key])}}gs.Map.recycle(node)}},recyclePrototypicalTree:function(node){if(Array.isArray(node._children)){var children=node._children;for(var i=0,end=children.length;i&lt;end;i++){gs.array.recyclePrototypicalTree(children[i])}node.recycleArrays()}}};gs.Map={_pool:[],_poolMaxSize:128,provide:function(){if(this._pool.length&gt;0){return this._pool.pop()}return{}},recycle:function(map){if(this._pool.length&lt;this._poolMaxSize){for(var key in map){delete map[key]}this._pool[this._pool.length]=map}}};gs.MultiSet=function(){this.size=0};gs.MultiSet.prototype={addObject:function(element){if(element in this){this[element]++}else{this[element]=1}this.size++},countOfObject:function(element){return element in this?this[element]:0},removeObject:function(element){if(element in this){this[element]--;this.size--}}};gs.set={setWithObjects:function(arg){var newSet={};for(var key in arg){newSet[key]=true}return newSet},arrayToSet:function(array){var newSet={};var len=array.length;for(var i=0;i&lt;len;++i){newSet[array[i]]=true}return newSet},setToArray:function(aSet){var newArray=gs.array.provide();for(var name in aSet){newArray.push(name)}return newArray},unionSet:function(aSet,bSet){var newSet={};var name;for(name in aSet){newSet[name]=aSet[name]}for(name in bSet){newSet[name]=bSet[name]}return newSet}};gs.sparseArray={addItem:function(item){var holes=this.holes;var index;if(holes.length){index=holes.pop()}else{index=this.n;this.n=index+1}this[index]=item;return index},removeItemAtIndex:function(index){this[index]=null;var holes=this.holes;holes.push(index)},create:function(){var newArray=[];newArray.n=0;newArray.holes=[];newArray.addItem=gs.sparseArray.addItem;newArray.removeItemAtIndex=gs.sparseArray.removeItemAtIndex;return newArray}};String.prototype.endsWith=function(suffix){return this.indexOf(suffix,this.length-suffix.length)!==-1};String.prototype.trim=function(){return this.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")};String.prototype.pathExtension=function(){var components=this.split(".");return components[components.length-1]};gs.string={safe:function(s){return typeof s==="string"?s:""},safeLowerCase:function(s){if(typeof s==="string"){return s.toLowerCase()}return""},beginsWith:function(s,t){return s.indexOf(t)===0},endsWith:function(s,t){return s.indexOf(t,s.length-t.length)!==-1},contains:function(s,t){return s.indexOf(t)!==-1}};gs.Vector2=function(){this.x=0;this.y=0};gs.Pool.init(gs.Vector2);gs.Vector2.ZERO_VECTOR=[0,0];gs.Vector2.EPSILON=5;gs.Vector2.X_COMPONENT=0;gs.Vector2.Y_COMPONENT=1;gs.Vector2.vectorRotate2D=function(result,vector,theta){var x=vector[0];var y=vector[1];var costheta=Math.cos(theta);var sintheta=Math.sin(theta);result[0]=x*costheta-y*sintheta;result[1]=x*sintheta+y*costheta};gs.Vector2.equals=function(vectorA,vectorB,epsilon){return Math.abs(vectorA[0]-vectorB[0])&lt;=epsilon&amp;&amp;Math.abs(vectorA[1]-vectorB[1])&lt;=epsilon};gs.Rect={};gs.Rect.pointInRect=function(x,y,rect){var minX=rect.x;var minY=rect.y;var maxX=minX+rect.width;var maxY=minY+rect.height;return x&gt;minX&amp;&amp;x&lt;maxX&amp;&amp;y&gt;minY&amp;&amp;y&lt;maxY};gs.Rect.nearestPointInRect=function(result,x,y,rect){result[0]=rect.x+rect.width*.5;result[1]=rect.y+rect.height*.5;if(rect.width&gt;0){var minX=rect.x;var maxX=minX+rect.width;result[0]=gsMath.clampf(x,minX,maxX)}if(rect.height&gt;0){var minY=rect.y;var maxY=minY+rect.height;result[1]=gsMath.clampf(y,minY,maxY)}return result};var Box2D=Box2D||{Collision:{Shapes:{}},Common:{Math:{}},Consts:{},Dynamics:{Contacts:{},Controllers:{},Joints:{}}};var UsageTracker={map:{},get:function(classname){if(!this.map[classname]){this.map[classname]={trackCreate:function(){console.log("create",classname)},trackGet:function(){},trackFree:function(){}}}return this.map[classname]}};Box2D.generateCallback=function(context,fn){return function(){fn.apply(context,arguments)}};Box2D.abstractMethod=function(){throw Error("unimplemented abstract method")};Box2D.inherits=function(childCtor,parentCtor){function tempCtor(){}tempCtor.prototype=parentCtor.prototype;childCtor.superClass_=parentCtor.prototype;childCtor.prototype=new tempCtor;childCtor.prototype.constructor=childCtor};Box2D.Array={};Box2D.Array.remove=function(array,element){var index=array.indexOf(element);array.splice(index,1)};Box2D.Array._freeCache=[];Box2D.Array.Get=function(){return gs.array.provide()};Box2D.Array.Free=function(o){if(o!=null){gs.array.recycle(o)}};Box2D.Consts.MIN_VALUE_SQUARED=Number.MIN_VALUE*Number.MIN_VALUE;Box2D.Common.b2Color=function(rr,gg,bb){this._r=255*Box2D.Common.Math.b2Math.Clamp(rr,0,1);this._g=255*Box2D.Common.Math.b2Math.Clamp(gg,0,1);this._b=255*Box2D.Common.Math.b2Math.Clamp(bb,0,1)};Box2D.Common.b2Color.prototype.Set=function(rr,gg,bb){this._r=255*Box2D.Common.Math.b2Math.Clamp(rr,0,1);this._g=255*Box2D.Common.Math.b2Math.Clamp(gg,0,1);this._b=255*Box2D.Common.Math.b2Math.Clamp(bb,0,1)};Box2D.Common.b2Color.prototype.GetColor=function(){return this._r&lt;&lt;16|this._g&lt;&lt;8|this._b};Box2D.Common.b2Settings={};Box2D.Common.b2Settings.b2MixFriction=function(friction1,friction2){return Math.sqrt(friction1*friction2)};Box2D.Common.b2Settings.b2MixRestitution=function(restitution1,restitution2){return restitution1&gt;restitution2?restitution1:restitution2};Box2D.Common.b2Settings.b2Assert=function(a){if(!a){throw"Assertion Failed"}};Box2D.Common.b2Settings.VERSION="2.1alpha-illandril";Box2D.Common.b2Settings.USHRT_MAX=65535;Box2D.Common.b2Settings.b2_maxManifoldPoints=2;Box2D.Common.b2Settings.b2_aabbExtension=.1;Box2D.Common.b2Settings.b2_aabbMultiplier=2;Box2D.Common.b2Settings.b2_polygonRadius=2*Box2D.Common.b2Settings.b2_linearSlop;Box2D.Common.b2Settings.b2_linearSlop=.005;Box2D.Common.b2Settings.b2_angularSlop=2/180*Math.PI;Box2D.Common.b2Settings.b2_toiSlop=8*Box2D.Common.b2Settings.b2_linearSlop;Box2D.Common.b2Settings.b2_maxTOIContactsPerIsland=32;Box2D.Common.b2Settings.b2_maxTOIJointsPerIsland=32;Box2D.Common.b2Settings.b2_velocityThreshold=1;Box2D.Common.b2Settings.b2_maxLinearCorrection=.2;Box2D.Common.b2Settings.b2_maxAngularCorrection=8/180*Math.PI;Box2D.Common.b2Settings.b2_maxTranslation=2;Box2D.Common.b2Settings.b2_maxTranslationSquared=Box2D.Common.b2Settings.b2_maxTranslation*Box2D.Common.b2Settings.b2_maxTranslation;Box2D.Common.b2Settings.b2_maxRotation=.5*Math.PI;Box2D.Common.b2Settings.b2_maxRotationSquared=Box2D.Common.b2Settings.b2_maxRotation*Box2D.Common.b2Settings.b2_maxRotation;Box2D.Common.b2Settings.b2_contactBaumgarte=.2;Box2D.Common.b2Settings.b2_timeToSleep=.5;Box2D.Common.b2Settings.b2_linearSleepTolerance=.01;Box2D.Common.b2Settings.b2_linearSleepToleranceSquared=Box2D.Common.b2Settings.b2_linearSleepTolerance*Box2D.Common.b2Settings.b2_linearSleepTolerance;Box2D.Common.b2Settings.b2_angularSleepTolerance=2/180*Math.PI;Box2D.Common.b2Settings.b2_angularSleepToleranceSquared=Box2D.Common.b2Settings.b2_angularSleepTolerance*Box2D.Common.b2Settings.b2_angularSleepTolerance;Box2D.Common.b2Settings.MIN_VALUE_SQUARED=Number.MIN_VALUE*Number.MIN_VALUE;var __b2Vec2=function(x,y){this.x=x;this.y=y;this.__nextPooledObject=null};Box2D.Common.Math.b2Vec2=__b2Vec2;var __b2Vec2_FirstPooledObject;var b2Vec2Get=function(x,y){if(__b2Vec2_FirstPooledObject!=null){var vec=__b2Vec2_FirstPooledObject;__b2Vec2_FirstPooledObject=vec.__nextPooledObject;vec.x=x;vec.y=y;vec.__nextPooledObject=null;return vec}return new __b2Vec2(x,y)};__b2Vec2.Get=b2Vec2Get;var b2Vec2Free=function(vec){if(vec!=null){vec.__nextPooledObject=__b2Vec2_FirstPooledObject;__b2Vec2_FirstPooledObject=vec}};__b2Vec2.Free=b2Vec2Free;__b2Vec2.prototype.SetZero=function(){this.x=0;this.y=0};__b2Vec2.prototype.Set=function(x,y){this.x=x;this.y=y};__b2Vec2.prototype.SetV=function(v){this.x=v.x;this.y=v.y};__b2Vec2.prototype.GetNegative=function(){return __b2Vec2.Get(-this.x,-this.y)};__b2Vec2.prototype.NegativeSelf=function(){this.x=-this.x;this.y=-this.y};__b2Vec2.prototype.Copy=function(){return __b2Vec2.Get(this.x,this.y)};__b2Vec2.prototype.Add=function(v){this.x+=v.x;this.y+=v.y};__b2Vec2.prototype.Subtract=function(v){this.x-=v.x;this.y-=v.y};__b2Vec2.prototype.Multiply=function(a){this.x*=a;this.y*=a};__b2Vec2.prototype.MulM=function(A){var tX=this.x;this.x=A.col1.x*tX+A.col2.x*this.y;this.y=A.col1.y*tX+A.col2.y*this.y};__b2Vec2.prototype.MulTM=function(A){var tX=this.x*A.col1.x+this.y*A.col1.y;this.y=this.x*A.col2.x+this.y*A.col2.y;this.x=tX};__b2Vec2.prototype.CrossVF=function(s){var tX=this.x;this.x=s*this.y;this.y=-s*tX};__b2Vec2.prototype.CrossFV=function(s){var tX=this.x;this.x=-s*this.y;this.y=s*tX};__b2Vec2.prototype.MinV=function(b){this.x=Math.min(this.x,b.x);this.y=Math.min(this.y,b.y)};__b2Vec2.prototype.MaxV=function(b){this.x=Math.max(this.x,b.x);this.y=Math.max(this.y,b.y)};__b2Vec2.prototype.Abs=function(){this.x=Math.abs(this.x);this.y=Math.abs(this.y)};__b2Vec2.prototype.Length=function(){return Math.sqrt(this.LengthSquared())};__b2Vec2.prototype.LengthSquared=function(){return this.x*this.x+this.y*this.y};__b2Vec2.prototype.Normalize=function(){var length=this.Length();if(length&lt;Number.MIN_VALUE){return 0}var invLength=1/length;this.x*=invLength;this.y*=invLength;return length};__b2Vec2.prototype.IsValid=function(){return isFinite(this.x)&amp;&amp;isFinite(this.y)};Box2D.Common.Math.b2Vec3=function(x,y,z){this.x=x;this.y=y;this.z=z};Box2D.Common.Math.b2Vec3._freeCache=[];Box2D.Common.Math.b2Vec3.Get=function(x,y,z){if(Box2D.Common.Math.b2Vec3._freeCache.length&gt;0){var vec=Box2D.Common.Math.b2Vec3._freeCache.pop();vec.Set(x,y,z);return vec}return new Box2D.Common.Math.b2Vec3(x,y,z)};Box2D.Common.Math.b2Vec3.Free=function(vec){if(vec!=null){Box2D.Common.Math.b2Vec3._freeCache.push(vec)}};Box2D.Common.Math.b2Vec3.prototype.SetZero=function(){this.x=0;this.y=0;this.z=0};Box2D.Common.Math.b2Vec3.prototype.Set=function(x,y,z){this.x=x;this.y=y;this.z=z};Box2D.Common.Math.b2Vec3.prototype.SetV=function(v){this.x=v.x;this.y=v.y;this.z=v.z};Box2D.Common.Math.b2Vec3.prototype.GetNegative=function(){return Box2D.Common.Math.b2Vec3.Get(-this.x,-this.y,-this.z)};Box2D.Common.Math.b2Vec3.prototype.NegativeSelf=function(){this.x=-this.x;this.y=-this.y;this.z=-this.z};Box2D.Common.Math.b2Vec3.prototype.Copy=function(){return Box2D.Common.Math.b2Vec3.Get(this.x,this.y,this.z)};Box2D.Common.Math.b2Vec3.prototype.Add=function(v){this.x+=v.x;this.y+=v.y;this.z+=v.z};Box2D.Common.Math.b2Vec3.prototype.Subtract=function(v){this.x-=v.x;this.y-=v.y;this.z-=v.z};Box2D.Common.Math.b2Vec3.prototype.Multiply=function(a){this.x*=a;this.y*=a;this.z*=a};Box2D.Common.Math.b2Mat22=function(){this.col1=b2Vec2Get(1,0);this.col2=b2Vec2Get(0,1)};Box2D.Common.Math.b2Mat22._freeCache=[];var b2Mat22GetUninitialized=function(){if(Box2D.Common.Math.b2Mat22._freeCache.length&gt;0){return Box2D.Common.Math.b2Mat22._freeCache.pop()}else{return new Box2D.Common.Math.b2Mat22}};Box2D.Common.Math.b2Mat22.Get=function(){if(Box2D.Common.Math.b2Mat22._freeCache.length&gt;0){var mat=Box2D.Common.Math.b2Mat22._freeCache.pop();mat.SetIdentity();return mat}return new Box2D.Common.Math.b2Mat22};var b2Mat22GetAndInit=function(col1X,col1Y,col2X,col2Y){var result=b2Mat22GetUninitialized();var col1=result.col1;var col2=result.col2;col1.x=col1X;col1.y=col1Y;col2.x=col2X;col2.y=col2Y;return result};Box2D.Common.Math.b2Mat22.Free=function(mat){if(mat!=null){Box2D.Common.Math.b2Mat22._freeCache.push(mat)}};Box2D.Common.Math.b2Mat22.FromAngle=function(angle){var mat=Box2D.Common.Math.b2Mat22.Get();mat.Set(angle);return mat};Box2D.Common.Math.b2Mat22.FromVV=function(c1,c2){var mat=Box2D.Common.Math.b2Mat22.Get();mat.SetVV(c1,c2);return mat};Box2D.Common.Math.b2Mat22.prototype.Set=function(angle){var c=Math.cos(angle);var s=Math.sin(angle);var col1=this.col1;col1.x=c;col1.y=s;var col2=this.col2;col2.x=-s;col2.y=c};Box2D.Common.Math.b2Mat22.prototype.SetVV=function(c1,c2){this.col1.SetV(c1);this.col2.SetV(c2)};Box2D.Common.Math.b2Mat22.prototype.Copy=function(){var mat=Box2D.Common.Math.b2Mat22.Get();mat.SetM(this);return mat};Box2D.Common.Math.b2Mat22.prototype.SetM=function(m){this.col1.SetV(m.col1);this.col2.SetV(m.col2)};Box2D.Common.Math.b2Mat22.prototype.AddM=function(m){this.col1.Add(m.col1);this.col2.Add(m.col2)};Box2D.Common.Math.b2Mat22.prototype.SetIdentity=function(){this.col1.Set(1,0);this.col2.Set(0,1)};Box2D.Common.Math.b2Mat22.prototype.SetZero=function(){this.col1.Set(0,0);this.col2.Set(0,0)};Box2D.Common.Math.b2Mat22.prototype.GetAngle=function(){return Math.atan2(this.col1.y,this.col1.x)};Box2D.Common.Math.b2Mat22.prototype.GetInverse=function(out){var det=this.col1.x*this.col2.y-this.col2.x*this.col1.y;if(det!==0){det=1/det}out.col1.x=det*this.col2.y;out.col2.x=-det*this.col2.x;out.col1.y=-det*this.col1.y;out.col2.y=det*this.col1.x;return out};Box2D.Common.Math.b2Mat22.prototype.Solve=function(out,bX,bY){var det=this.col1.x*this.col2.y-this.col2.x*this.col1.y;if(det!==0){det=1/det}out.x=det*(this.col2.y*bX-this.col2.x*bY);out.y=det*(this.col1.x*bY-this.col1.y*bX);return out};Box2D.Common.Math.b2Mat22.prototype.Abs=function(){this.col1.Abs();this.col2.Abs()};Box2D.Common.Math.b2Mat33=function(c1,c2,c3){this.col1=Box2D.Common.Math.b2Vec3.Get(0,0,0);this.col2=Box2D.Common.Math.b2Vec3.Get(0,0,0);this.col3=Box2D.Common.Math.b2Vec3.Get(0,0,0);if(c1){this.col1.SetV(c1)}if(c2){this.col2.SetV(c2)}if(c3){this.col3.SetV(c3)}};Box2D.Common.Math.b2Mat33.prototype.SetVVV=function(c1,c2,c3){this.col1.SetV(c1);this.col2.SetV(c2);this.col3.SetV(c3)};Box2D.Common.Math.b2Mat33.prototype.Copy=function(){return new Box2D.Common.Math.b2Mat33(this.col1,this.col2,this.col3)};Box2D.Common.Math.b2Mat33.prototype.SetM=function(m){this.col1.SetV(m.col1);this.col2.SetV(m.col2);this.col3.SetV(m.col3)};Box2D.Common.Math.b2Mat33.prototype.AddM=function(m){this.col1.x+=m.col1.x;this.col1.y+=m.col1.y;this.col1.z+=m.col1.z;this.col2.x+=m.col2.x;this.col2.y+=m.col2.y;this.col2.z+=m.col2.z;this.col3.x+=m.col3.x;this.col3.y+=m.col3.y;this.col3.z+=m.col3.z};Box2D.Common.Math.b2Mat33.prototype.SetIdentity=function(){this.col1.Set(1,0,0);this.col2.Set(0,1,0);this.col3.Set(0,0,1)};Box2D.Common.Math.b2Mat33.prototype.SetZero=function(){this.col1.Set(0,0,0);this.col2.Set(0,0,0);this.col3.Set(0,0,0)};Box2D.Common.Math.b2Mat33.prototype.Solve22=function(out,bX,bY){var a11=this.col1.x;var a12=this.col2.x;var a21=this.col1.y;var a22=this.col2.y;var det=a11*a22-a12*a21;if(det!=0){det=1/det}out.x=det*(a22*bX-a12*bY);out.y=det*(a11*bY-a21*bX);return out};Box2D.Common.Math.b2Mat33.prototype.Solve33=function(out,bX,bY,bZ){var a11=this.col1.x;var a21=this.col1.y;var a31=this.col1.z;var a12=this.col2.x;var a22=this.col2.y;var a32=this.col2.z;var a13=this.col3.x;var a23=this.col3.y;var a33=this.col3.z;var det=a11*(a22*a33-a32*a23)+a21*(a32*a13-a12*a33)+a31*(a12*a23-a22*a13);if(det!=0){det=1/det}out.x=det*(bX*(a22*a33-a32*a23)+bY*(a32*a13-a12*a33)+bZ*(a12*a23-a22*a13));out.y=det*(a11*(bY*a33-bZ*a23)+a21*(bZ*a13-bX*a33)+a31*(bX*a23-bY*a13));out.z=det*(a11*(a22*bZ-a32*bY)+a21*(a32*bX-a12*bZ)+a31*(a12*bY-a22*bX));return out};Box2D.Common.Math.b2Sweep=function(){this.localCenter=Box2D.Common.Math.b2Vec2.Get(0,0);this.c0=Box2D.Common.Math.b2Vec2.Get(0,0);this.c=Box2D.Common.Math.b2Vec2.Get(0,0);this.a0=null;this.a=null;this.t0=null};Box2D.Common.Math.b2Sweep.prototype.Set=function(other){this.localCenter.SetV(other.localCenter);this.c0.SetV(other.c0);this.c.SetV(other.c);this.a0=other.a0;this.a=other.a;this.t0=other.t0};Box2D.Common.Math.b2Sweep.prototype.Copy=function(){var copy=new Box2D.Common.Math.b2Sweep;copy.localCenter.SetV(this.localCenter);copy.c0.SetV(this.c0);copy.c.SetV(this.c);copy.a0=this.a0;copy.a=this.a;copy.t0=this.t0;return copy};Box2D.Common.Math.b2Sweep.prototype.GetTransform=function(xf,alpha){if(alpha===undefined)alpha=0;xf.position.x=(1-alpha)*this.c0.x+alpha*this.c.x;xf.position.y=(1-alpha)*this.c0.y+alpha*this.c.y;var angle=(1-alpha)*this.a0+alpha*this.a;xf.R.Set(angle);var tMat=xf.R;xf.position.x-=tMat.col1.x*this.localCenter.x+tMat.col2.x*this.localCenter.y;xf.position.y-=tMat.col1.y*this.localCenter.x+tMat.col2.y*this.localCenter.y};Box2D.Common.Math.b2Sweep.prototype.Advance=function(t){if(t===undefined)t=0;if(this.t0&lt;t&amp;&amp;1-this.t0&gt;Number.MIN_VALUE){var alpha=(t-this.t0)/(1-this.t0);this.c0.x=(1-alpha)*this.c0.x+alpha*this.c.x;this.c0.y=(1-alpha)*this.c0.y+alpha*this.c.y;this.a0=(1-alpha)*this.a0+alpha*this.a;this.t0=t}};Box2D.Common.Math.b2Sweep._freeCache=[];Box2D.Common.Math.b2Sweep.Get=function(){if(Box2D.Common.Math.b2Sweep._freeCache.length&gt;0){var o=Box2D.Common.Math.b2Sweep._freeCache.pop();return o}return new Box2D.Common.Math.b2Sweep};Box2D.Common.Math.b2Sweep.Free=function(o){if(o!=null){Box2D.Common.Math.b2Sweep._freeCache.push(o)}};Box2D.Common.Math.b2Transform=function(pos,r){this.position=Box2D.Common.Math.b2Vec2.Get(0,0);this.R=Box2D.Common.Math.b2Mat22.Get();if(pos){this.position.SetV(pos)}if(r){this.R.SetM(r)}};Box2D.Common.Math.b2Transform.prototype.Initialize=function(pos,r){this.position.SetV(pos);this.R.SetM(r)};Box2D.Common.Math.b2Transform.prototype.SetIdentity=function(){this.position.SetZero();this.R.SetIdentity()};Box2D.Common.Math.b2Transform.prototype.Set=function(x){this.position.SetV(x.position);this.R.SetM(x.R)};Box2D.Common.Math.b2Transform.prototype.GetAngle=function(){return Math.atan2(this.R.col1.y,this.R.col1.x)};Box2D.Common.Math.b2Transform._freeCache=[];Box2D.Common.Math.b2Transform.Get=function(){if(Box2D.Common.Math.b2Transform._freeCache.length&gt;0){var o=Box2D.Common.Math.b2Transform._freeCache.pop();o.SetIdentity();return o}return new Box2D.Common.Math.b2Transform};Box2D.Common.Math.b2Transform.Free=function(o){if(o!=null){Box2D.Common.Math.b2Transform._freeCache.push(o)}};Box2D.Common.Math.b2Math={};var b2MathClamp=function(a,low,high){return a&lt;low?low:a&gt;high?high:a};Box2D.Common.Math.b2Math.Clamp=b2MathClamp;var b2MathDot=function(a,b){return a.x*b.x+a.y*b.y};Box2D.Common.Math.b2Math.Dot=b2MathDot;var b2MathCrossVV=function(a,b){return a.x*b.y-a.y*b.x};Box2D.Common.Math.b2Math.CrossVV=b2MathCrossVV;var b2MathDistanceSquared=function(a,b){var cX=a.x-b.x;var cY=a.y-b.y;return cX*cX+cY*cY};Box2D.Common.Math.b2Math.DistanceSquared=b2MathDistanceSquared;var b2MathDistance=function(a,b){var cX=a.x-b.x;var cY=a.y-b.y;return Math.sqrt(cX*cX+cY*cY)};Box2D.Common.Math.b2Math.Distance=b2MathDistance;var b2MathAddVVInPlace=function(a,b,r){r.x=a.x+b.y;r.y=a.y+b.y};var b2MathSubtractVVInPlace=function(a,b,r){r.x=a.x-b.x;r.y=a.y-b.y};var b2MathMulXInPlace=function(T,v,r){var R=T.R;var col1=R.col1;var col2=R.col2;var position=T.position;var x=v.x;var y=v.y;r.x=col1.x*x+col2.x*y+position.x;r.y=col1.y*x+col2.y*y+position.y};var b2MathCrossVFInPlace=function(a,s,r){r.x=s*a.y;r.y=-s*a.x};var b2dMathCrossFVInPlace=function(s,a,r){r.x=-s*a.y;r.y=s*a.x};var b2MathMulMVInPlace=function(A,v,r){var col1=A.col1;var col2=A.col2;var vx=v.x;var vy=v.y;r.x=col1.x*vx+col2.x*vy;r.y=col1.y*vx+col2.y*vy};var b2MathMulTMVInPlace=function(A,v,r){var vx=v.x;var vy=v.y;var col1=A.col1;var col2=A.col2;r.x=vx*col1.x+vy*col1.y;r.y=vx*col2.x+vy*col2.y};var b2MathAbsVInPlace=function(a,r){r.x=Math.abs(a.x);r.y=Math.abs(a.y)};var b2MathCrossVF=function(a,s){return b2Vec2Get(s*a.y,-s*a.x)};Box2D.Common.Math.b2Math.CrossVF=b2MathCrossVF;var b2dMathCrossFV=function(s,a){return b2Vec2Get(-s*a.y,s*a.x)};Box2D.Common.Math.b2Math.CrossFV=b2dMathCrossFV;var b2MathMulMV=function(A,v){var col1=A.col1;var col2=A.col2;var vx=v.x;var vy=v.y;return b2Vec2Get(col1.x*vx+col2.x*vy,col1.y*vx+col2.y*vy)};Box2D.Common.Math.b2Math.MulMV=b2MathMulMV;var b2MathMulTMV=function(A,v){var vx=v.x;var vy=v.y;var col1=A.col1;var col2=A.col2;return b2Vec2Get(vx*col1.x+vy*col1.y,vx*col2.x+vy*col2.y)};Box2D.Common.Math.b2Math.MulTMV=b2MathMulTMV;Box2D.Common.Math.b2Math.MulX=function(T,v){var r=b2Vec2Get(0,0);b2MathMulXInPlace(T,v,r);return r};var b2MathAddVV=function(a,b){return b2Vec2Get(a.x+b.x,a.y+b.y)};Box2D.Common.Math.b2Math.AddVV=b2MathAddVV;var b2MathSubtractVV=function(a,b){return b2Vec2Get(a.x-b.x,a.y-b.y)};Box2D.Common.Math.b2Math.SubtractVV=b2MathSubtractVV;var b2MathMulFV=function(s,a){return b2Vec2Get(s*a.x,s*a.y)};Box2D.Common.Math.b2Math.MulFV=b2MathMulFV;Box2D.Common.Math.b2Math.MulXT=function(T,v){var a=b2MathSubtractVV(v,T.position);var tX=a.x*T.R.col1.x+a.y*T.R.col1.y;a.y=a.x*T.R.col2.x+a.y*T.R.col2.y;a.x=tX;return a};Box2D.Common.Math.b2Math.AddMM=function(A,B){var colA1=A.col1;var colA2=A.col2;var colB1=B.col1;var colB2=B.col2;return b2Mat22GetAndInit(colA1.x+colB1.x,colA1.y+colB1.y,colA2.x+colB2.x,colA2.y+colB2.y)};Box2D.Common.Math.b2Math.MulMM=function(A,B){var v1=Box2D.Common.Math.b2Math.MulMV(A,B.col1);var v2=Box2D.Common.Math.b2Math.MulMV(A,B.col2);var m=Box2D.Common.Math.b2Mat22.FromVV(v1,v2);b2Vec2Free(v1);b2Vec2Free(v2);return m};var b2MathMulTMM_c1=b2Vec2Get(0,0);var b2MathMulTMM_c2=b2Vec2Get(0,0);Box2D.Common.Math.b2Math.MulTMM=function(A,B){b2MathMulTMM_c1.x=b2MathDot(A.col1,B.col1);b2MathMulTMM_c1.y=b2MathDot(A.col2,B.col1);b2MathMulTMM_c2.x=b2MathDot(A.col1,B.col2);b2MathMulTMM_c2.y=b2MathDot(A.col2,B.col2);var m=Box2D.Common.Math.b2Mat22.FromVV(b2MathMulTMM_c1,b2MathMulTMM_c2);return m};var b2MathAbsV=function(a){return b2Vec2Get(Math.abs(a.x),Math.abs(a.y))};Box2D.Common.Math.b2Math.AbsV=b2MathAbsV;var b2MathAbsM_v1=b2Vec2Get(0,0);var b2MathAbsM_v2=b2Vec2Get(0,0);Box2D.Common.Math.b2Math.AbsM=function(A){b2MathAbsVInPlace(A.col1,b2MathAbsM_v1);b2MathAbsVInPlace(A.col2,b2MathAbsM_v2);var m=Box2D.Common.Math.b2Mat22.FromVV(b2MathAbsM_v1,b2MathAbsM_v2);return m};var b2MathClamp01=function(a){return a&lt;0?0:a&gt;1?1:a};Box2D.Common.Math.b2Math.Clamp01=b2MathClamp01;var b2MathClampV=function(a,low,high){var x=b2MathClamp(a.x,low.x,high.x);var y=b2MathClamp(a.y,low.y,high.y);return b2Vec2Get(x,y)};Box2D.Common.Math.b2Math.ClampV=b2MathClampV;Box2D.Collision.b2AABB=function(){this.lowerBound=Box2D.Common.Math.b2Vec2.Get(0,0);this.upperBound=Box2D.Common.Math.b2Vec2.Get(0,0)};Box2D.Collision.b2AABB._freeCache=[];Box2D.Collision.b2AABB.Get=function(){if(Box2D.Collision.b2AABB._freeCache.length&gt;0){var aabb=Box2D.Collision.b2AABB._freeCache.pop();aabb.SetZero();return aabb}return new Box2D.Collision.b2AABB};Box2D.Collision.b2AABB.Free=function(aabb){if(aabb!=null){Box2D.Collision.b2AABB._freeCache.push(aabb)}};Box2D.Collision.b2AABB.prototype.Set=function(lowerX,lowerY,upperX,upperY){this.lowerBound.Set(lowerX,lowerY);this.upperBound.Set(upperX,upperY)};Box2D.Collision.b2AABB.prototype.SetVV=function(lowerBound,upperBound){this.lowerBound.SetV(lowerBound);this.upperBound.SetV(upperBound)};Box2D.Collision.b2AABB.prototype.SetZero=function(){this.lowerBound.Set(0,0);this.upperBound.Set(0,0)};Box2D.Collision.b2AABB.prototype.IsValid=function(){var dX=this.upperBound.x-this.lowerBound.x;if(dX&lt;0){return false}var dY=this.upperBound.y-this.lowerBound.y;if(dY&lt;0){return false}return this.lowerBound.IsValid()&amp;&amp;this.upperBound.IsValid()};Box2D.Collision.b2AABB.prototype.GetCenter=function(){return Box2D.Common.Math.b2Vec2.Get((this.lowerBound.x+this.upperBound.x)/2,(this.lowerBound.y+this.upperBound.y)/2)};Box2D.Collision.b2AABB.prototype.SetCenter=function(newCenter){var oldCenter=this.GetCenter();this.lowerBound.Subtract(oldCenter);this.upperBound.Subtract(oldCenter);this.lowerBound.Add(newCenter);this.upperBound.Add(newCenter);Box2D.Common.Math.b2Vec2.Free(oldCenter)};Box2D.Collision.b2AABB.prototype.GetExtents=function(){return Box2D.Common.Math.b2Vec2.Get((this.upperBound.x-this.lowerBound.x)/2,(this.upperBound.y-this.lowerBound.y)/2)};Box2D.Collision.b2AABB.prototype.Contains=function(aabb){var result=true;result=result&amp;&amp;this.lowerBound.x&lt;=aabb.lowerBound.x;result=result&amp;&amp;this.lowerBound.y&lt;=aabb.lowerBound.y;result=result&amp;&amp;aabb.upperBound.x&lt;=this.upperBound.x;result=result&amp;&amp;aabb.upperBound.y&lt;=this.upperBound.y;return result};Box2D.Collision.b2AABB.prototype.RayCast=function(output,input){var tmin=-Number.MAX_VALUE;var tmax=Number.MAX_VALUE;var dX=input.p2.x-input.p1.x;var absDX=Math.abs(dX);if(absDX&lt;Number.MIN_VALUE){if(input.p1.x&lt;this.lowerBound.x||this.upperBound.x&lt;input.p1.x){return false}}else{var inv_d=1/dX;var t1=(this.lowerBound.x-input.p1.x)*inv_d;var t2=(this.upperBound.x-input.p1.x)*inv_d;var s=-1;if(t1&gt;t2){var t3=t1;t1=t2;t2=t3;s=1}if(t1&gt;tmin){output.normal.x=s;output.normal.y=0;tmin=t1}tmax=Math.min(tmax,t2);if(tmin&gt;tmax)return false}var dY=input.p2.y-input.p1.y;var absDY=Math.abs(dY);if(absDY&lt;Number.MIN_VALUE){if(input.p1.y&lt;this.lowerBound.y||this.upperBound.y&lt;input.p1.y){return false}}else{var inv_d=1/dY;var t1=(this.lowerBound.y-input.p1.y)*inv_d;var t2=(this.upperBound.y-input.p1.y)*inv_d;var s=-1;if(t1&gt;t2){var t3=t1;t1=t2;t2=t3;s=1}if(t1&gt;tmin){output.normal.y=s;output.normal.x=0;tmin=t1}tmax=Math.min(tmax,t2);if(tmin&gt;tmax){return false}}output.fraction=tmin;return true};Box2D.Collision.b2AABB.prototype.TestOverlap=function(other){if(other.lowerBound.x-this.upperBound.x&gt;0){return false}if(other.lowerBound.y-this.upperBound.y&gt;0){return false}if(this.lowerBound.x-other.upperBound.x&gt;0){return false}if(this.lowerBound.y-other.upperBound.y&gt;0){return false}return true};Box2D.Collision.b2AABB.Combine=function(aabb1,aabb2){var aabb=Box2D.Collision.b2AABB.Get();aabb.Combine(aabb1,aabb2);return aabb};Box2D.Collision.b2AABB.prototype.Combine=function(aabb1,aabb2){this.lowerBound.x=Math.min(aabb1.lowerBound.x,aabb2.lowerBound.x);this.lowerBound.y=Math.min(aabb1.lowerBound.y,aabb2.lowerBound.y);this.upperBound.x=Math.max(aabb1.upperBound.x,aabb2.upperBound.x);this.upperBound.y=Math.max(aabb1.upperBound.y,aabb2.upperBound.y)};Box2D.Collision.b2AABB.prototype.GetMinX=function(){return this.lowerBound.x};Box2D.Collision.b2AABB.prototype.GetMaxX=function(){return this.upperBound.x};Box2D.Collision.b2AABB.prototype.GetMinY=function(){return this.lowerBound.y};Box2D.Collision.b2AABB.prototype.GetMaxY=function(){return this.upperBound.y};Box2D.Dynamics.iContactFilter=function(){};Box2D.Dynamics.iContactFilter.prototype.ShouldCollide=function(fixtureA,fixtureB){};Box2D.Dynamics.iContactListener=function(){};Box2D.Dynamics.iContactListener.prototype.BeginContact=function(contact){};Box2D.Dynamics.iContactListener.prototype.EndContact=function(contact){};Box2D.Dynamics.iContactListener.prototype.PreSolve=function(contact,oldManifold){};Box2D.Dynamics.iContactListener.prototype.PostSolve=function(contact,impulse){};Box2D.Dynamics.b2Body=function(bd,world){this.ID=Box2D.Dynamics.b2Body.NEXT_ID++;if(!this.m_xf){this.m_xf=Box2D.Common.Math.b2Transform.Get()}this.m_xf.position.SetV(bd.position);this.m_xf.R.Set(bd.angle);if(!this.m_sweep){this.m_sweep=Box2D.Common.Math.b2Sweep.Get()}this.m_sweep.localCenter.SetZero();this.m_sweep.t0=1;this.m_sweep.a0=this.m_sweep.a=bd.angle;this.m_sweep.c.x=this.m_xf.R.col1.x*this.m_sweep.localCenter.x+this.m_xf.R.col2.x*this.m_sweep.localCenter.y;this.m_sweep.c.y=this.m_xf.R.col1.y*this.m_sweep.localCenter.x+this.m_xf.R.col2.y*this.m_sweep.localCenter.y;this.m_sweep.c.x+=this.m_xf.position.x;this.m_sweep.c.y+=this.m_xf.position.y;this.m_sweep.c0.SetV(this.m_sweep.c);if(!this.m_linearVelocity){this.m_linearVelocity=bd.linearVelocity.Copy()}else{this.m_linearVelocity.SetV(bd.linearVelocity)}if(!this.m_force){this.m_force=Box2D.Common.Math.b2Vec2.Get(0,0)}else{this.m_force.Set(0,0)}this.m_bullet=bd.bullet;this.m_fixedRotation=bd.fixedRotation;this.m_allowSleep=bd.allowSleep;this.m_awake=bd.awake;this.m_active=bd.active;this.m_world=world;this.m_jointList=null;if(!this.contactList){this.contactList=new Box2D.Dynamics.Contacts.b2ContactList}if(!this.controllerList){this.controllerList=new Box2D.Dynamics.Controllers.b2ControllerList}this.m_controllerCount=0;this.m_angularVelocity=bd.angularVelocity;this.m_linearDamping=bd.linearDamping;this.m_angularDamping=bd.angularDamping;this.m_torque=0;this.m_sleepTime=0;this.m_type=bd.type;this.m_mass=this.m_type==Box2D.Dynamics.b2BodyDef.b2_dynamicBody?1:0;this.m_invMass=this.m_type==Box2D.Dynamics.b2BodyDef.b2_dynamicBody?1:0;this.m_massOffset=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_I=0;this.m_invI=0;this.m_inertiaScale=bd.inertiaScale;if(!this.fixtureList){this.fixtureList=Box2D.Dynamics.b2FixtureList.Get()}if(!this.m_lists){this.m_lists=Box2D.Array.Get()}};Box2D.Dynamics.b2Body._freeCache=[];Box2D.Dynamics.b2Body.Get=function(bd,world){var cache=this._freeCache;var o;if(cache.length&gt;0){o=cache.pop();this.call(o,bd,world)}else{o=new this(bd,world)}return o};Box2D.Dynamics.b2Body.Free=function(o){this._freeCache.push(o)};Box2D.Dynamics.b2Body.prototype.CreateFixture=function(def){Box2D.Common.b2Settings.b2Assert(!this.m_world.IsLocked());var fixture=Box2D.Dynamics.b2Fixture.Get(this,this.m_xf,def);if(this.m_active){var broadPhase=this.m_world.m_contactManager.m_broadPhase;fixture.CreateProxy(broadPhase,this.m_xf)}this.fixtureList.AddFixture(fixture);fixture.m_body=this;if(fixture.m_density&gt;0){this.ResetMassData()}this.m_world.m_newFixture=true;return fixture};Box2D.Dynamics.b2Body.prototype.CreateFixture2=function(shape,density){var def=new Box2D.Dynamics.b2FixtureDef;def.shape=shape;def.density=density;return this.CreateFixture(def)};Box2D.Dynamics.b2Body.prototype.Destroy=function(){Box2D.Dynamics.b2Body.Free(this)};Box2D.Dynamics.b2Body.prototype.DestroyFixture=function(fixture){Box2D.Common.b2Settings.b2Assert(!this.m_world.IsLocked());this.fixtureList.RemoveFixture(fixture);for(var contactNode=this.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){if(fixture==contactNode.contact.GetFixtureA()||fixture==contactNode.contact.GetFixtureB()){this.m_world.m_contactManager.Destroy(contactNode.contact)}}if(this.m_active){var broadPhase=this.m_world.m_contactManager.m_broadPhase;fixture.DestroyProxy(broadPhase)}fixture.Destroy();this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.SetPositionAndAngle=function(position,angle){Box2D.Common.b2Settings.b2Assert(!this.m_world.IsLocked());this.m_xf.R.Set(angle);this.m_xf.position.SetV(position);var tMat=this.m_xf.R;var tVec=this.m_sweep.localCenter;this.m_sweep.c.x=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;this.m_sweep.c.y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;this.m_sweep.c.x+=this.m_xf.position.x;this.m_sweep.c.y+=this.m_xf.position.y;this.m_sweep.c0.SetV(this.m_sweep.c);this.m_sweep.a0=this.m_sweep.a=angle;var broadPhase=this.m_world.m_contactManager.m_broadPhase;for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.Synchronize(broadPhase,this.m_xf,this.m_xf)}this.m_world.m_contactManager.FindNewContacts()};Box2D.Dynamics.b2Body.prototype.SetTransform=function(xf){this.SetPositionAndAngle(xf.position,xf.GetAngle())};Box2D.Dynamics.b2Body.prototype.GetTransform=function(){return this.m_xf};Box2D.Dynamics.b2Body.prototype.GetPosition=function(){return this.m_xf.position};Box2D.Dynamics.b2Body.prototype.SetPosition=function(position){this.SetPositionAndAngle(position,this.GetAngle())};Box2D.Dynamics.b2Body.prototype.GetAngle=function(){return this.m_sweep.a};Box2D.Dynamics.b2Body.prototype.SetCalculatedAngle=function(angle){this.m_sweep.a=angle};Box2D.Dynamics.b2Body.prototype.SetAngle=function(angle){this.SetPositionAndAngle(this.GetPosition(),angle)};Box2D.Dynamics.b2Body.prototype.GetWorldCenter=function(){return this.m_sweep.c};Box2D.Dynamics.b2Body.prototype.GetLocalCenter=function(){return this.m_sweep.localCenter};Box2D.Dynamics.b2Body.prototype.SetLinearVelocity=function(v){if(this.m_type==Box2D.Dynamics.b2BodyDef.b2_staticBody){return}this.m_linearVelocity.SetV(v)};Box2D.Dynamics.b2Body.prototype.GetLinearVelocity=function(){return this.m_linearVelocity};Box2D.Dynamics.b2Body.prototype.SetAngularVelocity=function(omega){if(this.m_type==Box2D.Dynamics.b2BodyDef.b2_staticBody){return}this.m_angularVelocity=omega};Box2D.Dynamics.b2Body.prototype.GetAngularVelocity=function(){return this.m_angularVelocity};Box2D.Dynamics.b2Body.prototype.GetDefinition=function(){var bd=new Box2D.Dynamics.b2BodyDef;bd.type=this.GetType();bd.allowSleep=this.m_allowSleep;bd.angle=this.GetAngle();bd.angularDamping=this.m_angularDamping;bd.angularVelocity=this.m_angularVelocity;bd.fixedRotation=this.m_fixedRotation;bd.bullet=this.m_bullet;bd.active=this.m_active;bd.awake=this.m_awake;bd.linearDamping=this.m_linearDamping;bd.linearVelocity.SetV(this.GetLinearVelocity());bd.position.SetV(this.GetPosition());return bd};Box2D.Dynamics.b2Body.prototype.ApplyForce=function(force,point){if(this.m_type!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody){return}this.SetAwake(true);this.m_force.x+=force.x;this.m_force.y+=force.y;this.m_torque+=(point.x-this.m_sweep.c.x)*force.y-(point.y-this.m_sweep.c.y)*force.x};Box2D.Dynamics.b2Body.prototype.ApplyTorque=function(torque){if(this.m_type!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody){return}this.SetAwake(true);this.m_torque+=torque};Box2D.Dynamics.b2Body.prototype.ApplyImpulse=function(impulse,point){if(this.m_type!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody){return}this.SetAwake(true);this.m_linearVelocity.x+=this.m_invMass*impulse.x;this.m_linearVelocity.y+=this.m_invMass*impulse.y;this.m_angularVelocity+=this.m_invI*((point.x-this.m_sweep.c.x)*impulse.y-(point.y-this.m_sweep.c.y)*impulse.x)};Box2D.Dynamics.b2Body.prototype.Split=function(callback){var linearVelocity=this.GetLinearVelocity().Copy();var angularVelocity=this.GetAngularVelocity();var center=this.GetWorldCenter();var body1=this;var body2=this.m_world.CreateBody(this.GetDefinition());for(var node=body1.fixtureList.GetFirstNode();node;node=node.GetNextNode()){var f=node.fixture;if(callback(f)){body1.fixtureList.RemoveFixture(f);body2.fixtureList.AddFixture(f)}}body1.ResetMassData();body2.ResetMassData();var center1=body1.GetWorldCenter();var center2=body2.GetWorldCenter();var center1Diff=Box2D.Common.Math.b2Math.SubtractVV(center1,center);var center1Cross=Box2D.Common.Math.b2Math.CrossFV(angularVelocity,center1Diff);Box2D.Common.Math.b2Vec2.Free(center1Diff);var velocity1=Box2D.Common.Math.b2Math.AddVV(linearVelocity,center1Cross);Box2D.Common.Math.b2Vec2.Free(center1Cross);body1.SetLinearVelocity(velocity1);Box2D.Common.Math.b2Vec2.Free(velocity1);var center2Diff=Box2D.Common.Math.b2Math.SubtractVV(center2,center);var center2Cross=Box2D.Common.Math.b2Math.CrossFV(angularVelocity,center2Diff);Box2D.Common.Math.b2Vec2.Free(center2Diff);var velocity2=Box2D.Common.Math.b2Math.AddVV(linearVelocity,center2Cross);Box2D.Common.Math.b2Vec2.Free(center2Cross);body2.SetLinearVelocity(velocity2);Box2D.Common.Math.b2Vec2.Free(velocity2);Box2D.Common.Math.b2Vec2.Free(linearVelocity);body1.SetAngularVelocity(angularVelocity);body2.SetAngularVelocity(angularVelocity);body1.SynchronizeFixtures();body2.SynchronizeFixtures();return body2};Box2D.Dynamics.b2Body.prototype.Merge=function(other){for(var node=other.fixtureList.GetFirstNode();node;node=node.GetNextNode()){this.fixtureList.AddFixture(node.fixture);other.fixtureList.RemoveFixture(node.fixture)}other.ResetMassData();this.ResetMassData();this.SynchronizeFixtures()};Box2D.Dynamics.b2Body.prototype.GetMass=function(){return this.m_mass};Box2D.Dynamics.b2Body.prototype.GetInverseMass=function(){return this.m_invMass};Box2D.Dynamics.b2Body.prototype.GetInertia=function(){return this.m_I};Box2D.Dynamics.b2Body.prototype.GetInverseInertia=function(){return this.m_invI};Box2D.Dynamics.b2Body.prototype.GetMassData=function(massData){if(!massData){massData=Box2D.Collision.Shapes.b2MassData.Get()}massData.mass=this.m_mass;massData.I=this.m_I;massData.center.SetV(this.m_sweep.localCenter);return massData};Box2D.Dynamics.b2Body.prototype.SetMassData=function(massData){Box2D.Common.b2Settings.b2Assert(!this.m_world.IsLocked());if(this.m_type!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody){return}this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_mass=massData.mass;if(this.m_mass&lt;=0){this.m_mass=1}this.m_invMass=1/this.m_mass;if(massData.I&gt;0&amp;&amp;!this.m_fixedRotation){this.m_I=massData.I-this.m_mass*(massData.center.x*massData.center.x+massData.center.y*massData.center.y);this.m_invI=1/this.m_I}var oldCenter=this.m_sweep.c.Copy();this.m_sweep.localCenter.SetV(massData.center);this.m_sweep.c0.SetV(Box2D.Common.Math.b2Math.MulX(this.m_xf,this.m_sweep.localCenter));this.m_sweep.c.SetV(this.m_sweep.c0);this.m_linearVelocity.x+=this.m_angularVelocity*-(this.m_sweep.c.y-oldCenter.y);this.m_linearVelocity.y+=this.m_angularVelocity*+(this.m_sweep.c.x-oldCenter.x);Box2D.Common.Math.b2Vec2.Free(oldCenter)};Box2D.Dynamics.b2Body.prototype.GetMassOffset=function(){return this.m_massOffset};Box2D.Dynamics.b2Body.prototype.SetMassOffset=function(offset){this.m_massOffset.x=offset.x;this.m_massOffset.y=offset.y;this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.ResetMassData=function(){this.m_mass=0;this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_sweep.localCenter.SetZero();if(this.m_type==Box2D.Dynamics.b2BodyDef.b2_staticBody||this.m_type==Box2D.Dynamics.b2BodyDef.b2_kinematicBody){return}var center=Box2D.Common.Math.b2Vec2.Get(0,0);for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){var f=node.fixture;if(f.m_density==0){continue}var massData=f.GetMassData();this.m_mass+=massData.mass;center.x+=massData.center.x*massData.mass;center.y+=massData.center.y*massData.mass;this.m_I+=massData.I;Box2D.Collision.Shapes.b2MassData.Free(massData)}if(this.m_mass&gt;0){this.m_invMass=1/this.m_mass;center.x*=this.m_invMass;center.y*=this.m_invMass}else{this.m_mass=1;this.m_invMass=1}if(this.m_I&gt;0&amp;&amp;!this.m_fixedRotation){this.m_I-=this.m_mass*(center.x*center.x+center.y*center.y);this.m_I*=this.m_inertiaScale;Box2D.Common.b2Settings.b2Assert(this.m_I&gt;0);this.m_invI=1/this.m_I}else{this.m_I=0;this.m_invI=0}center.x+=this.m_massOffset.x;center.y+=this.m_massOffset.y;var oldCenter=this.m_sweep.c.Copy();this.m_sweep.localCenter.SetV(center);var c0temp=Box2D.Common.Math.b2Math.MulX(this.m_xf,this.m_sweep.localCenter);this.m_sweep.c0.SetV(c0temp);this.m_sweep.c.SetV(this.m_sweep.c0);this.m_linearVelocity.x+=this.m_angularVelocity*-(this.m_sweep.c.y-oldCenter.y);this.m_linearVelocity.y+=this.m_angularVelocity*+(this.m_sweep.c.x-oldCenter.x);Box2D.Common.Math.b2Vec2.Free(center);Box2D.Common.Math.b2Vec2.Free(oldCenter);Box2D.Common.Math.b2Vec2.Free(c0temp)};Box2D.Dynamics.b2Body.prototype.GetWorldPoint=function(localPoint){var A=this.m_xf.R;var u=Box2D.Common.Math.b2Vec2.Get(A.col1.x*localPoint.x+A.col2.x*localPoint.y,A.col1.y*localPoint.x+A.col2.y*localPoint.y);u.x+=this.m_xf.position.x;u.y+=this.m_xf.position.y;return u};Box2D.Dynamics.b2Body.prototype.GetWorldVector=function(localVector){return Box2D.Common.Math.b2Math.MulMV(this.m_xf.R,localVector)};Box2D.Dynamics.b2Body.prototype.GetLocalPoint=function(worldPoint){return Box2D.Common.Math.b2Math.MulXT(this.m_xf,worldPoint)};Box2D.Dynamics.b2Body.prototype.GetLocalVector=function(worldVector){return Box2D.Common.Math.b2Math.MulTMV(this.m_xf.R,worldVector)};Box2D.Dynamics.b2Body.prototype.GetLinearVelocityFromWorldPoint=function(worldPoint){return Box2D.Common.Math.b2Vec2.Get(this.m_linearVelocity.x-this.m_angularVelocity*(worldPoint.y-this.m_sweep.c.y),this.m_linearVelocity.y+this.m_angularVelocity*(worldPoint.x-this.m_sweep.c.x))};Box2D.Dynamics.b2Body.prototype.GetLinearVelocityFromLocalPoint=function(localPoint){var A=this.m_xf.R;var worldPoint=Box2D.Common.Math.b2Vec2.Get(A.col1.x*localPoint.x+A.col2.x*localPoint.y,A.col1.y*localPoint.x+A.col2.y*localPoint.y);worldPoint.x+=this.m_xf.position.x;worldPoint.y+=this.m_xf.position.y;var velocity=Box2D.Common.Math.b2Vec2.Get(this.m_linearVelocity.x-this.m_angularVelocity*(worldPoint.y-this.m_sweep.c.y),this.m_linearVelocity.y+this.m_angularVelocity*(worldPoint.x-this.m_sweep.c.x));Box2D.Common.Math.b2Vec2.Free(worldPoint);return velocity};Box2D.Dynamics.b2Body.prototype.GetLinearDamping=function(){return this.m_linearDamping};Box2D.Dynamics.b2Body.prototype.SetLinearDamping=function(linearDamping){this.m_linearDamping=linearDamping};Box2D.Dynamics.b2Body.prototype.GetAngularDamping=function(){return this.m_angularDamping};Box2D.Dynamics.b2Body.prototype.SetAngularDamping=function(angularDamping){this.m_angularDamping=angularDamping};Box2D.Dynamics.b2Body.prototype.SetType=function(type){if(this.m_type==type){return}this.m_type=type;this.ResetMassData();if(this.m_type==Box2D.Dynamics.b2BodyDef.b2_staticBody){this.m_linearVelocity.SetZero();this.m_angularVelocity=0}this.SetAwake(true);this.m_force.SetZero();this.m_torque=0;for(var contactNode=this.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){contactNode.contact.FlagForFiltering()}for(var i=0;i&lt;this.m_lists.length;i++){this.m_lists[i].UpdateBody(this)}};Box2D.Dynamics.b2Body.prototype.GetType=function(){return this.m_type};Box2D.Dynamics.b2Body.prototype.SetBullet=function(flag){this.m_bullet=flag};Box2D.Dynamics.b2Body.prototype.IsBullet=function(){return this.m_bullet};Box2D.Dynamics.b2Body.prototype.SetSleepingAllowed=function(flag){this.m_allowSleep=flag;if(!flag){this.SetAwake(true)}};Box2D.Dynamics.b2Body.prototype.SetAwake=function(flag){if(this.m_awake!=flag){this.m_awake=flag;this.m_sleepTime=0;if(!flag){this.m_linearVelocity.SetZero();this.m_angularVelocity=0;this.m_force.SetZero();this.m_torque=0}for(var i=0;i&lt;this.m_lists.length;i++){this.m_lists[i].UpdateBody(this)}}};Box2D.Dynamics.b2Body.prototype.IsAwake=function(){return this.m_awake};Box2D.Dynamics.b2Body.prototype.SetFixedRotation=function(fixed){this.m_fixedRotation=fixed;this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.IsFixedRotation=function(){return this.m_fixedRotation};Box2D.Dynamics.b2Body.prototype.SetActive=function(flag){if(flag==this.m_active){return}if(flag){this.m_active=true;var broadPhase=this.m_world.m_contactManager.m_broadPhase;for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.CreateProxy(broadPhase,this.m_xf)}}else{this.m_active=false;var broadPhase=this.m_world.m_contactManager.m_broadPhase;for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.DestroyProxy(broadPhase)}for(var contactNode=this.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){this.m_world.m_contactManager.Destroy(contactNode.contact)}}for(var i=0;i&lt;this.m_lists.length;i++){this.m_lists[i].UpdateBody(this)}};Box2D.Dynamics.b2Body.prototype.IsActive=function(){return this.m_active};Box2D.Dynamics.b2Body.prototype.IsSleepingAllowed=function(){return this.m_allowSleep};Box2D.Dynamics.b2Body.prototype.GetFixtureList=function(){return this.fixtureList};Box2D.Dynamics.b2Body.prototype.GetJointList=function(){return this.m_jointList};Box2D.Dynamics.b2Body.prototype.GetControllerList=function(){return this.controllerList};Box2D.Dynamics.b2Body.prototype.AddController=function(controller){this.controllerList.AddController(controller)};Box2D.Dynamics.b2Body.prototype.RemoveController=function(controller){this.controllerList.RemoveController(controller)};Box2D.Dynamics.b2Body.prototype.GetContactList=function(){return this.contactList};Box2D.Dynamics.b2Body.prototype.GetWorld=function(){return this.m_world};Box2D.Dynamics.b2Body.prototype.SynchronizeFixtures=function(){var xf1=Box2D.Dynamics.b2Body.s_xf1;xf1.R.Set(this.m_sweep.a0);var tMat=xf1.R;var tVec=this.m_sweep.localCenter;xf1.position.x=this.m_sweep.c0.x-(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);xf1.position.y=this.m_sweep.c0.y-(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);var broadPhase=this.m_world.m_contactManager.m_broadPhase;for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.Synchronize(broadPhase,xf1,this.m_xf)}};Box2D.Dynamics.b2Body.prototype.SynchronizeTransform=function(){this.m_xf.R.Set(this.m_sweep.a);var tMat=this.m_xf.R;var tVec=this.m_sweep.localCenter;this.m_xf.position.x=this.m_sweep.c.x-(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);this.m_xf.position.y=this.m_sweep.c.y-(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y)};Box2D.Dynamics.b2Body.prototype.ShouldCollide=function(other){if(this.m_type!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody&amp;&amp;other.m_type!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody){return false}for(var jn=this.m_jointList;jn;jn=jn.next){if(jn.other==other)if(jn.joint.m_collideConnected==false){return false}}return true};Box2D.Dynamics.b2Body.prototype.Advance=function(t){this.m_sweep.Advance(t);this.m_sweep.c.SetV(this.m_sweep.c0);this.m_sweep.a=this.m_sweep.a0;this.SynchronizeTransform()};Box2D.Dynamics.b2Body.NEXT_ID=0;Box2D.Dynamics.b2Body.s_xf1=new Box2D.Common.Math.b2Transform;Box2D.Dynamics.b2BodyDef=function(){this.position=Box2D.Common.Math.b2Vec2.Get(0,0);this.linearVelocity=Box2D.Common.Math.b2Vec2.Get(0,0);this.angle=0;this.angularVelocity=0;this.linearDamping=0;this.angularDamping=0;this.allowSleep=true;this.awake=true;this.fixedRotation=false;this.bullet=false;this.type=Box2D.Dynamics.b2BodyDef.b2_staticBody;this.active=true;this.inertiaScale=1};Box2D.Dynamics.b2BodyDef.b2_staticBody=0;Box2D.Dynamics.b2BodyDef.b2_kinematicBody=1;Box2D.Dynamics.b2BodyDef.b2_dynamicBody=2;Box2D.Dynamics.b2BodyList=function(){this.bodyFirstNodes=Box2D.Array.Get();for(var i=0;i&lt;=Box2D.Dynamics.b2BodyList.TYPES.allBodies;i++){this.bodyFirstNodes[i]=null}this.bodyLastNodes=Box2D.Array.Get();for(var i=0;i&lt;=Box2D.Dynamics.b2BodyList.TYPES.allBodies;i++){this.bodyLastNodes[i]=null}this.bodyNodeLookup={};this.bodyCount=0};Box2D.Dynamics.b2BodyList.prototype.GetFirstNode=function(type){return this.bodyFirstNodes[type]};Box2D.Dynamics.b2BodyList.prototype.AddBody=function(body){var bodyID=body.ID;if(this.bodyNodeLookup[bodyID]==null){this.CreateNode(body,bodyID,Box2D.Dynamics.b2BodyList.TYPES.allBodies);this.UpdateBody(body);body.m_lists.push(this);this.bodyCount++}};Box2D.Dynamics.b2BodyList.prototype.UpdateBody=function(body){var type=body.GetType();var bodyID=body.ID;var awake=body.IsAwake();var active=body.IsActive();if(type==Box2D.Dynamics.b2BodyDef.b2_dynamicBody){this.CreateNode(body,bodyID,Box2D.Dynamics.b2BodyList.TYPES.dynamicBodies)}else{this.RemoveNode(bodyID,Box2D.Dynamics.b2BodyList.TYPES.dynamicBodies)}if(type!=Box2D.Dynamics.b2BodyDef.b2_staticBody){this.CreateNode(body,bodyID,Box2D.Dynamics.b2BodyList.TYPES.nonStaticBodies)}else{this.RemoveNode(bodyID,Box2D.Dynamics.b2BodyList.TYPES.nonStaticBodies)}if(type!=Box2D.Dynamics.b2BodyDef.b2_staticBody&amp;&amp;active&amp;&amp;awake){this.CreateNode(body,bodyID,Box2D.Dynamics.b2BodyList.TYPES.nonStaticActiveAwakeBodies)}else{this.RemoveNode(bodyID,Box2D.Dynamics.b2BodyList.TYPES.nonStaticActiveAwakeBodies)}if(awake){this.CreateNode(body,bodyID,Box2D.Dynamics.b2BodyList.TYPES.awakeBodies)}else{this.RemoveNode(bodyID,Box2D.Dynamics.b2BodyList.TYPES.awakeBodies)}if(active){this.CreateNode(body,bodyID,Box2D.Dynamics.b2BodyList.TYPES.activeBodies)}else{this.RemoveNode(bodyID,Box2D.Dynamics.b2BodyList.TYPES.activeBodies)}};Box2D.Dynamics.b2BodyList.prototype.RemoveBody=function(body){var bodyID=body.ID;if(this.bodyNodeLookup[bodyID]!=null){Box2D.Array.remove(body.m_lists,this);for(var i=0;i&lt;=Box2D.Dynamics.b2BodyList.TYPES.allBodies;i++){this.RemoveNode(bodyID,i)}delete this.bodyNodeLookup[bodyID];this.bodyCount--}};Box2D.Dynamics.b2BodyList.prototype.RemoveNode=function(bodyID,type){var nodeList=this.bodyNodeLookup[bodyID];if(nodeList==null){return}var node=nodeList[type];if(node==null){return}nodeList[type]=null;var prevNode=node.GetPreviousNode();var nextNode=node.GetNextNode();if(prevNode==null){this.bodyFirstNodes[type]=nextNode}else{prevNode.SetNextNode(nextNode)}if(nextNode==null){this.bodyLastNodes[type]=prevNode}else{nextNode.SetPreviousNode(prevNode)}Box2D.Dynamics.b2BodyListNode.Free(node)};Box2D.Dynamics.b2BodyList.prototype.CreateNode=function(body,bodyID,type){var nodeList=this.bodyNodeLookup[bodyID];if(nodeList==null){nodeList=Box2D.Array.Get();for(var i=0;i&lt;=Box2D.Dynamics.b2BodyList.TYPES.allBodies;i++){nodeList[i]=null}this.bodyNodeLookup[bodyID]=nodeList}if(nodeList[type]==null){nodeList[type]=Box2D.Dynamics.b2BodyListNode.Get(body);var prevNode=this.bodyLastNodes[type];if(prevNode!=null){prevNode.SetNextNode(nodeList[type])}else{this.bodyFirstNodes[type]=nodeList[type]}nodeList[type].SetPreviousNode(prevNode);this.bodyLastNodes[type]=nodeList[type]}};Box2D.Dynamics.b2BodyList.prototype.GetBodyCount=function(){return this.bodyCount};Box2D.Dynamics.b2BodyList.TYPES={dynamicBodies:0,nonStaticBodies:1,activeBodies:2,nonStaticActiveAwakeBodies:3,awakeBodies:4,allBodies:5};Box2D.Dynamics.b2BodyListNode=function(body){this.body=body;this.next=null;this.previous=null};Box2D.Dynamics.b2BodyListNode.prototype.SetNextNode=function(node){this.next=node};Box2D.Dynamics.b2BodyListNode.prototype.SetPreviousNode=function(node){this.previous=node};Box2D.Dynamics.b2BodyListNode.prototype.GetBody=function(){return this.body};Box2D.Dynamics.b2BodyListNode.prototype.GetNextNode=function(){return this.next};Box2D.Dynamics.b2BodyListNode.prototype.GetPreviousNode=function(){return this.previous};Box2D.Dynamics.b2BodyListNode._freeCache=[];Box2D.Dynamics.b2BodyListNode.Get=function(body){if(Box2D.Dynamics.b2BodyListNode._freeCache.length&gt;0){var obj=Box2D.Dynamics.b2BodyListNode._freeCache.pop();obj.body=body;obj.next=null;obj.previous=null;return obj}return new Box2D.Dynamics.b2BodyListNode(body)};Box2D.Dynamics.b2BodyListNode.Free=function(obj){if(obj!=null){Box2D.Dynamics.b2BodyListNode._freeCache.push(obj)}};Box2D.Dynamics.b2ContactFilter=function(){};Box2D.Dynamics.b2ContactFilter.prototype.ShouldCollide=function(fixtureA,fixtureB){var filter1=fixtureA.GetFilterData();var filter2=fixtureB.GetFilterData();if(filter1.groupIndex==filter2.groupIndex&amp;&amp;filter1.groupIndex!=0){return filter1.groupIndex&gt;0}return(filter1.maskBits&amp;filter2.categoryBits)!=0&amp;&amp;(filter1.categoryBits&amp;filter2.maskBits)!=0};Box2D.Dynamics.b2ContactFilter.b2_defaultFilter=new Box2D.Dynamics.b2ContactFilter;Box2D.Dynamics.b2ContactImpulse=function(){this.normalImpulses=Box2D.Array.Get();this.tangentImpulses=Box2D.Array.Get()};Box2D.Dynamics.b2ContactImpulse.prototype.Reset=function(){this.normalImpulses.length=0;this.tangentImpulses.length=0};Box2D.Dynamics.b2ContactListener=function(){};Box2D.Dynamics.b2ContactListener.prototype.BeginContact=function(contact){};Box2D.Dynamics.b2ContactListener.prototype.EndContact=function(contact){};Box2D.Dynamics.b2ContactListener.prototype.PreSolve=function(contact,oldManifold){};Box2D.Dynamics.b2ContactListener.prototype.PostSolve=function(contact,impulse){};Box2D.Dynamics.b2ContactListener.b2_defaultListener=new Box2D.Dynamics.b2ContactListener;Box2D.Dynamics.b2DebugDraw=function(){this.m_drawScale=1;this.m_lineThickness=1;this.m_alpha=1;this.m_fillAlpha=1;this.m_xformScale=1;this.m_drawFlags=0;this.m_ctx=null};Box2D.Dynamics.b2DebugDraw.prototype.Clear=function(){this.m_ctx.clearRect(0,0,this.m_ctx.canvas.width,this.m_ctx.canvas.height)};Box2D.Dynamics.b2DebugDraw.prototype._color=function(color,alpha){return"rgba("+((color&amp;16711680)&gt;&gt;16)+","+((color&amp;65280)&gt;&gt;8)+","+(color&amp;255)+","+alpha+")"};Box2D.Dynamics.b2DebugDraw.prototype.SetFlags=function(flags){this.m_drawFlags=flags};Box2D.Dynamics.b2DebugDraw.prototype.GetFlags=function(){return this.m_drawFlags};Box2D.Dynamics.b2DebugDraw.prototype.AppendFlags=function(flags){this.m_drawFlags|=flags};Box2D.Dynamics.b2DebugDraw.prototype.ClearFlags=function(flags){this.m_drawFlags&amp;=~flags};Box2D.Dynamics.b2DebugDraw.prototype.SetSprite=function(sprite){this.m_ctx=sprite};Box2D.Dynamics.b2DebugDraw.prototype.GetSprite=function(){return this.m_ctx};Box2D.Dynamics.b2DebugDraw.prototype.SetDrawScale=function(drawScale){this.m_drawScale=drawScale};Box2D.Dynamics.b2DebugDraw.prototype.GetDrawScale=function(){return this.m_drawScale};Box2D.Dynamics.b2DebugDraw.prototype.SetLineThickness=function(lineThickness){this.m_lineThickness=lineThickness;this.m_ctx.strokeWidth=lineThickness};Box2D.Dynamics.b2DebugDraw.prototype.GetLineThickness=function(){return this.m_lineThickness};Box2D.Dynamics.b2DebugDraw.prototype.SetAlpha=function(alpha){this.m_alpha=alpha};Box2D.Dynamics.b2DebugDraw.prototype.GetAlpha=function(){return this.m_alpha};Box2D.Dynamics.b2DebugDraw.prototype.SetFillAlpha=function(alpha){this.m_fillAlpha=alpha};Box2D.Dynamics.b2DebugDraw.prototype.GetFillAlpha=function(){return this.m_fillAlpha};Box2D.Dynamics.b2DebugDraw.prototype.SetXFormScale=function(scale){this.m_xformScale=scale};Box2D.Dynamics.b2DebugDraw.prototype.GetXFormScale=function(){return this.m_xformScale};(function(b2DebugDraw){b2DebugDraw.prototype.DrawPolygon=function(vertices,vertexCount,color){if(!vertexCount)return;var s=this.m_ctx;var drawScale=this.m_drawScale;s.beginPath();s.strokeStyle=this._color(color.GetColor(),this.m_alpha);s.moveTo(vertices[0].x*drawScale,vertices[0].y*drawScale);for(var i=1;i&lt;vertexCount;i++){s.lineTo(vertices[i].x*drawScale,vertices[i].y*drawScale)}s.lineTo(vertices[0].x*drawScale,vertices[0].y*drawScale);s.closePath();s.stroke()};b2DebugDraw.prototype.DrawSolidPolygon=function(vertices,vertexCount,color){if(!vertexCount)return;var s=this.m_ctx;var drawScale=this.m_drawScale;s.beginPath();s.strokeStyle=this._color(color.GetColor(),this.m_alpha);s.fillStyle=this._color(color.GetColor(),this.m_fillAlpha);s.moveTo(vertices[0].x*drawScale,vertices[0].y*drawScale);for(var i=1;i&lt;vertexCount;i++){s.lineTo(vertices[i].x*drawScale,vertices[i].y*drawScale)}s.lineTo(vertices[0].x*drawScale,vertices[0].y*drawScale);s.closePath();s.fill();s.stroke()};b2DebugDraw.prototype.DrawCircle=function(center,radius,color){if(!radius)return;var s=this.m_ctx;var drawScale=this.m_drawScale;s.beginPath();s.strokeStyle=this._color(color.GetColor(),this.m_alpha);s.arc(center.x*drawScale,center.y*drawScale,radius*drawScale,0,Math.PI*2,true);s.closePath();s.stroke()};b2DebugDraw.prototype.DrawSolidCircle=function(center,radius,axis,color){if(!radius)return;var s=this.m_ctx,drawScale=this.m_drawScale,cx=center.x*drawScale,cy=center.y*drawScale;s.moveTo(0,0);s.beginPath();s.strokeStyle=this._color(color.GetColor(),this.m_alpha);s.fillStyle=this._color(color.GetColor(),this.m_fillAlpha);s.arc(cx,cy,radius*drawScale,0,Math.PI*2,true);s.moveTo(cx,cy);s.lineTo((center.x+axis.x*radius)*drawScale,(center.y+axis.y*radius)*drawScale);s.closePath();s.fill();s.stroke()};b2DebugDraw.prototype.DrawSegment=function(p1,p2,color){var s=this.m_ctx,drawScale=this.m_drawScale;s.strokeStyle=this._color(color.GetColor(),this.m_alpha);s.beginPath();s.moveTo(p1.x*drawScale,p1.y*drawScale);s.lineTo(p2.x*drawScale,p2.y*drawScale);s.closePath();s.stroke()};b2DebugDraw.prototype.DrawTransform=function(xf){var s=this.m_ctx,drawScale=this.m_drawScale;s.beginPath();s.strokeStyle=this._color(16711680,this.m_alpha);s.moveTo(xf.position.x*drawScale,xf.position.y*drawScale);s.lineTo((xf.position.x+this.m_xformScale*xf.R.col1.x)*drawScale,(xf.position.y+this.m_xformScale*xf.R.col1.y)*drawScale);s.strokeStyle=this._color(65280,this.m_alpha);s.moveTo(xf.position.x*drawScale,xf.position.y*drawScale);s.lineTo((xf.position.x+this.m_xformScale*xf.R.col2.x)*drawScale,(xf.position.y+this.m_xformScale*xf.R.col2.y)*drawScale);s.closePath();s.stroke()}})(Box2D.Dynamics.b2DebugDraw);Box2D.Dynamics.b2DebugDraw.e_shapeBit=1;Box2D.Dynamics.b2DebugDraw.e_jointBit=2;Box2D.Dynamics.b2DebugDraw.e_aabbBit=4;Box2D.Dynamics.b2DebugDraw.e_pairBit=8;Box2D.Dynamics.b2DebugDraw.e_centerOfMassBit=16;Box2D.Dynamics.b2DebugDraw.e_controllerBit=32;Box2D.Dynamics.b2DestructionListener=function(){};Box2D.Dynamics.b2DestructionListener.prototype.SayGoodbyeJoint=function(joint){};Box2D.Dynamics.b2DestructionListener.prototype.SayGoodbyeFixture=function(fixture){};Box2D.Dynamics.b2FilterData=function(){this.categoryBits=1;this.maskBits=65535;this.groupIndex=0};Box2D.Dynamics.b2FilterData.prototype.Copy=function(){var copy=Box2D.Dynamics.b2FilterData.Get();copy.categoryBits=this.categoryBits;copy.maskBits=this.maskBits;copy.groupIndex=this.groupIndex;return copy};Box2D.Dynamics.b2FilterData.prototype.Set=function(other){this.categoryBits=other.categoryBits;this.maskBits=other.maskBits;this.groupIndex=other.groupIndex};Box2D.Dynamics.b2FilterData._freeCache=[];Box2D.Dynamics.b2FilterData.Get=function(){if(Box2D.Dynamics.b2FilterData._freeCache.length&gt;0){var o=Box2D.Dynamics.b2FilterData._freeCache.pop();o.categoryBits=1;o.maskBits=65535;o.groupIndex=0;return o}return new Box2D.Dynamics.b2FilterData};Box2D.Dynamics.b2FilterData.Free=function(o){if(o!=null){Box2D.Dynamics.b2FilterData._freeCache.push(o)}};Box2D.Dynamics.b2Fixture=function(body,xf,def){this.ID=Box2D.Dynamics.b2Fixture.NEXT_ID++;this.m_filter=def.filter.Copy();this.m_aabb=Box2D.Collision.b2AABB.Get();this.m_body=body;this.m_shape=def.shape.Copy();this.m_density=def.density;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_isSensor=def.isSensor};Box2D.Dynamics.b2Fixture.s_aabb_temp=Box2D.Collision.b2AABB.Get();Box2D.Dynamics.b2Fixture._freeCache=[];Box2D.Dynamics.b2Fixture.Get=function(body,xf,def){var cache=this._freeCache;var o;if(cache.length&gt;0){o=cache.pop();o.m_filter.Set(def.filter);o.m_body=body;o.m_shape=def.shape.Copy();o.m_density=def.density;o.m_friction=def.friction;o.m_restitution=def.restitution;o.m_isSensor=def.isSensor}else{o=new this(body,xf,def)}return o};Box2D.Dynamics.b2Fixture.Free=function(o){this._freeCache.push(o)};Box2D.Dynamics.b2Fixture.prototype.GetShape=function(){return this.m_shape};Box2D.Dynamics.b2Fixture.prototype.SetSensor=function(sensor){if(this.m_isSensor==sensor){return}this.m_isSensor=sensor;if(this.m_body==null){return}for(var contactNode=this.m_body.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){var fixtureA=contactNode.contact.GetFixtureA();var fixtureB=contactNode.contact.GetFixtureB();if(fixtureA==this||fixtureB==this){contactNode.contact.SetSensor(fixtureA.IsSensor()||fixtureB.IsSensor())}}};Box2D.Dynamics.b2Fixture.prototype.IsSensor=function(){return this.m_isSensor};Box2D.Dynamics.b2Fixture.prototype.SetFilterData=function(filter){this.m_filter=filter.Copy();if(this.m_body==null){return}for(var contactNode=this.m_body.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){if(contactNode.contact.GetFixtureA()==this||contactNode.contact.GetFixtureB()==this){contactNode.contact.FlagForFiltering()}}};Box2D.Dynamics.b2Fixture.prototype.GetFilterData=function(){return this.m_filter};Box2D.Dynamics.b2Fixture.prototype.GetBody=function(){return this.m_body};Box2D.Dynamics.b2Fixture.prototype.TestPoint=function(p){return this.m_shape.TestPoint(this.m_body.GetTransform(),p)};Box2D.Dynamics.b2Fixture.prototype.RayCast=function(output,input){return this.m_shape.RayCast(output,input,this.m_body.GetTransform())};Box2D.Dynamics.b2Fixture.prototype.GetMassData=function(massData){if(!massData){massData=Box2D.Collision.Shapes.b2MassData.Get()}this.m_shape.ComputeMass(massData,this.m_density);return massData};Box2D.Dynamics.b2Fixture.prototype.SetDensity=function(density){this.m_density=density};Box2D.Dynamics.b2Fixture.prototype.GetDensity=function(){return this.m_density};Box2D.Dynamics.b2Fixture.prototype.GetFriction=function(){return this.m_friction};Box2D.Dynamics.b2Fixture.prototype.SetFriction=function(friction){this.m_friction=friction};Box2D.Dynamics.b2Fixture.prototype.GetRestitution=function(){return this.m_restitution};Box2D.Dynamics.b2Fixture.prototype.SetRestitution=function(restitution){this.m_restitution=restitution};Box2D.Dynamics.b2Fixture.prototype.GetAABB=function(){return this.m_aabb};Box2D.Dynamics.b2Fixture.prototype.Destroy=function(){this.m_shape.Destroy();this.m_shape=null;Box2D.Dynamics.b2Fixture.Free(this)};Box2D.Dynamics.b2Fixture.prototype.CreateProxy=function(broadPhase,xf){this.m_shape.ComputeAABB(this.m_aabb,xf);this.m_proxy=broadPhase.CreateProxy(this.m_aabb,this)};Box2D.Dynamics.b2Fixture.prototype.DestroyProxy=function(broadPhase){if(this.m_proxy==null){return}broadPhase.DestroyProxy(this.m_proxy);this.m_proxy=null};Box2D.Dynamics.b2Fixture.prototype.Synchronize=function(broadPhase,transform1,transform2){if(!this.m_proxy)return;var temp=Box2D.Dynamics.b2Fixture.s_aabb_temp;this.m_shape.ComputeAABB(this.m_aabb,transform1);this.m_shape.ComputeAABB(temp,transform2);this.m_aabb.Combine(this.m_aabb,temp);var displacement=Box2D.Common.Math.b2Math.SubtractVV(transform2.position,transform1.position);broadPhase.MoveProxy(this.m_proxy,this.m_aabb,displacement);Box2D.Common.Math.b2Vec2.Free(displacement)};Box2D.Dynamics.b2Fixture.NEXT_ID=0;Box2D.Dynamics.b2FixtureDef=function(){this.filter=Box2D.Dynamics.b2FilterData.Get();this.filter.categoryBits=1;this.filter.maskBits=65535;this.filter.groupIndex=0;this.shape=null;this.friction=.2;this.restitution=0;this.density=0;this.isSensor=false};Box2D.Dynamics.b2FixtureList=function(){this.fixtureFirstNode=null;this.fixtureLastNode=null;this.fixtureNodeLookup={};this.fixtureCount=0};Box2D.Dynamics.b2FixtureList.prototype.GetFirstNode=function(){return this.fixtureFirstNode};Box2D.Dynamics.b2FixtureList.prototype.AddFixture=function(fixture){var fixtureID=fixture.ID;if(this.fixtureNodeLookup[fixtureID]==null){var node=Box2D.Dynamics.b2FixtureListNode.Get(fixture);var prevNode=this.fixtureLastNode;if(prevNode!=null){prevNode.SetNextNode(node)}else{this.fixtureFirstNode=node}node.SetPreviousNode(prevNode);this.fixtureLastNode=node;this.fixtureNodeLookup[fixtureID]=node;this.fixtureCount++}};Box2D.Dynamics.b2FixtureList.prototype.RemoveFixture=function(fixture){var fixtureID=fixture.ID;var node=this.fixtureNodeLookup[fixtureID];if(node==null){return}var prevNode=node.GetPreviousNode();var nextNode=node.GetNextNode();if(prevNode==null){this.fixtureFirstNode=nextNode}else{prevNode.SetNextNode(nextNode)}if(nextNode==null){this.fixtureLastNode=prevNode}else{nextNode.SetPreviousNode(prevNode)}delete this.fixtureNodeLookup[fixtureID];this.fixtureCount--;Box2D.Dynamics.b2FixtureListNode.Free(node)};Box2D.Dynamics.b2FixtureList.prototype.GetFixtureCount=function(){return this.fixtureCount};Box2D.Dynamics.b2FixtureList._freeCache=[];Box2D.Dynamics.b2FixtureList.Get=function(){if(Box2D.Dynamics.b2FixtureList._freeCache.length&gt;0){var o=Box2D.Dynamics.b2FixtureList._freeCache.pop();o.fixtureNodeLookup={};return o}return new Box2D.Dynamics.b2FixtureList};Box2D.Dynamics.b2FixtureList.Free=function(o){if(o!=null){o.fixtureFirstNode=null;o.fixtureLastNode=null;o.fixtureNodeLookup=null;o.fixtureCount=0;Box2D.Dynamics.b2FixtureList._freeCache.push(o)}};Box2D.Dynamics.b2FixtureListNode=function(fixture){this.fixture=fixture;this.next=null;this.previous=null};Box2D.Dynamics.b2FixtureListNode.prototype.SetNextNode=function(node){this.next=node};Box2D.Dynamics.b2FixtureListNode.prototype.SetPreviousNode=function(node){this.previous=node};Box2D.Dynamics.b2FixtureListNode.prototype.GetNextNode=function(){return this.next};Box2D.Dynamics.b2FixtureListNode.prototype.GetPreviousNode=function(){return this.previous};Box2D.Dynamics.b2FixtureListNode._freeCache=[];Box2D.Dynamics.b2FixtureListNode.Get=function(fixture){if(Box2D.Dynamics.b2FixtureListNode._freeCache.length&gt;0){var o=Box2D.Dynamics.b2FixtureListNode._freeCache.pop();o.fixture=fixture;return o}return new Box2D.Dynamics.b2FixtureListNode(fixture)};Box2D.Dynamics.b2FixtureListNode.Free=function(o){if(o!=null){o.fixture=null;o.next=null;o.previous=null;Box2D.Dynamics.b2FixtureListNode._freeCache.push(o)}};Box2D.Dynamics.b2Island=function(listener,contactSolver){this.m_listener=listener;this.m_contactSolver=contactSolver;this.m_bodies=Box2D.Array.Get();this.m_dynamicBodies=Box2D.Array.Get();this.m_nonStaticBodies=Box2D.Array.Get();this.m_contacts=Box2D.Array.Get();this.m_joints=Box2D.Array.Get();this.impulse=new Box2D.Dynamics.b2ContactImpulse};Box2D.Dynamics.b2Island.prototype.Reset=function(listener,contactSolver){this.m_listener=listener;this.m_contactSolver=contactSolver};Box2D.Dynamics.b2Island.prototype.Clear=function(){this.m_bodies.length=0;this.m_dynamicBodies.length=0;this.m_nonStaticBodies.length=0;this.m_contacts.length=0;this.m_joints.length=0};Box2D.Dynamics.b2Island.prototype.Solve=function(step,gravity,allowSleep){this._InitializeVelocities(step,gravity);this.m_contactSolver.Initialize(step,this.m_contacts,this.m_contacts.length);this._SolveVelocityConstraints(step);this._SolveBodies(step);this._SolvePositionConstraints(step);if(allowSleep){this._SleepIfTired(step)}};Box2D.Dynamics.b2Island.prototype._InitializeVelocities=function(step,gravity){for(var i=0,iend=this.m_dynamicBodies.length;i&lt;iend;i++){var b=this.m_dynamicBodies[i];b.m_linearVelocity.x+=step.dt*(gravity.x+b.m_invMass*b.m_force.x);b.m_linearVelocity.y+=step.dt*(gravity.y+b.m_invMass*b.m_force.y);b.m_angularVelocity+=step.dt*b.m_invI*b.m_torque;b.m_linearVelocity.Multiply(Box2D.Common.Math.b2Math.Clamp01(1-step.dt*b.m_linearDamping));b.m_angularVelocity*=Box2D.Common.Math.b2Math.Clamp01(1-step.dt*b.m_angularDamping)}};Box2D.Dynamics.b2Island.prototype._SolveVelocityConstraints=function(step){var i,iend,j,jend;this.m_contactSolver.InitVelocityConstraints(step);for(i=0,iend=this.m_joints.length;i&lt;iend;i++){this.m_joints[i].InitVelocityConstraints(step)}for(i=0;i&lt;step.velocityIterations;i++){for(j=0,jend=this.m_joints.length;j&lt;jend;j++){this.m_joints[j].SolveVelocityConstraints(step)}this.m_contactSolver.SolveVelocityConstraints()}for(i=0,iend=this.m_joints.length;i&lt;iend;i++){this.m_joints[i].FinalizeVelocityConstraints()}this.m_contactSolver.FinalizeVelocityConstraints()};Box2D.Dynamics.b2Island.prototype._SolveBodies=function(step){for(var i=0;i&lt;this.m_nonStaticBodies.length;++i){var b=this.m_nonStaticBodies[i];var translationX=step.dt*b.m_linearVelocity.x;var translationY=step.dt*b.m_linearVelocity.y;if(translationX*translationX+translationY*translationY&gt;Box2D.Common.b2Settings.b2_maxTranslationSquared){b.m_linearVelocity.Normalize();b.m_linearVelocity.x*=Box2D.Common.b2Settings.b2_maxTranslation*step.inv_dt;b.m_linearVelocity.y*=Box2D.Common.b2Settings.b2_maxTranslation*step.inv_dt}var rotation=step.dt*b.m_angularVelocity;if(rotation*rotation&gt;Box2D.Common.b2Settings.b2_maxRotationSquared){if(b.m_angularVelocity&lt;0){b.m_angularVelocity=-Box2D.Common.b2Settings.b2_maxRotation*step.inv_dt}else{b.m_angularVelocity=Box2D.Common.b2Settings.b2_maxRotation*step.inv_dt}}b.m_sweep.c0.SetV(b.m_sweep.c);b.m_sweep.a0=b.m_sweep.a;b.m_sweep.c.x+=step.dt*b.m_linearVelocity.x;b.m_sweep.c.y+=step.dt*b.m_linearVelocity.y;b.m_sweep.a+=step.dt*b.m_angularVelocity;b.SynchronizeTransform()}};Box2D.Dynamics.b2Island.prototype._SolvePositionConstraints=function(step){for(var i=0;i&lt;step.positionIterations;i++){var contactsOkay=this.m_contactSolver.SolvePositionConstraints(Box2D.Common.b2Settings.b2_contactBaumgarte);var jointsOkay=true;for(var j=0;j&lt;this.m_joints.length;j++){var jointOkay=this.m_joints[j].SolvePositionConstraints(Box2D.Common.b2Settings.b2_contactBaumgarte);jointsOkay=jointsOkay&amp;&amp;jointOkay}if(contactsOkay&amp;&amp;jointsOkay){break}}};Box2D.Dynamics.b2Island.prototype._SleepIfTired=function(step){var minSleepTime=Number.MAX_VALUE;for(var nonstaticBodyIdx=0;nonstaticBodyIdx&lt;this.m_nonStaticBodies.length;nonstaticBodyIdx++){var b=this.m_nonStaticBodies[nonstaticBodyIdx];if(!b.m_allowSleep||Math.abs(b.m_angularVelocity)&gt;Box2D.Common.b2Settings.b2_angularSleepTolerance||Box2D.Common.Math.b2Math.Dot(b.m_linearVelocity,b.m_linearVelocity)&gt;Box2D.Common.b2Settings.b2_linearSleepToleranceSquared){b.m_sleepTime=0;minSleepTime=0}else{b.m_sleepTime+=step.dt;minSleepTime=Math.min(minSleepTime,b.m_sleepTime)}}if(minSleepTime&gt;=Box2D.Common.b2Settings.b2_timeToSleep){for(var bodyIdx=0;bodyIdx&lt;this.m_bodies.length;bodyIdx++){this.m_bodies[bodyIdx].SetAwake(false)}}};Box2D.Dynamics.b2Island.prototype.SolveTOI=function(subStep){var i,j;var k_toiBaumgarte=.75;this.m_contactSolver.Initialize(subStep,this.m_contacts,this.m_contacts.length);var contactSolver=this.m_contactSolver;for(i=0;i&lt;this.m_joints.length;++i){this.m_joints[i].InitVelocityConstraints(subStep)}for(i=0;i&lt;subStep.velocityIterations;++i){contactSolver.SolveVelocityConstraints();for(j=0;j&lt;this.m_joints.length;++j){this.m_joints[j].SolveVelocityConstraints(subStep)}}for(i=0;i&lt;this.m_nonStaticBodies.length;++i){var b=this.m_nonStaticBodies[i];var translationX=subStep.dt*b.m_linearVelocity.x;var translationY=subStep.dt*b.m_linearVelocity.y;if(translationX*translationX+translationY*translationY&gt;Box2D.Common.b2Settings.b2_maxTranslationSquared){b.m_linearVelocity.Normalize();b.m_linearVelocity.x*=Box2D.Common.b2Settings.b2_maxTranslation*subStep.inv_dt;b.m_linearVelocity.y*=Box2D.Common.b2Settings.b2_maxTranslation*subStep.inv_dt}var rotation=subStep.dt*b.m_angularVelocity;if(rotation*rotation&gt;Box2D.Common.b2Settings.b2_maxRotationSquared){if(b.m_angularVelocity&lt;0){b.m_angularVelocity=-Box2D.Common.b2Settings.b2_maxRotation*subStep.inv_dt}else{b.m_angularVelocity=Box2D.Common.b2Settings.b2_maxRotation*subStep.inv_dt}}b.m_sweep.c0.SetV(b.m_sweep.c);b.m_sweep.a0=b.m_sweep.a;b.m_sweep.c.x+=subStep.dt*b.m_linearVelocity.x;b.m_sweep.c.y+=subStep.dt*b.m_linearVelocity.y;b.m_sweep.a+=subStep.dt*b.m_angularVelocity;b.SynchronizeTransform()}for(i=0;i&lt;subStep.positionIterations;++i){var contactsOkay=contactSolver.SolvePositionConstraints(k_toiBaumgarte);var jointsOkay=true;for(j=0;j&lt;this.m_joints.length;++j){var jointOkay=this.m_joints[j].SolvePositionConstraints(Box2D.Common.b2Settings.b2_contactBaumgarte);jointsOkay=jointsOkay&amp;&amp;jointOkay}if(contactsOkay&amp;&amp;jointsOkay){break}}};Box2D.Dynamics.b2Island.prototype.Report=function(constraints){if(this.m_listener==null){return}for(var i=0;i&lt;this.m_contacts.length;++i){var c=this.m_contacts[i];var cc=constraints[i];this.impulse.Reset();for(var j=0;j&lt;cc.pointCount;++j){this.impulse.normalImpulses[j]=cc.points[j].normalImpulse;this.impulse.tangentImpulses[j]=cc.points[j].tangentImpulse}this.m_listener.PostSolve(c,this.impulse)}};Box2D.Dynamics.b2Island.prototype.AddBody=function(body){this.m_bodies.push(body);if(body.GetType()!=Box2D.Dynamics.b2BodyDef.b2_staticBody){this.m_nonStaticBodies.push(body);if(body.GetType()==Box2D.Dynamics.b2BodyDef.b2_dynamicBody){this.m_dynamicBodies.push(body)}}};Box2D.Dynamics.b2Island.prototype.AddContact=function(contact){this.m_contacts.push(contact)};Box2D.Dynamics.b2Island.prototype.AddJoint=function(joint){this.m_joints.push(joint)};Box2D.Dynamics.b2TimeStep=function(dt,dtRatio,positionIterations,velocityIterations,warmStarting){this.Reset(dt,dtRatio,positionIterations,velocityIterations,warmStarting)};Box2D.Dynamics.b2TimeStep.prototype.Reset=function(dt,dtRatio,positionIterations,velocityIterations,warmStarting){this.dt=dt;var invDT=0;if(dt&gt;0){invDT=1/dt}this.inv_dt=invDT;this.dtRatio=dtRatio;this.positionIterations=positionIterations;this.velocityIterations=velocityIterations;this.warmStarting=warmStarting};Box2D.Dynamics.Joints.b2JointDef=function(){this.type=Box2D.Dynamics.Joints.b2Joint.e_unknownJoint;this.bodyA=null;this.bodyB=null;this.collideConnected=false};Box2D.Dynamics.Joints.b2Joint=function(def){this.m_edgeA=new Box2D.Dynamics.Joints.b2JointEdge;this.m_edgeB=new Box2D.Dynamics.Joints.b2JointEdge;this.m_localCenterA=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localCenterB=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Common.b2Settings.b2Assert(def.bodyA!=def.bodyB);this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_bodyA=def.bodyA;this.m_bodyB=def.bodyB;this.m_collideConnected=def.collideConnected};Box2D.Dynamics.Joints.b2Joint.prototype.GetType=function(){return this.m_type};Box2D.Dynamics.Joints.b2Joint.prototype.GetAnchorA=function(){return null};Box2D.Dynamics.Joints.b2Joint.prototype.GetAnchorB=function(){return null};Box2D.Dynamics.Joints.b2Joint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return null};Box2D.Dynamics.Joints.b2Joint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return 0};Box2D.Dynamics.Joints.b2Joint.prototype.GetBodyA=function(){return this.m_bodyA};Box2D.Dynamics.Joints.b2Joint.prototype.GetBodyB=function(){return this.m_bodyB};Box2D.Dynamics.Joints.b2Joint.prototype.GetNext=function(){return this.m_next};Box2D.Dynamics.Joints.b2Joint.prototype.IsActive=function(){return this.m_bodyA.IsActive()&amp;&amp;this.m_bodyB.IsActive()};Box2D.Dynamics.Joints.b2Joint.Create=function(def){return def.Create()};Box2D.Dynamics.Joints.b2Joint.prototype.InitVelocityConstraints=function(step){};Box2D.Dynamics.Joints.b2Joint.prototype.SolveVelocityConstraints=function(step){};Box2D.Dynamics.Joints.b2Joint.prototype.FinalizeVelocityConstraints=function(){};Box2D.Dynamics.Joints.b2Joint.prototype.SolvePositionConstraints=function(baumgarte){return false};Box2D.Dynamics.Joints.b2Joint.e_unknownJoint=0;Box2D.Dynamics.Joints.b2Joint.e_revoluteJoint=1;Box2D.Dynamics.Joints.b2Joint.e_prismaticJoint=2;Box2D.Dynamics.Joints.b2Joint.e_distanceJoint=3;Box2D.Dynamics.Joints.b2Joint.e_pulleyJoint=4;Box2D.Dynamics.Joints.b2Joint.e_mouseJoint=5;Box2D.Dynamics.Joints.b2Joint.e_gearJoint=6;Box2D.Dynamics.Joints.b2Joint.e_lineJoint=7;Box2D.Dynamics.Joints.b2Joint.e_weldJoint=8;Box2D.Dynamics.Joints.b2Joint.e_frictionJoint=9;Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit=0;Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit=1;Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit=2;Box2D.Dynamics.Joints.b2Joint.e_equalLimits=3;Box2D.Dynamics.Joints.b2DistanceJoint=function(def){Box2D.Dynamics.Joints.b2Joint.call(this,def);this.m_localAnchor1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_u=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor1.SetV(def.localAnchorA);this.m_localAnchor2.SetV(def.localAnchorB);this.m_length=def.length;this.m_frequencyHz=def.frequencyHz;this.m_dampingRatio=def.dampingRatio;this.m_impulse=0;this.m_gamma=0;this.m_bias=0};Box2D.inherits(Box2D.Dynamics.Joints.b2DistanceJoint,Box2D.Dynamics.Joints.b2Joint);Box2D.Dynamics.Joints.b2DistanceJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.GetReactionForce=function(inv_dt){return Box2D.Common.Math.b2Vec2.Get(inv_dt*this.m_impulse*this.m_u.x,inv_dt*this.m_impulse*this.m_u.y)};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.GetReactionTorque=function(inv_dt){return 0};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.GetLength=function(){return this.m_length};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.SetLength=function(length){this.m_length=length};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.GetFrequency=function(){return this.m_frequencyHz};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.SetFrequency=function(hz){this.m_frequencyHz=hz};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.GetDampingRatio=function(){return this.m_dampingRatio};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.SetDampingRatio=function(ratio){this.m_dampingRatio=ratio};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.InitVelocityConstraints=function(step){var tMat;var tX=0;var bA=this.m_bodyA;var bB=this.m_bodyB;tMat=bA.m_xf.R;var r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;var r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;var r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;var r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;this.m_u.x=bB.m_sweep.c.x+r2X-bA.m_sweep.c.x-r1X;this.m_u.y=bB.m_sweep.c.y+r2Y-bA.m_sweep.c.y-r1Y;var length=Math.sqrt(this.m_u.x*this.m_u.x+this.m_u.y*this.m_u.y);if(length&gt;Box2D.Common.b2Settings.b2_linearSlop){this.m_u.Multiply(1/length)}else{this.m_u.SetZero()}var cr1u=r1X*this.m_u.y-r1Y*this.m_u.x;var cr2u=r2X*this.m_u.y-r2Y*this.m_u.x;var invMass=bA.m_invMass+bA.m_invI*cr1u*cr1u+bB.m_invMass+bB.m_invI*cr2u*cr2u;this.m_mass=invMass!=0?1/invMass:0;if(this.m_frequencyHz&gt;0){var C=length-this.m_length;var omega=2*Math.PI*this.m_frequencyHz;var d=2*this.m_mass*this.m_dampingRatio*omega;var k=this.m_mass*omega*omega;this.m_gamma=step.dt*(d+step.dt*k);this.m_gamma=this.m_gamma!=0?1/this.m_gamma:0;this.m_bias=C*step.dt*k*this.m_gamma;this.m_mass=invMass+this.m_gamma;this.m_mass=this.m_mass!=0?1/this.m_mass:0}if(step.warmStarting){this.m_impulse*=step.dtRatio;var PX=this.m_impulse*this.m_u.x;var PY=this.m_impulse*this.m_u.y;bA.m_linearVelocity.x-=bA.m_invMass*PX;bA.m_linearVelocity.y-=bA.m_invMass*PY;bA.m_angularVelocity-=bA.m_invI*(r1X*PY-r1Y*PX);bB.m_linearVelocity.x+=bB.m_invMass*PX;bB.m_linearVelocity.y+=bB.m_invMass*PY;bB.m_angularVelocity+=bB.m_invI*(r2X*PY-r2Y*PX)}else{this.m_impulse=0}};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.SolveVelocityConstraints=function(step){var r1X=this.m_localAnchor1.x-this.m_bodyA.m_sweep.localCenter.x;var r1Y=this.m_localAnchor1.y-this.m_bodyA.m_sweep.localCenter.y;var tX=this.m_bodyA.m_xf.R.col1.x*r1X+this.m_bodyA.m_xf.R.col2.x*r1Y;r1Y=this.m_bodyA.m_xf.R.col1.y*r1X+this.m_bodyA.m_xf.R.col2.y*r1Y;r1X=tX;var r2X=this.m_localAnchor2.x-this.m_bodyB.m_sweep.localCenter.x;var r2Y=this.m_localAnchor2.y-this.m_bodyB.m_sweep.localCenter.y;tX=this.m_bodyB.m_xf.R.col1.x*r2X+this.m_bodyB.m_xf.R.col2.x*r2Y;r2Y=this.m_bodyB.m_xf.R.col1.y*r2X+this.m_bodyB.m_xf.R.col2.y*r2Y;r2X=tX;var v1X=this.m_bodyA.m_linearVelocity.x-this.m_bodyA.m_angularVelocity*r1Y;var v1Y=this.m_bodyA.m_linearVelocity.y+this.m_bodyA.m_angularVelocity*r1X;var v2X=this.m_bodyB.m_linearVelocity.x-this.m_bodyB.m_angularVelocity*r2Y;var v2Y=this.m_bodyB.m_linearVelocity.y+this.m_bodyB.m_angularVelocity*r2X;var Cdot=this.m_u.x*(v2X-v1X)+this.m_u.y*(v2Y-v1Y);var impulse=-this.m_mass*(Cdot+this.m_bias+this.m_gamma*this.m_impulse);this.m_impulse+=impulse;var PX=impulse*this.m_u.x;var PY=impulse*this.m_u.y;this.m_bodyA.m_linearVelocity.x-=this.m_bodyA.m_invMass*PX;this.m_bodyA.m_linearVelocity.y-=this.m_bodyA.m_invMass*PY;this.m_bodyA.m_angularVelocity-=this.m_bodyA.m_invI*(r1X*PY-r1Y*PX);this.m_bodyB.m_linearVelocity.x+=this.m_bodyB.m_invMass*PX;this.m_bodyB.m_linearVelocity.y+=this.m_bodyB.m_invMass*PY;this.m_bodyB.m_angularVelocity+=this.m_bodyB.m_invI*(r2X*PY-r2Y*PX)};Box2D.Dynamics.Joints.b2DistanceJoint.prototype.SolvePositionConstraints=function(baumgarte){if(this.m_frequencyHz&gt;0){return true}var r1X=this.m_localAnchor1.x-this.m_bodyA.m_sweep.localCenter.x;var r1Y=this.m_localAnchor1.y-this.m_bodyA.m_sweep.localCenter.y;var tX=this.m_bodyA.m_xf.R.col1.x*r1X+this.m_bodyA.m_xf.R.col2.x*r1Y;r1Y=this.m_bodyA.m_xf.R.col1.y*r1X+this.m_bodyA.m_xf.R.col2.y*r1Y;r1X=tX;var r2X=this.m_localAnchor2.x-this.m_bodyB.m_sweep.localCenter.x;var r2Y=this.m_localAnchor2.y-this.m_bodyB.m_sweep.localCenter.y;tX=this.m_bodyB.m_xf.R.col1.x*r2X+this.m_bodyB.m_xf.R.col2.x*r2Y;r2Y=this.m_bodyB.m_xf.R.col1.y*r2X+this.m_bodyB.m_xf.R.col2.y*r2Y;r2X=tX;var dX=this.m_bodyB.m_sweep.c.x+r2X-this.m_bodyA.m_sweep.c.x-r1X;var dY=this.m_bodyB.m_sweep.c.y+r2Y-this.m_bodyA.m_sweep.c.y-r1Y;var length=Math.sqrt(dX*dX+dY*dY);dX/=length;dY/=length;var C=Box2D.Common.Math.b2Math.Clamp(length-this.m_length,-Box2D.Common.b2Settings.b2_maxLinearCorrection,Box2D.Common.b2Settings.b2_maxLinearCorrection);var impulse=-this.m_mass*C;this.m_u.Set(dX,dY);var PX=impulse*this.m_u.x;var PY=impulse*this.m_u.y;this.m_bodyA.m_sweep.c.x-=this.m_bodyA.m_invMass*PX;this.m_bodyA.m_sweep.c.y-=this.m_bodyA.m_invMass*PY;this.m_bodyA.m_sweep.a-=this.m_bodyA.m_invI*(r1X*PY-r1Y*PX);this.m_bodyB.m_sweep.c.x+=this.m_bodyB.m_invMass*PX;this.m_bodyB.m_sweep.c.y+=this.m_bodyB.m_invMass*PY;this.m_bodyB.m_sweep.a+=this.m_bodyB.m_invI*(r2X*PY-r2Y*PX);this.m_bodyA.SynchronizeTransform();this.m_bodyB.SynchronizeTransform();return Math.abs(C)&lt;Box2D.Common.b2Settings.b2_linearSlop};Box2D.Dynamics.Joints.b2DistanceJointDef=function(){Box2D.Dynamics.Joints.b2JointDef.call(this);this.localAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.type=Box2D.Dynamics.Joints.b2Joint.e_distanceJoint;this.length=1;this.frequencyHz=0;this.dampingRatio=0};Box2D.inherits(Box2D.Dynamics.Joints.b2DistanceJointDef,Box2D.Dynamics.Joints.b2JointDef);Box2D.Dynamics.Joints.b2DistanceJointDef.prototype.Initialize=function(bA,bB,anchorA,anchorB){this.bodyA=bA;this.bodyB=bB;this.localAnchorA.SetV(this.bodyA.GetLocalPoint(anchorA));this.localAnchorB.SetV(this.bodyB.GetLocalPoint(anchorB));var dX=anchorB.x-anchorA.x;var dY=anchorB.y-anchorA.y;this.length=Math.sqrt(dX*dX+dY*dY);this.frequencyHz=0;this.dampingRatio=0};Box2D.Dynamics.Joints.b2DistanceJointDef.prototype.Create=function(){return new Box2D.Dynamics.Joints.b2DistanceJoint(this)};Box2D.Dynamics.Joints.b2FrictionJoint=function(def){Box2D.Dynamics.Joints.b2Joint.call(this,def);this.m_localAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_linearMass=Box2D.Common.Math.b2Mat22.Get();this.m_linearImpulse=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchorA.SetV(def.localAnchorA);this.m_localAnchorB.SetV(def.localAnchorB);this.m_linearMass.SetZero();this.m_angularMass=0;this.m_linearImpulse.SetZero();this.m_angularImpulse=0;this.m_maxForce=def.maxForce;this.m_maxTorque=def.maxTorque};Box2D.inherits(Box2D.Dynamics.Joints.b2FrictionJoint,Box2D.Dynamics.Joints.b2Joint);Box2D.Dynamics.Joints.b2FrictionJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA)};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB)};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return new Box2D.Common.Math.b2Vec2.Get(inv_dt*this.m_linearImpulse.x,inv_dt*this.m_linearImpulse.y)};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return inv_dt*this.m_angularImpulse};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.SetMaxForce=function(force){if(force===undefined)force=0;this.m_maxForce=force};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.GetMaxForce=function(){return this.m_maxForce};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.SetMaxTorque=function(torque){if(torque===undefined)torque=0;this.m_maxTorque=torque};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.GetMaxTorque=function(){return this.m_maxTorque};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.InitVelocityConstraints=function(step){var tMat;var tX=0;var bA=this.m_bodyA;var bB=this.m_bodyB;tMat=bA.m_xf.R;var rAX=this.m_localAnchorA.x-bA.m_sweep.localCenter.x;var rAY=this.m_localAnchorA.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*rAX+tMat.col2.x*rAY;rAY=tMat.col1.y*rAX+tMat.col2.y*rAY;rAX=tX;tMat=bB.m_xf.R;var rBX=this.m_localAnchorB.x-bB.m_sweep.localCenter.x;var rBY=this.m_localAnchorB.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*rBX+tMat.col2.x*rBY;rBY=tMat.col1.y*rBX+tMat.col2.y*rBY;rBX=tX;var mA=bA.m_invMass;var mB=bB.m_invMass;var iA=bA.m_invI;var iB=bB.m_invI;var K=new b2Mat22;K.col1.x=mA+mB;K.col2.x=0;K.col1.y=0;K.col2.y=mA+mB;K.col1.x+=iA*rAY*rAY;K.col2.x+=-iA*rAX*rAY;K.col1.y+=-iA*rAX*rAY;K.col2.y+=iA*rAX*rAX;K.col1.x+=iB*rBY*rBY;K.col2.x+=-iB*rBX*rBY;K.col1.y+=-iB*rBX*rBY;K.col2.y+=iB*rBX*rBX;K.GetInverse(this.m_linearMass);this.m_angularMass=iA+iB;if(this.m_angularMass&gt;0){this.m_angularMass=1/this.m_angularMass}if(step.warmStarting){this.m_linearImpulse.x*=step.dtRatio;this.m_linearImpulse.y*=step.dtRatio;this.m_angularImpulse*=step.dtRatio;var P=this.m_linearImpulse;bA.m_linearVelocity.x-=mA*P.x;bA.m_linearVelocity.y-=mA*P.y;bA.m_angularVelocity-=iA*(rAX*P.y-rAY*P.x+this.m_angularImpulse);bB.m_linearVelocity.x+=mB*P.x;bB.m_linearVelocity.y+=mB*P.y;bB.m_angularVelocity+=iB*(rBX*P.y-rBY*P.x+this.m_angularImpulse)}else{this.m_linearImpulse.SetZero();this.m_angularImpulse=0}};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.SolveVelocityConstraints=function(step){var tMat;var tX=0;var bA=this.m_bodyA;var bB=this.m_bodyB;var vA=bA.m_linearVelocity;var wA=bA.m_angularVelocity;var vB=bB.m_linearVelocity;var wB=bB.m_angularVelocity;var mA=bA.m_invMass;var mB=bB.m_invMass;var iA=bA.m_invI;var iB=bB.m_invI;tMat=bA.m_xf.R;var rAX=this.m_localAnchorA.x-bA.m_sweep.localCenter.x;var rAY=this.m_localAnchorA.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*rAX+tMat.col2.x*rAY;rAY=tMat.col1.y*rAX+tMat.col2.y*rAY;rAX=tX;tMat=bB.m_xf.R;var rBX=this.m_localAnchorB.x-bB.m_sweep.localCenter.x;var rBY=this.m_localAnchorB.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*rBX+tMat.col2.x*rBY;rBY=tMat.col1.y*rBX+tMat.col2.y*rBY;rBX=tX;var maxImpulse=0;var Cdot=wB-wA;var impulse=-this.m_angularMass*Cdot;var oldImpulse=this.m_angularImpulse;maxImpulse=step.dt*this.m_maxTorque;this.m_angularImpulse=Box2D.Common.Math.b2Math.Clamp(this.m_angularImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_angularImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse;var CdotX=vB.x-wB*rBY-vA.x+wA*rAY;var CdotY=vB.y+wB*rBX-vA.y-wA*rAX;var impulseV=Box2D.Common.Math.b2Vec2.Get(-CdotX,-CdotY);impulseV.MulM(this.m_linearMass);var oldImpulseV=this.m_linearImpulse.Copy();this.m_linearImpulse.Add(impulseV);Box2D.Common.Math.b2Vec2.Free(impulseV);maxImpulse=step.dt*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()&gt;maxImpulse*maxImpulse){this.m_linearImpulse.Normalize();this.m_linearImpulse.Multiply(maxImpulse)}impulseV=Box2D.Common.Math.b2Math.SubtractVV(this.m_linearImpulse,oldImpulseV);Box2D.Common.Math.b2Vec2.Free(oldImpulseV);vA.x-=mA*impulseV.x;vA.y-=mA*impulseV.y;wA-=iA*(rAX*impulseV.y-rAY*impulseV.x);vB.x+=mB*impulseV.x;vB.y+=mB*impulseV.y;wB+=iB*(rBX*impulseV.y-rBY*impulseV.x);Box2D.Common.Math.b2Vec2.Free(impulseV);bA.m_angularVelocity=wA;bB.m_angularVelocity=wB};Box2D.Dynamics.Joints.b2FrictionJoint.prototype.SolvePositionConstraints=function(baumgarte){return true};Box2D.Dynamics.Joints.b2FrictionJointDef=function(){Box2D.Dynamics.Joints.b2JointDef.call(this);this.localAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.type=Box2D.Dynamics.Joints.b2Joint.e_frictionJoint;this.maxForce=0;this.maxTorque=0};Box2D.inherits(Box2D.Dynamics.Joints.b2FrictionJointDef,Box2D.Dynamics.Joints.b2JointDef);Box2D.Dynamics.Joints.b2FrictionJointDef.prototype.Initialize=function(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.localAnchorA.SetV(this.bodyA.GetLocalPoint(anchor));this.localAnchorB.SetV(this.bodyB.GetLocalPoint(anchor))};Box2D.Dynamics.Joints.b2FrictionJointDef.prototype.Create=function(){return new Box2D.Dynamics.Joints.b2FrictionJoint(this)};Box2D.Dynamics.Joints.b2GearJoint=function(def){Box2D.Dynamics.Joints.b2Joint.call(this,def);this.m_groundAnchor1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_groundAnchor2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_J=new Box2D.Dynamics.Joints.b2Jacobian;var type1=def.joint1.m_type;var type2=def.joint2.m_type;this.m_revolute1=null;this.m_prismatic1=null;this.m_revolute2=null;this.m_prismatic2=null;var coordinate1=0;var coordinate2=0;this.m_ground1=def.joint1.GetBodyA();this.m_bodyA=def.joint1.GetBodyB();if(type1==Box2D.Dynamics.Joints.b2Joint.e_revoluteJoint){this.m_revolute1=def.joint1;this.m_groundAnchor1.SetV(this.m_revolute1.m_localAnchor1);this.m_localAnchor1.SetV(this.m_revolute1.m_localAnchor2);coordinate1=this.m_revolute1.GetJointAngle()}else{this.m_prismatic1=def.joint1;this.m_groundAnchor1.SetV(this.m_prismatic1.m_localAnchor1);this.m_localAnchor1.SetV(this.m_prismatic1.m_localAnchor2);coordinate1=this.m_prismatic1.GetJointTranslation()}this.m_ground2=def.joint2.GetBodyA();this.m_bodyB=def.joint2.GetBodyB();if(type2==Box2D.Dynamics.Joints.b2Joint.e_revoluteJoint){this.m_revolute2=def.joint2;this.m_groundAnchor2.SetV(this.m_revolute2.m_localAnchor1);this.m_localAnchor2.SetV(this.m_revolute2.m_localAnchor2);coordinate2=this.m_revolute2.GetJointAngle()}else{this.m_prismatic2=def.joint2;this.m_groundAnchor2.SetV(this.m_prismatic2.m_localAnchor1);this.m_localAnchor2.SetV(this.m_prismatic2.m_localAnchor2);coordinate2=this.m_prismatic2.GetJointTranslation()}this.m_ratio=def.ratio;this.m_constant=coordinate1+this.m_ratio*coordinate2;this.m_impulse=0};Box2D.inherits(Box2D.Dynamics.Joints.b2GearJoint,Box2D.Dynamics.Joints.b2Joint);Box2D.Dynamics.Joints.b2GearJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};Box2D.Dynamics.Joints.b2GearJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};Box2D.Dynamics.Joints.b2GearJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return Box2D.Common.Math.b2Vec2.Get(inv_dt*this.m_impulse*this.m_J.linearB.x,inv_dt*this.m_impulse*this.m_J.linearB.y)};Box2D.Dynamics.Joints.b2GearJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;var tMat=this.m_bodyB.m_xf.R;var rX=this.m_localAnchor1.x-this.m_bodyB.m_sweep.localCenter.x;var rY=this.m_localAnchor1.y-this.m_bodyB.m_sweep.localCenter.y;var tX=tMat.col1.x*rX+tMat.col2.x*rY;rY=tMat.col1.y*rX+tMat.col2.y*rY;rX=tX;var PX=this.m_impulse*this.m_J.linearB.x;var PY=this.m_impulse*this.m_J.linearB.y;return inv_dt*(this.m_impulse*this.m_J.angularB-rX*PY+rY*PX)};Box2D.Dynamics.Joints.b2GearJoint.prototype.GetRatio=function(){return this.m_ratio};Box2D.Dynamics.Joints.b2GearJoint.prototype.SetRatio=function(ratio){if(ratio===undefined)ratio=0;this.m_ratio=ratio};Box2D.Dynamics.Joints.b2GearJoint.prototype.InitVelocityConstraints=function(step){var g1=this.m_ground1;var g2=this.m_ground2;var bA=this.m_bodyA;var bB=this.m_bodyB;var ugX=0;var ugY=0;var rX=0;var rY=0;var tMat;var tVec;var crug=0;var tX=0;var K=0;this.m_J.SetZero();if(this.m_revolute1){this.m_J.angularA=-1;K+=bA.m_invI}else{tMat=g1.m_xf.R;tVec=this.m_prismatic1.m_localXAxis1;ugX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;ugY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=bA.m_xf.R;rX=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;rY=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*rX+tMat.col2.x*rY;rY=tMat.col1.y*rX+tMat.col2.y*rY;rX=tX;crug=rX*ugY-rY*ugX;this.m_J.linearA.Set(-ugX,-ugY);this.m_J.angularA=-crug;K+=bA.m_invMass+bA.m_invI*crug*crug}if(this.m_revolute2){this.m_J.angularB=-this.m_ratio;K+=this.m_ratio*this.m_ratio*bB.m_invI}else{tMat=g2.m_xf.R;tVec=this.m_prismatic2.m_localXAxis1;ugX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;ugY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=bB.m_xf.R;rX=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;rY=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*rX+tMat.col2.x*rY;rY=tMat.col1.y*rX+tMat.col2.y*rY;rX=tX;crug=rX*ugY-rY*ugX;this.m_J.linearB.Set(-this.m_ratio*ugX,-this.m_ratio*ugY);this.m_J.angularB=-this.m_ratio*crug;K+=this.m_ratio*this.m_ratio*(bB.m_invMass+bB.m_invI*crug*crug)}this.m_mass=K&gt;0?1/K:0;if(step.warmStarting){bA.m_linearVelocity.x+=bA.m_invMass*this.m_impulse*this.m_J.linearA.x;bA.m_linearVelocity.y+=bA.m_invMass*this.m_impulse*this.m_J.linearA.y;bA.m_angularVelocity+=bA.m_invI*this.m_impulse*this.m_J.angularA;bB.m_linearVelocity.x+=bB.m_invMass*this.m_impulse*this.m_J.linearB.x;bB.m_linearVelocity.y+=bB.m_invMass*this.m_impulse*this.m_J.linearB.y;bB.m_angularVelocity+=bB.m_invI*this.m_impulse*this.m_J.angularB}else{this.m_impulse=0}};Box2D.Dynamics.Joints.b2GearJoint.prototype.SolveVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var Cdot=this.m_J.Compute(bA.m_linearVelocity,bA.m_angularVelocity,bB.m_linearVelocity,bB.m_angularVelocity);var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;bA.m_linearVelocity.x+=bA.m_invMass*impulse*this.m_J.linearA.x;bA.m_linearVelocity.y+=bA.m_invMass*impulse*this.m_J.linearA.y;bA.m_angularVelocity+=bA.m_invI*impulse*this.m_J.angularA;bB.m_linearVelocity.x+=bB.m_invMass*impulse*this.m_J.linearB.x;bB.m_linearVelocity.y+=bB.m_invMass*impulse*this.m_J.linearB.y;bB.m_angularVelocity+=bB.m_invI*impulse*this.m_J.angularB};Box2D.Dynamics.Joints.b2GearJoint.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;var linearError=0;var bA=this.m_bodyA;var bB=this.m_bodyB;var coordinate1=0;var coordinate2=0;if(this.m_revolute1){coordinate1=this.m_revolute1.GetJointAngle()}else{coordinate1=this.m_prismatic1.GetJointTranslation()}if(this.m_revolute2){coordinate2=this.m_revolute2.GetJointAngle()}else{coordinate2=this.m_prismatic2.GetJointTranslation()}var C=this.m_constant-(coordinate1+this.m_ratio*coordinate2);var impulse=-this.m_mass*C;bA.m_sweep.c.x+=bA.m_invMass*impulse*this.m_J.linearA.x;bA.m_sweep.c.y+=bA.m_invMass*impulse*this.m_J.linearA.y;bA.m_sweep.a+=bA.m_invI*impulse*this.m_J.angularA;bB.m_sweep.c.x+=bB.m_invMass*impulse*this.m_J.linearB.x;bB.m_sweep.c.y+=bB.m_invMass*impulse*this.m_J.linearB.y;bB.m_sweep.a+=bB.m_invI*impulse*this.m_J.angularB;bA.SynchronizeTransform();bB.SynchronizeTransform();return linearError&lt;Box2D.Common.b2Settings.b2_linearSlop};Box2D.Dynamics.Joints.b2GearJointDef=function(){Box2D.Dynamics.Joints.b2JointDef.call(this);this.type=Box2D.Dynamics.Joints.b2Joint.e_gearJoint;this.joint1=null;this.joint2=null;this.ratio=1};Box2D.inherits(Box2D.Dynamics.Joints.b2GearJointDef,Box2D.Dynamics.Joints.b2JointDef);Box2D.Dynamics.Joints.b2GearJointDef.prototype.Initialize=function(joint1,joint2,ratio){this.joint1=joint1;this.bodyA=joint1.GetBodyA();this.joint2=joint2;this.bodyB=joint2.GetBodyA();this.ratio=ratio};Box2D.Dynamics.Joints.b2GearJointDef.prototype.Create=function(){return new Box2D.Dynamics.Joints.b2GearJoint(this)};Box2D.Dynamics.Joints.b2Jacobian=function(){this.linearA=Box2D.Common.Math.b2Vec2.Get(0,0);this.linearB=Box2D.Common.Math.b2Vec2.Get(0,0)};Box2D.Dynamics.Joints.b2Jacobian.prototype.SetZero=function(){this.linearA.SetZero();this.angularA=0;this.linearB.SetZero();this.angularB=0};Box2D.Dynamics.Joints.b2Jacobian.prototype.Set=function(x1,a1,x2,a2){if(a1===undefined)a1=0;if(a2===undefined)a2=0;this.linearA.SetV(x1);this.angularA=a1;this.linearB.SetV(x2);this.angularB=a2};Box2D.Dynamics.Joints.b2Jacobian.prototype.Compute=function(x1,a1,x2,a2){if(a1===undefined)a1=0;if(a2===undefined)a2=0;return this.linearA.x*x1.x+this.linearA.y*x1.y+this.angularA*a1+(this.linearB.x*x2.x+this.linearB.y*x2.y)+this.angularB*a2};Box2D.Dynamics.Joints.b2JointEdge=function(){};Box2D.Dynamics.Joints.b2LineJoint=function(def){Box2D.Dynamics.Joints.b2Joint.call(this,def);this.m_localAnchor1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localXAxis1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localYAxis1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_axis=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_perp=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_K=Box2D.Common.Math.b2Mat22.Get();this.m_impulse=Box2D.Common.Math.b2Vec2.Get(0,0);var tMat;var tX=0;var tY=0;this.m_localAnchor1.SetV(def.localAnchorA);this.m_localAnchor2.SetV(def.localAnchorB);this.m_localXAxis1.SetV(def.localAxisA);this.m_localYAxis1.x=-this.m_localXAxis1.y;this.m_localYAxis1.y=this.m_localXAxis1.x;this.m_impulse.SetZero();this.m_motorMass=0;this.m_motorImpulse=0;this.m_lowerTranslation=def.lowerTranslation;this.m_upperTranslation=def.upperTranslation;this.m_maxMotorForce=def.maxMotorForce;this.m_motorSpeed=def.motorSpeed;this.m_enableLimit=def.enableLimit;this.m_enableMotor=def.enableMotor;this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;this.m_axis.SetZero();this.m_perp.SetZero()};Box2D.inherits(Box2D.Dynamics.Joints.b2LineJoint,Box2D.Dynamics.Joints.b2Joint);Box2D.Dynamics.Joints.b2LineJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return Box2D.Common.Math.b2Vec2.Get(inv_dt*(this.m_impulse.x*this.m_perp.x+(this.m_motorImpulse+this.m_impulse.y)*this.m_axis.x),inv_dt*(this.m_impulse.x*this.m_perp.y+(this.m_motorImpulse+this.m_impulse.y)*this.m_axis.y))};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return inv_dt*this.m_impulse.y};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetJointTranslation=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;var p1=bA.GetWorldPoint(this.m_localAnchor1);var p2=bB.GetWorldPoint(this.m_localAnchor2);var dX=p2.x-p1.x;var dY=p2.y-p1.y;var axis=bA.GetWorldVector(this.m_localXAxis1);var translation=axis.x*dX+axis.y*dY;return translation};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetJointSpeed=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;tMat=bA.m_xf.R;var r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;var r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;var tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;var r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;var r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var p1X=bA.m_sweep.c.x+r1X;var p1Y=bA.m_sweep.c.y+r1Y;var p2X=bB.m_sweep.c.x+r2X;var p2Y=bB.m_sweep.c.y+r2Y;var dX=p2X-p1X;var dY=p2Y-p1Y;var axis=bA.GetWorldVector(this.m_localXAxis1);var v1=bA.m_linearVelocity;var v2=bB.m_linearVelocity;var w1=bA.m_angularVelocity;var w2=bB.m_angularVelocity;var speed=dX*(-w1*axis.y)+dY*(w1*axis.x)+(axis.x*(v2.x+-w2*r2Y-v1.x- -w1*r1Y)+axis.y*(v2.y+w2*r2X-v1.y-w1*r1X));return speed};Box2D.Dynamics.Joints.b2LineJoint.prototype.IsLimitEnabled=function(){return this.m_enableLimit};Box2D.Dynamics.Joints.b2LineJoint.prototype.EnableLimit=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetLowerLimit=function(){return this.m_lowerTranslation};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetUpperLimit=function(){return this.m_upperTranslation};Box2D.Dynamics.Joints.b2LineJoint.prototype.SetLimits=function(lower,upper){if(lower===undefined)lower=0;if(upper===undefined)upper=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_lowerTranslation=lower;this.m_upperTranslation=upper};Box2D.Dynamics.Joints.b2LineJoint.prototype.IsMotorEnabled=function(){return this.m_enableMotor};Box2D.Dynamics.Joints.b2LineJoint.prototype.EnableMotor=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag};Box2D.Dynamics.Joints.b2LineJoint.prototype.SetMotorSpeed=function(speed){if(speed===undefined)speed=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetMotorSpeed=function(){return this.m_motorSpeed};Box2D.Dynamics.Joints.b2LineJoint.prototype.SetMaxMotorForce=function(force){if(force===undefined)force=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorForce=force};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetMaxMotorForce=function(){return this.m_maxMotorForce};Box2D.Dynamics.Joints.b2LineJoint.prototype.GetMotorForce=function(){return this.m_motorImpulse};Box2D.Dynamics.Joints.b2LineJoint.prototype.InitVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;var tX=0;this.m_localCenterA.SetV(bA.GetLocalCenter());this.m_localCenterB.SetV(bB.GetLocalCenter());var xf1=bA.GetTransform();var xf2=bB.GetTransform();tMat=bA.m_xf.R;var r1X=this.m_localAnchor1.x-this.m_localCenterA.x;var r1Y=this.m_localAnchor1.y-this.m_localCenterA.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;var r2X=this.m_localAnchor2.x-this.m_localCenterB.x;var r2Y=this.m_localAnchor2.y-this.m_localCenterB.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var dX=bB.m_sweep.c.x+r2X-bA.m_sweep.c.x-r1X;var dY=bB.m_sweep.c.y+r2Y-bA.m_sweep.c.y-r1Y;this.m_invMassA=bA.m_invMass;this.m_invMassB=bB.m_invMass;this.m_invIA=bA.m_invI;this.m_invIB=bB.m_invI;this.m_axis.SetV(Box2D.Common.Math.b2Math.MulMV(xf1.R,this.m_localXAxis1));this.m_a1=(dX+r1X)*this.m_axis.y-(dY+r1Y)*this.m_axis.x;this.m_a2=r2X*this.m_axis.y-r2Y*this.m_axis.x;this.m_motorMass=this.m_invMassA+this.m_invMassB+this.m_invIA*this.m_a1*this.m_a1+this.m_invIB*this.m_a2*this.m_a2;this.m_motorMass=this.m_motorMass&gt;Number.MIN_VALUE?1/this.m_motorMass:0;this.m_perp.SetV(Box2D.Common.Math.b2Math.MulMV(xf1.R,this.m_localYAxis1));this.m_s1=(dX+r1X)*this.m_perp.y-(dY+r1Y)*this.m_perp.x;this.m_s2=r2X*this.m_perp.y-r2Y*this.m_perp.x;var m1=this.m_invMassA;var m2=this.m_invMassB;var i1=this.m_invIA;var i2=this.m_invIB;this.m_K.col1.x=m1+m2+i1*this.m_s1*this.m_s1+i2*this.m_s2*this.m_s2;this.m_K.col1.y=i1*this.m_s1*this.m_a1+i2*this.m_s2*this.m_a2;this.m_K.col2.x=this.m_K.col1.y;this.m_K.col2.y=m1+m2+i1*this.m_a1*this.m_a1+i2*this.m_a2*this.m_a2;if(this.m_enableLimit){var jointTransition=this.m_axis.x*dX+this.m_axis.y*dY;if(Math.abs(this.m_upperTranslation-this.m_lowerTranslation)&lt;2*Box2D.Common.b2Settings.b2_linearSlop){this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_equalLimits}else if(jointTransition&lt;=this.m_lowerTranslation){if(this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit){this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit;this.m_impulse.y=0}}else if(jointTransition&gt;=this.m_upperTranslation){if(this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit;this.m_impulse.y=0}}else{this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;this.m_impulse.y=0}}else{this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit}if(this.m_enableMotor==false){this.m_motorImpulse=0}if(step.warmStarting){this.m_impulse.x*=step.dtRatio;this.m_impulse.y*=step.dtRatio;this.m_motorImpulse*=step.dtRatio;var PX=this.m_impulse.x*this.m_perp.x+(this.m_motorImpulse+this.m_impulse.y)*this.m_axis.x;var PY=this.m_impulse.x*this.m_perp.y+(this.m_motorImpulse+this.m_impulse.y)*this.m_axis.y;var L1=this.m_impulse.x*this.m_s1+(this.m_motorImpulse+this.m_impulse.y)*this.m_a1;var L2=this.m_impulse.x*this.m_s2+(this.m_motorImpulse+this.m_impulse.y)*this.m_a2;bA.m_linearVelocity.x-=this.m_invMassA*PX;bA.m_linearVelocity.y-=this.m_invMassA*PY;bA.m_angularVelocity-=this.m_invIA*L1;bB.m_linearVelocity.x+=this.m_invMassB*PX;bB.m_linearVelocity.y+=this.m_invMassB*PY;bB.m_angularVelocity+=this.m_invIB*L2}else{this.m_impulse.SetZero();this.m_motorImpulse=0}};Box2D.Dynamics.Joints.b2LineJoint.prototype.SolveVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var v1=bA.m_linearVelocity;var w1=bA.m_angularVelocity;var v2=bB.m_linearVelocity;var w2=bB.m_angularVelocity;var PX=0;var PY=0;var L1=0;var L2=0;if(this.m_enableMotor&amp;&amp;this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_equalLimits){var Cdot=this.m_axis.x*(v2.x-v1.x)+this.m_axis.y*(v2.y-v1.y)+this.m_a2*w2-this.m_a1*w1;var impulse=this.m_motorMass*(this.m_motorSpeed-Cdot);var oldImpulse=this.m_motorImpulse;var maxImpulse=step.dt*this.m_maxMotorForce;this.m_motorImpulse=Box2D.Common.Math.b2Math.Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;PX=impulse*this.m_axis.x;PY=impulse*this.m_axis.y;L1=impulse*this.m_a1;L2=impulse*this.m_a2;v1.x-=this.m_invMassA*PX;v1.y-=this.m_invMassA*PY;w1-=this.m_invIA*L1;v2.x+=this.m_invMassB*PX;v2.y+=this.m_invMassB*PY;w2+=this.m_invIB*L2}var Cdot1=this.m_perp.x*(v2.x-v1.x)+this.m_perp.y*(v2.y-v1.y)+this.m_s2*w2-this.m_s1*w1;if(this.m_enableLimit&amp;&amp;this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit){var Cdot2=this.m_axis.x*(v2.x-v1.x)+this.m_axis.y*(v2.y-v1.y)+this.m_a2*w2-this.m_a1*w1;var f1=this.m_impulse.Copy();var tempOriginVec=Box2D.Common.Math.b2Vec2.Get(0,0);var df=this.m_K.Solve(tempOriginVec,-Cdot1,-Cdot2);Box2D.Common.Math.b2Vec2.Free(tempOriginVec);this.m_impulse.Add(df);if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit){this.m_impulse.y=Math.max(this.m_impulse.y,0)}else if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){this.m_impulse.y=Math.min(this.m_impulse.y,0)}var b=-Cdot1-(this.m_impulse.y-f1.y)*this.m_K.col2.x;var f2r=0;if(this.m_K.col1.x!=0){f2r=b/this.m_K.col1.x+f1.x}else{f2r=f1.x}this.m_impulse.x=f2r;df.x=this.m_impulse.x-f1.x;df.y=this.m_impulse.y-f1.y;Box2D.Common.Math.b2Vec2.Free(f1);PX=df.x*this.m_perp.x+df.y*this.m_axis.x;PY=df.x*this.m_perp.y+df.y*this.m_axis.y;L1=df.x*this.m_s1+df.y*this.m_a1;L2=df.x*this.m_s2+df.y*this.m_a2;v1.x-=this.m_invMassA*PX;v1.y-=this.m_invMassA*PY;w1-=this.m_invIA*L1;v2.x+=this.m_invMassB*PX;v2.y+=this.m_invMassB*PY;w2+=this.m_invIB*L2}else{var df2=0;if(this.m_K.col1.x!=0){df2=-Cdot1/this.m_K.col1.x}else{df2=0}this.m_impulse.x+=df2;PX=df2*this.m_perp.x;PY=df2*this.m_perp.y;L1=df2*this.m_s1;L2=df2*this.m_s2;v1.x-=this.m_invMassA*PX;v1.y-=this.m_invMassA*PY;w1-=this.m_invIA*L1;v2.x+=this.m_invMassB*PX;v2.y+=this.m_invMassB*PY;w2+=this.m_invIB*L2}bA.m_linearVelocity.SetV(v1);bA.m_angularVelocity=w1;bB.m_linearVelocity.SetV(v2);bB.m_angularVelocity=w2};Box2D.Dynamics.Joints.b2LineJoint.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;var limitC=0;var oldLimitImpulse=0;var bA=this.m_bodyA;var bB=this.m_bodyB;var c1=bA.m_sweep.c;var a1=bA.m_sweep.a;var c2=bB.m_sweep.c;var a2=bB.m_sweep.a;var tMat;var tX=0;var m1=0;var m2=0;var i1=0;var i2=0;var linearError=0;var angularError=0;var active=false;var C2=0;var R1=Box2D.Common.Math.b2Mat22.FromAngle(a1);var R2=Box2D.Common.Math.b2Mat22.FromAngle(a2);tMat=R1;var r1X=this.m_localAnchor1.x-this.m_localCenterA.x;var r1Y=this.m_localAnchor1.y-this.m_localCenterA.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=R2;var r2X=this.m_localAnchor2.x-this.m_localCenterB.x;var r2Y=this.m_localAnchor2.y-this.m_localCenterB.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var dX=c2.x+r2X-c1.x-r1X;var dY=c2.y+r2Y-c1.y-r1Y;if(this.m_enableLimit){this.m_axis=Box2D.Common.Math.b2Math.MulMV(R1,this.m_localXAxis1);this.m_a1=(dX+r1X)*this.m_axis.y-(dY+r1Y)*this.m_axis.x;this.m_a2=r2X*this.m_axis.y-r2Y*this.m_axis.x;var translation=this.m_axis.x*dX+this.m_axis.y*dY;if(Math.abs(this.m_upperTranslation-this.m_lowerTranslation)&lt;2*Box2D.Common.b2Settings.b2_linearSlop){C2=Box2D.Common.Math.b2Math.Clamp(translation,-Box2D.Common.b2Settings.b2_maxLinearCorrection,Box2D.Common.b2Settings.b2_maxLinearCorrection);linearError=Math.abs(translation);active=true}else if(translation&lt;=this.m_lowerTranslation){C2=Box2D.Common.Math.b2Math.Clamp(translation-this.m_lowerTranslation+Box2D.Common.b2Settings.b2_linearSlop,-Box2D.Common.b2Settings.b2_maxLinearCorrection,0);linearError=this.m_lowerTranslation-translation;active=true}else if(translation&gt;=this.m_upperTranslation){C2=Box2D.Common.Math.b2Math.Clamp(translation-this.m_upperTranslation+Box2D.Common.b2Settings.b2_linearSlop,0,Box2D.Common.b2Settings.b2_maxLinearCorrection);linearError=translation-this.m_upperTranslation;active=true}}this.m_perp=Box2D.Common.Math.b2Math.MulMV(R1,this.m_localYAxis1);this.m_s1=(dX+r1X)*this.m_perp.y-(dY+r1Y)*this.m_perp.x;this.m_s2=r2X*this.m_perp.y-r2Y*this.m_perp.x;var impulse=Box2D.Common.Math.b2Vec2.Get(0,0);var C1=this.m_perp.x*dX+this.m_perp.y*dY;linearError=Math.max(linearError,Math.abs(C1));angularError=0;if(active){m1=this.m_invMassA;m2=this.m_invMassB;i1=this.m_invIA;i2=this.m_invIB;this.m_K.col1.x=m1+m2+i1*this.m_s1*this.m_s1+i2*this.m_s2*this.m_s2;this.m_K.col1.y=i1*this.m_s1*this.m_a1+i2*this.m_s2*this.m_a2;this.m_K.col2.x=this.m_K.col1.y;this.m_K.col2.y=m1+m2+i1*this.m_a1*this.m_a1+i2*this.m_a2*this.m_a2;this.m_K.Solve(impulse,-C1,-C2)}else{m1=this.m_invMassA;m2=this.m_invMassB;i1=this.m_invIA;i2=this.m_invIB;var k11=m1+m2+i1*this.m_s1*this.m_s1+i2*this.m_s2*this.m_s2;var impulse1=0;if(k11!=0){impulse1=-C1/k11}else{impulse1=0}impulse.x=impulse1;impulse.y=0}var PX=impulse.x*this.m_perp.x+impulse.y*this.m_axis.x;var PY=impulse.x*this.m_perp.y+impulse.y*this.m_axis.y;var L1=impulse.x*this.m_s1+impulse.y*this.m_a1;var L2=impulse.x*this.m_s2+impulse.y*this.m_a2;c1.x-=this.m_invMassA*PX;c1.y-=this.m_invMassA*PY;a1-=this.m_invIA*L1;c2.x+=this.m_invMassB*PX;c2.y+=this.m_invMassB*PY;a2+=this.m_invIB*L2;bA.m_sweep.a=a1;bB.m_sweep.a=a2;bA.SynchronizeTransform();bB.SynchronizeTransform();return linearError&lt;=Box2D.Common.b2Settings.b2_linearSlop&amp;&amp;angularError&lt;=Box2D.Common.b2Settings.b2_angularSlop};Box2D.Dynamics.Joints.b2LineJointDef=function(){Box2D.Dynamics.Joints.b2JointDef.call(this);this.localAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAxisA=Box2D.Common.Math.b2Vec2.Get(0,0);this.type=Box2D.Dynamics.Joints.b2Joint.e_lineJoint;this.localAxisA.Set(1,0);this.enableLimit=false;this.lowerTranslation=0;this.upperTranslation=0;this.enableMotor=false;this.maxMotorForce=0;this.motorSpeed=0};Box2D.inherits(Box2D.Dynamics.Joints.b2LineJointDef,Box2D.Dynamics.Joints.b2JointDef);Box2D.Dynamics.Joints.b2LineJointDef.prototype.Initialize=function(bA,bB,anchor,axis){this.bodyA=bA;this.bodyB=bB;this.localAnchorA=this.bodyA.GetLocalPoint(anchor);this.localAnchorB=this.bodyB.GetLocalPoint(anchor);this.localAxisA=this.bodyA.GetLocalVector(axis)};Box2D.Dynamics.Joints.b2LineJointDef.prototype.Create=function(){return new Box2D.Dynamics.Joints.b2LineJoint(this)};Box2D.Dynamics.Joints.b2MouseJoint=function(def){Box2D.Dynamics.Joints.b2Joint.call(this,def);this.K=Box2D.Common.Math.b2Mat22.Get();this.K1=Box2D.Common.Math.b2Mat22.Get();this.K2=Box2D.Common.Math.b2Mat22.Get();this.m_localAnchor=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_target=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_impulse=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_mass=Box2D.Common.Math.b2Mat22.Get();this.m_C=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_target.SetV(def.target);var tX=this.m_target.x-this.m_bodyB.m_xf.position.x;var tY=this.m_target.y-this.m_bodyB.m_xf.position.y;var tMat=this.m_bodyB.m_xf.R;this.m_localAnchor.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor.y=tX*tMat.col2.x+tY*tMat.col2.y;this.m_maxForce=def.maxForce;this.m_impulse.SetZero();this.m_frequencyHz=def.frequencyHz;this.m_dampingRatio=def.dampingRatio;this.m_beta=0;this.m_gamma=0};Box2D.inherits(Box2D.Dynamics.Joints.b2MouseJoint,Box2D.Dynamics.Joints.b2Joint);Box2D.Dynamics.Joints.b2MouseJoint.prototype.GetAnchorA=function(){return Box2D.Common.Math.b2Vec2.Get(this.m_target.x,this.m_target.y)};Box2D.Dynamics.Joints.b2MouseJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor)};Box2D.Dynamics.Joints.b2MouseJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return Box2D.Common.Math.b2Vec2.Get(inv_dt*this.m_impulse.x,inv_dt*this.m_impulse.y)};Box2D.Dynamics.Joints.b2MouseJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return 0};Box2D.Dynamics.Joints.b2MouseJoint.prototype.GetTarget=function(){return this.m_target};Box2D.Dynamics.Joints.b2MouseJoint.prototype.SetTarget=function(target){if(this.m_bodyB.IsAwake()==false){this.m_bodyB.SetAwake(true)}this.m_target=target};Box2D.Dynamics.Joints.b2MouseJoint.prototype.GetMaxForce=function(){return this.m_maxForce};Box2D.Dynamics.Joints.b2MouseJoint.prototype.SetMaxForce=function(maxForce){if(maxForce===undefined)maxForce=0;this.m_maxForce=maxForce};Box2D.Dynamics.Joints.b2MouseJoint.prototype.GetFrequency=function(){return this.m_frequencyHz};Box2D.Dynamics.Joints.b2MouseJoint.prototype.SetFrequency=function(hz){if(hz===undefined)hz=0;this.m_frequencyHz=hz};Box2D.Dynamics.Joints.b2MouseJoint.prototype.GetDampingRatio=function(){return this.m_dampingRatio};Box2D.Dynamics.Joints.b2MouseJoint.prototype.SetDampingRatio=function(ratio){if(ratio===undefined)ratio=0;this.m_dampingRatio=ratio};Box2D.Dynamics.Joints.b2MouseJoint.prototype.InitVelocityConstraints=function(step){var b=this.m_bodyB;var mass=b.GetMass();var omega=2*Math.PI*this.m_frequencyHz;var d=2*mass*this.m_dampingRatio*omega;var k=mass*omega*omega;this.m_gamma=step.dt*(d+step.dt*k);this.m_gamma=this.m_gamma!=0?1/this.m_gamma:0;this.m_beta=step.dt*k*this.m_gamma;var tMat;tMat=b.m_xf.R;var rX=this.m_localAnchor.x-b.m_sweep.localCenter.x;var rY=this.m_localAnchor.y-b.m_sweep.localCenter.y;var tX=tMat.col1.x*rX+tMat.col2.x*rY;rY=tMat.col1.y*rX+tMat.col2.y*rY;rX=tX;var invMass=b.m_invMass;var invI=b.m_invI;this.K1.col1.x=invMass;this.K1.col2.x=0;this.K1.col1.y=0;this.K1.col2.y=invMass;this.K2.col1.x=invI*rY*rY;this.K2.col2.x=-invI*rX*rY;this.K2.col1.y=-invI*rX*rY;this.K2.col2.y=invI*rX*rX;this.K.SetM(this.K1);this.K.AddM(this.K2);this.K.col1.x+=this.m_gamma;this.K.col2.y+=this.m_gamma;this.K.GetInverse(this.m_mass);this.m_C.x=b.m_sweep.c.x+rX-this.m_target.x;this.m_C.y=b.m_sweep.c.y+rY-this.m_target.y;b.m_angularVelocity*=.98;this.m_impulse.x*=step.dtRatio;this.m_impulse.y*=step.dtRatio;b.m_linearVelocity.x+=invMass*this.m_impulse.x;b.m_linearVelocity.y+=invMass*this.m_impulse.y;b.m_angularVelocity+=invI*(rX*this.m_impulse.y-rY*this.m_impulse.x)};Box2D.Dynamics.Joints.b2MouseJoint.prototype.SolveVelocityConstraints=function(step){var b=this.m_bodyB;var tMat;var tX=0;var tY=0;tMat=b.m_xf.R;var rX=this.m_localAnchor.x-b.m_sweep.localCenter.x;var rY=this.m_localAnchor.y-b.m_sweep.localCenter.y;tX=tMat.col1.x*rX+tMat.col2.x*rY;rY=tMat.col1.y*rX+tMat.col2.y*rY;rX=tX;var CdotX=b.m_linearVelocity.x+-b.m_angularVelocity*rY;var CdotY=b.m_linearVelocity.y+b.m_angularVelocity*rX;tMat=this.m_mass;tX=CdotX+this.m_beta*this.m_C.x+this.m_gamma*this.m_impulse.x;tY=CdotY+this.m_beta*this.m_C.y+this.m_gamma*this.m_impulse.y;var impulseX=-(tMat.col1.x*tX+tMat.col2.x*tY);var impulseY=-(tMat.col1.y*tX+tMat.col2.y*tY);var oldImpulseX=this.m_impulse.x;var oldImpulseY=this.m_impulse.y;this.m_impulse.x+=impulseX;this.m_impulse.y+=impulseY;var maxImpulse=step.dt*this.m_maxForce;if(this.m_impulse.LengthSquared()&gt;maxImpulse*maxImpulse){this.m_impulse.Multiply(maxImpulse/this.m_impulse.Length())}impulseX=this.m_impulse.x-oldImpulseX;impulseY=this.m_impulse.y-oldImpulseY;b.m_linearVelocity.x+=b.m_invMass*impulseX;b.m_linearVelocity.y+=b.m_invMass*impulseY;b.m_angularVelocity+=b.m_invI*(rX*impulseY-rY*impulseX)};Box2D.Dynamics.Joints.b2MouseJoint.prototype.SolvePositionConstraints=function(baumgarte){return true};Box2D.Dynamics.Joints.b2MouseJointDef=function(){Box2D.Dynamics.Joints.b2JointDef.call(this);this.target=Box2D.Common.Math.b2Vec2.Get(0,0);this.type=Box2D.Dynamics.Joints.b2Joint.e_mouseJoint;this.maxForce=0;this.frequencyHz=5;this.dampingRatio=.7};Box2D.inherits(Box2D.Dynamics.Joints.b2MouseJointDef,Box2D.Dynamics.Joints.b2JointDef);Box2D.Dynamics.Joints.b2MouseJointDef.prototype.Create=function(){return new Box2D.Dynamics.Joints.b2MouseJoint(this)};Box2D.Dynamics.Joints.b2PrismaticJoint=function(def){Box2D.Dynamics.Joints.b2Joint.call(this,def);this.m_localAnchor1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localXAxis1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localYAxis1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_axis=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_perp=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_K=new Box2D.Common.Math.b2Mat33;this.m_impulse=Box2D.Common.Math.b2Vec3.Get(0,0,0);this.m_localAnchor1.SetV(def.localAnchorA);this.m_localAnchor2.SetV(def.localAnchorB);this.m_localXAxis1.SetV(def.localAxisA);this.m_localYAxis1.x=-this.m_localXAxis1.y;this.m_localYAxis1.y=this.m_localXAxis1.x;this.m_refAngle=def.referenceAngle;this.m_impulse.SetZero();this.m_motorMass=0;this.m_motorImpulse=0;this.m_lowerTranslation=def.lowerTranslation;this.m_upperTranslation=def.upperTranslation;this.m_maxMotorForce=def.maxMotorForce;this.m_motorSpeed=def.motorSpeed;this.m_enableLimit=def.enableLimit;this.m_enableMotor=def.enableMotor;this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;this.m_axis.SetZero();this.m_perp.SetZero()};Box2D.inherits(Box2D.Dynamics.Joints.b2PrismaticJoint,Box2D.Dynamics.Joints.b2Joint);Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return Box2D.Common.Math.b2Vec2.Get(inv_dt*(this.m_impulse.x*this.m_perp.x+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.x),inv_dt*(this.m_impulse.x*this.m_perp.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.y))};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return inv_dt*this.m_impulse.y};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetJointTranslation=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var p1=bA.GetWorldPoint(this.m_localAnchor1);var p2=bB.GetWorldPoint(this.m_localAnchor2);var dX=p2.x-p1.x;var dY=p2.y-p1.y;Box2D.Common.Math.b2Vec2.Free(p1);Box2D.Common.Math.b2Vec2.Free(p2);var axis=bA.GetWorldVector(this.m_localXAxis1);var translation=axis.x*dX+axis.y*dY;Box2D.Common.Math.b2Vec2.Free(axis);return translation};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetJointSpeed=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;tMat=bA.m_xf.R;var r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;var r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;var tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;var r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;var r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var p1X=bA.m_sweep.c.x+r1X;var p1Y=bA.m_sweep.c.y+r1Y;var p2X=bB.m_sweep.c.x+r2X;var p2Y=bB.m_sweep.c.y+r2Y;var dX=p2X-p1X;var dY=p2Y-p1Y;var axis=bA.GetWorldVector(this.m_localXAxis1);var v1=bA.m_linearVelocity;var v2=bB.m_linearVelocity;var w1=bA.m_angularVelocity;var w2=bB.m_angularVelocity;var speed=dX*(-w1*axis.y)+dY*(w1*axis.x)+(axis.x*(v2.x+-w2*r2Y-v1.x- -w1*r1Y)+axis.y*(v2.y+w2*r2X-v1.y-w1*r1X));Box2D.Common.Math.b2Vec2.Free(axis);return speed};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.IsLimitEnabled=function(){return this.m_enableLimit};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.EnableLimit=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetLowerLimit=function(){return this.m_lowerTranslation};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetUpperLimit=function(){return this.m_upperTranslation};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.SetLimits=function(lower,upper){if(lower===undefined)lower=0;if(upper===undefined)upper=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_lowerTranslation=lower;this.m_upperTranslation=upper};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.IsMotorEnabled=function(){return this.m_enableMotor};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.EnableMotor=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.SetMotorSpeed=function(speed){if(speed===undefined)speed=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetMotorSpeed=function(){return this.m_motorSpeed};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.SetMaxMotorForce=function(force){if(force===undefined)force=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorForce=force};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.GetMotorForce=function(){return this.m_motorImpulse};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.InitVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;var tX=0;this.m_localCenterA.SetV(bA.GetLocalCenter());this.m_localCenterB.SetV(bB.GetLocalCenter());var xf1=bA.GetTransform();tMat=bA.m_xf.R;var r1X=this.m_localAnchor1.x-this.m_localCenterA.x;var r1Y=this.m_localAnchor1.y-this.m_localCenterA.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;var r2X=this.m_localAnchor2.x-this.m_localCenterB.x;var r2Y=this.m_localAnchor2.y-this.m_localCenterB.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var dX=bB.m_sweep.c.x+r2X-bA.m_sweep.c.x-r1X;var dY=bB.m_sweep.c.y+r2Y-bA.m_sweep.c.y-r1Y;this.m_invMassA=bA.m_invMass;this.m_invMassB=bB.m_invMass;this.m_invIA=bA.m_invI;this.m_invIB=bB.m_invI;var newAxis=Box2D.Common.Math.b2Math.MulMV(xf1.R,this.m_localXAxis1);this.m_axis.SetV(newAxis);Box2D.Common.Math.b2Vec2.Free(newAxis);this.m_a1=(dX+r1X)*this.m_axis.y-(dY+r1Y)*this.m_axis.x;this.m_a2=r2X*this.m_axis.y-r2Y*this.m_axis.x;this.m_motorMass=this.m_invMassA+this.m_invMassB+this.m_invIA*this.m_a1*this.m_a1+this.m_invIB*this.m_a2*this.m_a2;if(this.m_motorMass&gt;Number.MIN_VALUE)this.m_motorMass=1/this.m_motorMass;var newPerp=Box2D.Common.Math.b2Math.MulMV(xf1.R,this.m_localYAxis1);this.m_perp.SetV(newPerp);Box2D.Common.Math.b2Vec2.Free(newPerp);this.m_s1=(dX+r1X)*this.m_perp.y-(dY+r1Y)*this.m_perp.x;this.m_s2=r2X*this.m_perp.y-r2Y*this.m_perp.x;var m1=this.m_invMassA;var m2=this.m_invMassB;var i1=this.m_invIA;var i2=this.m_invIB;this.m_K.col1.x=m1+m2+i1*this.m_s1*this.m_s1+i2*this.m_s2*this.m_s2;this.m_K.col1.y=i1*this.m_s1+i2*this.m_s2;this.m_K.col1.z=i1*this.m_s1*this.m_a1+i2*this.m_s2*this.m_a2;this.m_K.col2.x=this.m_K.col1.y;this.m_K.col2.y=i1+i2;this.m_K.col2.z=i1*this.m_a1+i2*this.m_a2;this.m_K.col3.x=this.m_K.col1.z;this.m_K.col3.y=this.m_K.col2.z;this.m_K.col3.z=m1+m2+i1*this.m_a1*this.m_a1+i2*this.m_a2*this.m_a2;if(this.m_enableLimit){var jointTransition=this.m_axis.x*dX+this.m_axis.y*dY;if(Math.abs(this.m_upperTranslation-this.m_lowerTranslation)&lt;2*Box2D.Common.b2Settings.b2_linearSlop){this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_equalLimits}else if(jointTransition&lt;=this.m_lowerTranslation){if(this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit){this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit;this.m_impulse.z=0}}else if(jointTransition&gt;=this.m_upperTranslation){if(this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit;this.m_impulse.z=0}}else{this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit}if(this.m_enableMotor==false){this.m_motorImpulse=0}if(step.warmStarting){this.m_impulse.x*=step.dtRatio;this.m_impulse.y*=step.dtRatio;this.m_motorImpulse*=step.dtRatio;var PX=this.m_impulse.x*this.m_perp.x+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.x;var PY=this.m_impulse.x*this.m_perp.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.y;var L1=this.m_impulse.x*this.m_s1+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a1;var L2=this.m_impulse.x*this.m_s2+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a2;bA.m_linearVelocity.x-=this.m_invMassA*PX;bA.m_linearVelocity.y-=this.m_invMassA*PY;bA.m_angularVelocity-=this.m_invIA*L1;bB.m_linearVelocity.x+=this.m_invMassB*PX;bB.m_linearVelocity.y+=this.m_invMassB*PY;bB.m_angularVelocity+=this.m_invIB*L2}else{this.m_impulse.SetZero();this.m_motorImpulse=0}};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.SolveVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var v1=bA.m_linearVelocity;var w1=bA.m_angularVelocity;var v2=bB.m_linearVelocity;var w2=bB.m_angularVelocity;var PX=0;var PY=0;var L1=0;var L2=0;if(this.m_enableMotor&amp;&amp;this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_equalLimits){var Cdot=this.m_axis.x*(v2.x-v1.x)+this.m_axis.y*(v2.y-v1.y)+this.m_a2*w2-this.m_a1*w1;var impulse=this.m_motorMass*(this.m_motorSpeed-Cdot);var oldImpulse=this.m_motorImpulse;var maxImpulse=step.dt*this.m_maxMotorForce;this.m_motorImpulse=Box2D.Common.Math.b2Math.Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;PX=impulse*this.m_axis.x;PY=impulse*this.m_axis.y;L1=impulse*this.m_a1;L2=impulse*this.m_a2;v1.x-=this.m_invMassA*PX;v1.y-=this.m_invMassA*PY;w1-=this.m_invIA*L1;v2.x+=this.m_invMassB*PX;v2.y+=this.m_invMassB*PY;w2+=this.m_invIB*L2}var Cdot1X=this.m_perp.x*(v2.x-v1.x)+this.m_perp.y*(v2.y-v1.y)+this.m_s2*w2-this.m_s1*w1;var Cdot1Y=w2-w1;if(this.m_enableLimit&amp;&amp;this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit){var Cdot2=this.m_axis.x*(v2.x-v1.x)+this.m_axis.y*(v2.y-v1.y)+this.m_a2*w2-this.m_a1*w1;var f1=this.m_impulse.Copy();var df=Box2D.Common.Math.b2Vec3.Get(0,0,0);this.m_K.Solve33(df,-Cdot1X,-Cdot1Y,-Cdot2);this.m_impulse.Add(df);if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit){this.m_impulse.z=Math.max(this.m_impulse.z,0)}else if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){this.m_impulse.z=Math.min(this.m_impulse.z,0)}var bX=-Cdot1X-(this.m_impulse.z-f1.z)*this.m_K.col3.x;var bY=-Cdot1Y-(this.m_impulse.z-f1.z)*this.m_K.col3.y;var out=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_K.Solve22(out,bX,bY);out.x+=f1.x;out.y+=f1.y;this.m_impulse.x=out.x;this.m_impulse.y=out.y;Box2D.Common.Math.b2Vec2.Free(out);df.x=this.m_impulse.x-f1.x;df.y=this.m_impulse.y-f1.y;df.z=this.m_impulse.z-f1.z;PX=df.x*this.m_perp.x+df.z*this.m_axis.x;PY=df.x*this.m_perp.y+df.z*this.m_axis.y;L1=df.x*this.m_s1+df.y+df.z*this.m_a1;L2=df.x*this.m_s2+df.y+df.z*this.m_a2;Box2D.Common.Math.b2Vec3.Free(df);v1.x-=this.m_invMassA*PX;v1.y-=this.m_invMassA*PY;w1-=this.m_invIA*L1;v2.x+=this.m_invMassB*PX;v2.y+=this.m_invMassB*PY;w2+=this.m_invIB*L2}else{var df2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_K.Solve22(df2,-Cdot1X,-Cdot1Y);this.m_impulse.x+=df2.x;this.m_impulse.y+=df2.y;PX=df2.x*this.m_perp.x;PY=df2.x*this.m_perp.y;L1=df2.x*this.m_s1+df2.y;L2=df2.x*this.m_s2+df2.y;Box2D.Common.Math.b2Vec2.Free(df2);v1.x-=this.m_invMassA*PX;v1.y-=this.m_invMassA*PY;w1-=this.m_invIA*L1;v2.x+=this.m_invMassB*PX;v2.y+=this.m_invMassB*PY;w2+=this.m_invIB*L2}bA.m_linearVelocity.SetV(v1);bA.m_angularVelocity=w1;bB.m_linearVelocity.SetV(v2);bB.m_angularVelocity=w2};Box2D.Dynamics.Joints.b2PrismaticJoint.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;var bA=this.m_bodyA;var bB=this.m_bodyB;var c1=bA.m_sweep.c;var a1=bA.m_sweep.a;var c2=bB.m_sweep.c;var a2=bB.m_sweep.a;var tX=0;var m1=0;var m2=0;var i1=0;var i2=0;var linearError=0;var angularError=0;var active=false;var C2=0;var R1=Box2D.Common.Math.b2Mat22.FromAngle(a1);var r1X=this.m_localAnchor1.x-this.m_localCenterA.x;var r1Y=this.m_localAnchor1.y-this.m_localCenterA.y;tX=R1.col1.x*r1X+R1.col2.x*r1Y;r1Y=R1.col1.y*r1X+R1.col2.y*r1Y;Box2D.Common.Math.b2Mat22.Free(R1);r1X=tX;var R2=Box2D.Common.Math.b2Mat22.FromAngle(a2);var r2X=this.m_localAnchor2.x-this.m_localCenterB.x;var r2Y=this.m_localAnchor2.y-this.m_localCenterB.y;tX=R2.col1.x*r2X+R2.col2.x*r2Y;r2Y=R2.col1.y*r2X+R2.col2.y*r2Y;Box2D.Common.Math.b2Mat22.Free(R2);r2X=tX;var dX=c2.x+r2X-c1.x-r1X;var dY=c2.y+r2Y-c1.y-r1Y;if(this.m_enableLimit){Box2D.Common.Math.b2Vec2.Free(this.m_axis);this.m_axis=Box2D.Common.Math.b2Math.MulMV(R1,this.m_localXAxis1);this.m_a1=(dX+r1X)*this.m_axis.y-(dY+r1Y)*this.m_axis.x;this.m_a2=r2X*this.m_axis.y-r2Y*this.m_axis.x;var translation=this.m_axis.x*dX+this.m_axis.y*dY;if(Math.abs(this.m_upperTranslation-this.m_lowerTranslation)&lt;2*Box2D.Common.b2Settings.b2_linearSlop){C2=Box2D.Common.Math.b2Math.Clamp(translation,-Box2D.Common.b2Settings.b2_maxLinearCorrection,Box2D.Common.b2Settings.b2_maxLinearCorrection);linearError=Math.abs(translation);active=true}else if(translation&lt;=this.m_lowerTranslation){C2=Box2D.Common.Math.b2Math.Clamp(translation-this.m_lowerTranslation+Box2D.Common.b2Settings.b2_linearSlop,-Box2D.Common.b2Settings.b2_maxLinearCorrection,0);linearError=this.m_lowerTranslation-translation;active=true}else if(translation&gt;=this.m_upperTranslation){C2=Box2D.Common.Math.b2Math.Clamp(translation-this.m_upperTranslation+Box2D.Common.b2Settings.b2_linearSlop,0,Box2D.Common.b2Settings.b2_maxLinearCorrection);linearError=translation-this.m_upperTranslation;active=true}}Box2D.Common.Math.b2Vec2.Free(this.m_perp);this.m_perp=Box2D.Common.Math.b2Math.MulMV(R1,this.m_localYAxis1);this.m_s1=(dX+r1X)*this.m_perp.y-(dY+r1Y)*this.m_perp.x;this.m_s2=r2X*this.m_perp.y-r2Y*this.m_perp.x;var impulse=Box2D.Common.Math.b2Vec3.Get(0,0,0);var C1X=this.m_perp.x*dX+this.m_perp.y*dY;var C1Y=a2-a1-this.m_refAngle;linearError=Math.max(linearError,Math.abs(C1X));angularError=Math.abs(C1Y);if(active){m1=this.m_invMassA;m2=this.m_invMassB;i1=this.m_invIA;i2=this.m_invIB;this.m_K.col1.x=m1+m2+i1*this.m_s1*this.m_s1+i2*this.m_s2*this.m_s2;this.m_K.col1.y=i1*this.m_s1+i2*this.m_s2;this.m_K.col1.z=i1*this.m_s1*this.m_a1+i2*this.m_s2*this.m_a2;this.m_K.col2.x=this.m_K.col1.y;this.m_K.col2.y=i1+i2;this.m_K.col2.z=i1*this.m_a1+i2*this.m_a2;this.m_K.col3.x=this.m_K.col1.z;this.m_K.col3.y=this.m_K.col2.z;this.m_K.col3.z=m1+m2+i1*this.m_a1*this.m_a1+i2*this.m_a2*this.m_a2;this.m_K.Solve33(impulse,-C1X,-C1Y,-C2)}else{m1=this.m_invMassA;m2=this.m_invMassB;i1=this.m_invIA;i2=this.m_invIB;var k11=m1+m2+i1*this.m_s1*this.m_s1+i2*this.m_s2*this.m_s2;var k12=i1*this.m_s1+i2*this.m_s2;var k22=i1+i2;this.m_K.col1.Set(k11,k12,0);this.m_K.col2.Set(k12,k22,0);var impulse1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_K.Solve22(impulse1,-C1X,-C1Y);impulse.x=impulse1.x;impulse.y=impulse1.y;Box2D.Common.Math.b2Vec2.Free(impulse1);impulse.z=0}var PX=impulse.x*this.m_perp.x+impulse.z*this.m_axis.x;var PY=impulse.x*this.m_perp.y+impulse.z*this.m_axis.y;var L1=impulse.x*this.m_s1+impulse.y+impulse.z*this.m_a1;var L2=impulse.x*this.m_s2+impulse.y+impulse.z*this.m_a2;Box2D.Common.Math.b2Vec3.Free(impulse);c1.x-=this.m_invMassA*PX;c1.y-=this.m_invMassA*PY;a1-=this.m_invIA*L1;c2.x+=this.m_invMassB*PX;c2.y+=this.m_invMassB*PY;a2+=this.m_invIB*L2;bA.m_sweep.a=a1;bB.m_sweep.a=a2;bA.SynchronizeTransform();bB.SynchronizeTransform();return linearError&lt;=Box2D.Common.b2Settings.b2_linearSlop&amp;&amp;angularError&lt;=Box2D.Common.b2Settings.b2_angularSlop};Box2D.Dynamics.Joints.b2PrismaticJointDef=function(){Box2D.Dynamics.Joints.b2JointDef.call(this);this.localAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAxisA=Box2D.Common.Math.b2Vec2.Get(0,0);this.type=Box2D.Dynamics.Joints.b2Joint.e_prismaticJoint;this.localAxisA.Set(1,0);this.referenceAngle=0;this.enableLimit=false;this.lowerTranslation=0;this.upperTranslation=0;this.enableMotor=false;this.maxMotorForce=0;this.motorSpeed=0};Box2D.inherits(Box2D.Dynamics.Joints.b2PrismaticJointDef,Box2D.Dynamics.Joints.b2JointDef);Box2D.Dynamics.Joints.b2PrismaticJointDef.prototype.Initialize=function(bA,bB,anchor,axis){this.bodyA=bA;this.bodyB=bB;this.localAnchorA=this.bodyA.GetLocalPoint(anchor);this.localAnchorB=this.bodyB.GetLocalPoint(anchor);this.localAxisA=this.bodyA.GetLocalVector(axis);this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle()};Box2D.Dynamics.Joints.b2PrismaticJointDef.prototype.Create=function(){return new Box2D.Dynamics.Joints.b2PrismaticJoint(this)};Box2D.Dynamics.Joints.b2PulleyJoint=function(def){Box2D.Dynamics.Joints.b2Joint.call(this,def);this.m_groundAnchor1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_groundAnchor2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_u1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_u2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_ground=this.m_bodyA.m_world.m_groundBody;this.m_groundAnchor1.x=def.groundAnchorA.x-this.m_ground.m_xf.position.x;this.m_groundAnchor1.y=def.groundAnchorA.y-this.m_ground.m_xf.position.y;this.m_groundAnchor2.x=def.groundAnchorB.x-this.m_ground.m_xf.position.x;this.m_groundAnchor2.y=def.groundAnchorB.y-this.m_ground.m_xf.position.y;this.m_localAnchor1.SetV(def.localAnchorA);this.m_localAnchor2.SetV(def.localAnchorB);this.m_ratio=def.ratio;this.m_constant=def.lengthA+this.m_ratio*def.lengthB;this.m_maxLength1=Math.min(def.maxLengthA,this.m_constant-this.m_ratio*Box2D.Dynamics.Joints.b2PulleyJoint.b2_minPulleyLength);this.m_maxLength2=Math.min(def.maxLengthB,(this.m_constant-Box2D.Dynamics.Joints.b2PulleyJoint.b2_minPulleyLength)/this.m_ratio);this.m_impulse=0;this.m_limitImpulse1=0;this.m_limitImpulse2=0};Box2D.inherits(Box2D.Dynamics.Joints.b2PulleyJoint,Box2D.Dynamics.Joints.b2Joint);Box2D.Dynamics.Joints.b2PulleyJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return Box2D.Common.Math.b2Vec2.Get(inv_dt*this.m_impulse*this.m_u2.x,inv_dt*this.m_impulse*this.m_u2.y)};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return 0};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.GetGroundAnchorA=function(){var a=this.m_ground.m_xf.position.Copy();a.Add(this.m_groundAnchor1);return a};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.GetGroundAnchorB=function(){var a=this.m_ground.m_xf.position.Copy();a.Add(this.m_groundAnchor2);return a};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.GetLength1=function(){var p=this.m_bodyA.GetWorldPoint(this.m_localAnchor1);var sX=this.m_ground.m_xf.position.x+this.m_groundAnchor1.x;var sY=this.m_ground.m_xf.position.y+this.m_groundAnchor1.y;var dX=p.x-sX;var dY=p.y-sY;return Math.sqrt(dX*dX+dY*dY)};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.GetLength2=function(){var p=this.m_bodyB.GetWorldPoint(this.m_localAnchor2);var sX=this.m_ground.m_xf.position.x+this.m_groundAnchor2.x;var sY=this.m_ground.m_xf.position.y+this.m_groundAnchor2.y;var dX=p.x-sX;var dY=p.y-sY;return Math.sqrt(dX*dX+dY*dY)};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.GetRatio=function(){return this.m_ratio};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.InitVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;tMat=bA.m_xf.R;var r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;var r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;var tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;var r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;var r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var p1X=bA.m_sweep.c.x+r1X;var p1Y=bA.m_sweep.c.y+r1Y;var p2X=bB.m_sweep.c.x+r2X;var p2Y=bB.m_sweep.c.y+r2Y;var s1X=this.m_ground.m_xf.position.x+this.m_groundAnchor1.x;var s1Y=this.m_ground.m_xf.position.y+this.m_groundAnchor1.y;var s2X=this.m_ground.m_xf.position.x+this.m_groundAnchor2.x;var s2Y=this.m_ground.m_xf.position.y+this.m_groundAnchor2.y;this.m_u1.Set(p1X-s1X,p1Y-s1Y);this.m_u2.Set(p2X-s2X,p2Y-s2Y);var length1=this.m_u1.Length();var length2=this.m_u2.Length();if(length1&gt;Box2D.Common.b2Settings.b2_linearSlop){this.m_u1.Multiply(1/length1)}else{this.m_u1.SetZero()}if(length2&gt;Box2D.Common.b2Settings.b2_linearSlop){this.m_u2.Multiply(1/length2)}else{this.m_u2.SetZero()}var C=this.m_constant-length1-this.m_ratio*length2;if(C&gt;0){this.m_state=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;this.m_impulse=0}else{this.m_state=Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit}if(length1&lt;this.m_maxLength1){this.m_limitState1=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;this.m_limitImpulse1=0}else{this.m_limitState1=Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit}if(length2&lt;this.m_maxLength2){this.m_limitState2=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;this.m_limitImpulse2=0}else{this.m_limitState2=Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit}var cr1u1=r1X*this.m_u1.y-r1Y*this.m_u1.x;var cr2u2=r2X*this.m_u2.y-r2Y*this.m_u2.x;this.m_limitMass1=bA.m_invMass+bA.m_invI*cr1u1*cr1u1;this.m_limitMass2=bB.m_invMass+bB.m_invI*cr2u2*cr2u2;this.m_pulleyMass=this.m_limitMass1+this.m_ratio*this.m_ratio*this.m_limitMass2;this.m_limitMass1=1/this.m_limitMass1;this.m_limitMass2=1/this.m_limitMass2;this.m_pulleyMass=1/this.m_pulleyMass;if(step.warmStarting){this.m_impulse*=step.dtRatio;this.m_limitImpulse1*=step.dtRatio;this.m_limitImpulse2*=step.dtRatio;var P1X=(-this.m_impulse-this.m_limitImpulse1)*this.m_u1.x;var P1Y=(-this.m_impulse-this.m_limitImpulse1)*this.m_u1.y;var P2X=(-this.m_ratio*this.m_impulse-this.m_limitImpulse2)*this.m_u2.x;var P2Y=(-this.m_ratio*this.m_impulse-this.m_limitImpulse2)*this.m_u2.y;bA.m_linearVelocity.x+=bA.m_invMass*P1X;bA.m_linearVelocity.y+=bA.m_invMass*P1Y;bA.m_angularVelocity+=bA.m_invI*(r1X*P1Y-r1Y*P1X);bB.m_linearVelocity.x+=bB.m_invMass*P2X;bB.m_linearVelocity.y+=bB.m_invMass*P2Y;bB.m_angularVelocity+=bB.m_invI*(r2X*P2Y-r2Y*P2X)}else{this.m_impulse=0;this.m_limitImpulse1=0;this.m_limitImpulse2=0}};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.SolveVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;tMat=bA.m_xf.R;var r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;var r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;var tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;var r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;var r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var v1X=0;var v1Y=0;var v2X=0;var v2Y=0;var P1X=0;var P1Y=0;var P2X=0;var P2Y=0;var Cdot=0;var impulse=0;var oldImpulse=0;if(this.m_state==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){v1X=bA.m_linearVelocity.x+-bA.m_angularVelocity*r1Y;v1Y=bA.m_linearVelocity.y+bA.m_angularVelocity*r1X;v2X=bB.m_linearVelocity.x+-bB.m_angularVelocity*r2Y;v2Y=bB.m_linearVelocity.y+bB.m_angularVelocity*r2X;Cdot=-(this.m_u1.x*v1X+this.m_u1.y*v1Y)-this.m_ratio*(this.m_u2.x*v2X+this.m_u2.y*v2Y);impulse=this.m_pulleyMass*-Cdot;oldImpulse=this.m_impulse;this.m_impulse=Math.max(0,this.m_impulse+impulse);impulse=this.m_impulse-oldImpulse;P1X=-impulse*this.m_u1.x;P1Y=-impulse*this.m_u1.y;P2X=-this.m_ratio*impulse*this.m_u2.x;P2Y=-this.m_ratio*impulse*this.m_u2.y;bA.m_linearVelocity.x+=bA.m_invMass*P1X;bA.m_linearVelocity.y+=bA.m_invMass*P1Y;bA.m_angularVelocity+=bA.m_invI*(r1X*P1Y-r1Y*P1X);bB.m_linearVelocity.x+=bB.m_invMass*P2X;bB.m_linearVelocity.y+=bB.m_invMass*P2Y;bB.m_angularVelocity+=bB.m_invI*(r2X*P2Y-r2Y*P2X)}if(this.m_limitState1==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){v1X=bA.m_linearVelocity.x+-bA.m_angularVelocity*r1Y;v1Y=bA.m_linearVelocity.y+bA.m_angularVelocity*r1X;Cdot=-(this.m_u1.x*v1X+this.m_u1.y*v1Y);impulse=-this.m_limitMass1*Cdot;oldImpulse=this.m_limitImpulse1;this.m_limitImpulse1=Math.max(0,this.m_limitImpulse1+impulse);impulse=this.m_limitImpulse1-oldImpulse;P1X=-impulse*this.m_u1.x;P1Y=-impulse*this.m_u1.y;bA.m_linearVelocity.x+=bA.m_invMass*P1X;bA.m_linearVelocity.y+=bA.m_invMass*P1Y;bA.m_angularVelocity+=bA.m_invI*(r1X*P1Y-r1Y*P1X)}if(this.m_limitState2==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){v2X=bB.m_linearVelocity.x+-bB.m_angularVelocity*r2Y;v2Y=bB.m_linearVelocity.y+bB.m_angularVelocity*r2X;Cdot=-(this.m_u2.x*v2X+this.m_u2.y*v2Y);impulse=-this.m_limitMass2*Cdot;oldImpulse=this.m_limitImpulse2;this.m_limitImpulse2=Math.max(0,this.m_limitImpulse2+impulse);impulse=this.m_limitImpulse2-oldImpulse;P2X=-impulse*this.m_u2.x;P2Y=-impulse*this.m_u2.y;bB.m_linearVelocity.x+=bB.m_invMass*P2X;bB.m_linearVelocity.y+=bB.m_invMass*P2Y;bB.m_angularVelocity+=bB.m_invI*(r2X*P2Y-r2Y*P2X)}};Box2D.Dynamics.Joints.b2PulleyJoint.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;var s1X=this.m_ground.m_xf.position.x+this.m_groundAnchor1.x;var s1Y=this.m_ground.m_xf.position.y+this.m_groundAnchor1.y;var s2X=this.m_ground.m_xf.position.x+this.m_groundAnchor2.x;var s2Y=this.m_ground.m_xf.position.y+this.m_groundAnchor2.y;var r1X=0;var r1Y=0;var r2X=0;var r2Y=0;var p1X=0;var p1Y=0;var p2X=0;var p2Y=0;var length1=0;var length2=0;var C=0;var impulse=0;var oldImpulse=0;var oldLimitPositionImpulse=0;var tX=0;var linearError=0;if(this.m_state==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){tMat=bA.m_xf.R;r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;p1X=bA.m_sweep.c.x+r1X;p1Y=bA.m_sweep.c.y+r1Y;p2X=bB.m_sweep.c.x+r2X;p2Y=bB.m_sweep.c.y+r2Y;this.m_u1.Set(p1X-s1X,p1Y-s1Y);this.m_u2.Set(p2X-s2X,p2Y-s2Y);length1=this.m_u1.Length();length2=this.m_u2.Length();if(length1&gt;Box2D.Common.b2Settings.b2_linearSlop){this.m_u1.Multiply(1/length1)}else{this.m_u1.SetZero()}if(length2&gt;Box2D.Common.b2Settings.b2_linearSlop){this.m_u2.Multiply(1/length2)}else{this.m_u2.SetZero()}C=this.m_constant-length1-this.m_ratio*length2;linearError=Math.max(linearError,-C);C=Box2D.Common.Math.b2Math.Clamp(C+Box2D.Common.b2Settings.b2_linearSlop,-Box2D.Common.b2Settings.b2_maxLinearCorrection,0);impulse=-this.m_pulleyMass*C;p1X=-impulse*this.m_u1.x;p1Y=-impulse*this.m_u1.y;p2X=-this.m_ratio*impulse*this.m_u2.x;p2Y=-this.m_ratio*impulse*this.m_u2.y;bA.m_sweep.c.x+=bA.m_invMass*p1X;bA.m_sweep.c.y+=bA.m_invMass*p1Y;bA.m_sweep.a+=bA.m_invI*(r1X*p1Y-r1Y*p1X);bB.m_sweep.c.x+=bB.m_invMass*p2X;bB.m_sweep.c.y+=bB.m_invMass*p2Y;bB.m_sweep.a+=bB.m_invI*(r2X*p2Y-r2Y*p2X);bA.SynchronizeTransform();bB.SynchronizeTransform()}if(this.m_limitState1==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){tMat=bA.m_xf.R;r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;p1X=bA.m_sweep.c.x+r1X;p1Y=bA.m_sweep.c.y+r1Y;this.m_u1.Set(p1X-s1X,p1Y-s1Y);length1=this.m_u1.Length();if(length1&gt;Box2D.Common.b2Settings.b2_linearSlop){this.m_u1.x*=1/length1;this.m_u1.y*=1/length1}else{this.m_u1.SetZero()}C=this.m_maxLength1-length1;linearError=Math.max(linearError,-C);C=Box2D.Common.Math.b2Math.Clamp(C+Box2D.Common.b2Settings.b2_linearSlop,-Box2D.Common.b2Settings.b2_maxLinearCorrection,0);impulse=-this.m_limitMass1*C;p1X=-impulse*this.m_u1.x;p1Y=-impulse*this.m_u1.y;bA.m_sweep.c.x+=bA.m_invMass*p1X;bA.m_sweep.c.y+=bA.m_invMass*p1Y;bA.m_sweep.a+=bA.m_invI*(r1X*p1Y-r1Y*p1X);bA.SynchronizeTransform()}if(this.m_limitState2==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){tMat=bB.m_xf.R;r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;p2X=bB.m_sweep.c.x+r2X;p2Y=bB.m_sweep.c.y+r2Y;this.m_u2.Set(p2X-s2X,p2Y-s2Y);length2=this.m_u2.Length();if(length2&gt;Box2D.Common.b2Settings.b2_linearSlop){this.m_u2.x*=1/length2;this.m_u2.y*=1/length2}else{this.m_u2.SetZero()}C=this.m_maxLength2-length2;linearError=Math.max(linearError,-C);C=Box2D.Common.Math.b2Math.Clamp(C+Box2D.Common.b2Settings.b2_linearSlop,-Box2D.Common.b2Settings.b2_maxLinearCorrection,0);impulse=-this.m_limitMass2*C;p2X=-impulse*this.m_u2.x;p2Y=-impulse*this.m_u2.y;bB.m_sweep.c.x+=bB.m_invMass*p2X;bB.m_sweep.c.y+=bB.m_invMass*p2Y;bB.m_sweep.a+=bB.m_invI*(r2X*p2Y-r2Y*p2X);bB.SynchronizeTransform()}return linearError&lt;Box2D.Common.b2Settings.b2_linearSlop};Box2D.Dynamics.Joints.b2PulleyJoint.b2_minPulleyLength=1;Box2D.Dynamics.Joints.b2PulleyJointDef=function(){Box2D.Dynamics.Joints.b2JointDef.call(this);this.groundAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.groundAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.type=Box2D.Dynamics.Joints.b2Joint.e_pulleyJoint;this.groundAnchorA.Set(-1,1);this.groundAnchorB.Set(1,1);this.localAnchorA.Set(-1,0);this.localAnchorB.Set(1,0);this.lengthA=0;this.maxLengthA=0;this.lengthB=0;this.maxLengthB=0;this.ratio=1;this.collideConnected=true};Box2D.inherits(Box2D.Dynamics.Joints.b2PulleyJointDef,Box2D.Dynamics.Joints.b2JointDef);Box2D.Dynamics.Joints.b2PulleyJointDef.prototype.Initialize=function(bA,bB,gaA,gaB,anchorA,anchorB,r){if(r===undefined)r=0;this.bodyA=bA;this.bodyB=bB;this.groundAnchorA.SetV(gaA);this.groundAnchorB.SetV(gaB);this.localAnchorA=this.bodyA.GetLocalPoint(anchorA);this.localAnchorB=this.bodyB.GetLocalPoint(anchorB);var d1X=anchorA.x-gaA.x;var d1Y=anchorA.y-gaA.y;this.lengthA=Math.sqrt(d1X*d1X+d1Y*d1Y);var d2X=anchorB.x-gaB.x;var d2Y=anchorB.y-gaB.y;this.lengthB=Math.sqrt(d2X*d2X+d2Y*d2Y);this.ratio=r;var C=this.lengthA+this.ratio*this.lengthB;this.maxLengthA=C-this.ratio*Box2D.Dynamics.Joints.b2PulleyJoint.b2_minPulleyLength;this.maxLengthB=(C-Box2D.Dynamics.Joints.b2PulleyJoint.b2_minPulleyLength)/this.ratio};Box2D.Dynamics.Joints.b2PulleyJointDef.prototype.Create=function(){return new Box2D.Dynamics.Joints.b2PulleyJoint(this)};Box2D.Dynamics.Joints.b2RevoluteJoint=function(def){Box2D.Dynamics.Joints.b2Joint.call(this,def);this.K=Box2D.Common.Math.b2Mat22.Get();this.K1=Box2D.Common.Math.b2Mat22.Get();this.K2=Box2D.Common.Math.b2Mat22.Get();this.K3=Box2D.Common.Math.b2Mat22.Get();this.impulse3=Box2D.Common.Math.b2Vec3.Get(0,0,0);this.impulse2=Box2D.Common.Math.b2Vec2.Get(0,0);this.reduced=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor1=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchor2=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_impulse=Box2D.Common.Math.b2Vec3.Get(0,0,0);this.m_mass=new Box2D.Common.Math.b2Mat33;this.m_localAnchor1.SetV(def.localAnchorA);this.m_localAnchor2.SetV(def.localAnchorB);this.m_referenceAngle=def.referenceAngle;this.m_impulse.SetZero();this.m_motorImpulse=0;this.m_lowerAngle=def.lowerAngle;this.m_upperAngle=def.upperAngle;this.m_maxMotorTorque=def.maxMotorTorque;this.m_motorSpeed=def.motorSpeed;this.m_enableLimit=def.enableLimit;this.m_enableMotor=def.enableMotor;this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;this.m_motorMass=0};Box2D.inherits(Box2D.Dynamics.Joints.b2RevoluteJoint,Box2D.Dynamics.Joints.b2Joint);Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return Box2D.Common.Math.b2Vec2.Get(inv_dt*this.m_impulse.x,inv_dt*this.m_impulse.y)};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return inv_dt*this.m_impulse.z};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetJointAngle=function(){return this.m_bodyB.m_sweep.a-this.m_bodyA.m_sweep.a-this.m_referenceAngle};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetJointSpeed=function(){return this.m_bodyB.m_angularVelocity-this.m_bodyA.m_angularVelocity};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.IsLimitEnabled=function(){return this.m_enableLimit};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.EnableLimit=function(flag){this.m_enableLimit=flag};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetLowerLimit=function(){return this.m_lowerAngle};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetUpperLimit=function(){return this.m_upperAngle};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.SetLimits=function(lower,upper){if(lower===undefined)lower=0;if(upper===undefined)upper=0;this.m_lowerAngle=lower;this.m_upperAngle=upper};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.IsMotorEnabled=function(){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);return this.m_enableMotor};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.EnableMotor=function(flag){this.m_enableMotor=flag};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.SetMotorSpeed=function(speed){if(speed===undefined)speed=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetMotorSpeed=function(){return this.m_motorSpeed};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.SetMaxMotorTorque=function(torque){if(torque===undefined)torque=0;this.m_maxMotorTorque=torque};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.GetMotorTorque=function(){return this.m_maxMotorTorque};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.InitVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;var tX=0;tMat=bA.m_xf.R;var r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;var r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;var r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;var r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var m1=bA.m_invMass;var m2=bB.m_invMass;var i1=bA.m_invI;var i2=bB.m_invI;this.m_mass.col1.x=m1+m2+r1Y*r1Y*i1+r2Y*r2Y*i2;this.m_mass.col2.x=-r1Y*r1X*i1-r2Y*r2X*i2;this.m_mass.col3.x=-r1Y*i1-r2Y*i2;this.m_mass.col1.y=this.m_mass.col2.x;this.m_mass.col2.y=m1+m2+r1X*r1X*i1+r2X*r2X*i2;this.m_mass.col3.y=r1X*i1+r2X*i2;this.m_mass.col1.z=this.m_mass.col3.x;this.m_mass.col2.z=this.m_mass.col3.y;this.m_mass.col3.z=i1+i2;if(i1+i2==0){this.m_motorMass=0}else{this.m_motorMass=1/(i1+i2)}if(!this.m_enableMotor){this.m_motorImpulse=0}if(this.m_enableLimit){var jointAngle=bB.m_sweep.a-bA.m_sweep.a-this.m_referenceAngle;if(Math.abs(this.m_upperAngle-this.m_lowerAngle)&lt;2*Box2D.Common.b2Settings.b2_angularSlop){this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_equalLimits}else if(jointAngle&lt;=this.m_lowerAngle){if(this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit){this.m_impulse.z=0}this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit}else if(jointAngle&gt;=this.m_upperAngle){if(this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){this.m_impulse.z=0}this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit}else{this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit}if(step.warmStarting){this.m_impulse.x*=step.dtRatio;this.m_impulse.y*=step.dtRatio;this.m_motorImpulse*=step.dtRatio;var PX=this.m_impulse.x;var PY=this.m_impulse.y;bA.m_linearVelocity.x-=m1*PX;bA.m_linearVelocity.y-=m1*PY;bA.m_angularVelocity-=i1*(r1X*PY-r1Y*PX+this.m_motorImpulse+this.m_impulse.z);bB.m_linearVelocity.x+=m2*PX;bB.m_linearVelocity.y+=m2*PY;bB.m_angularVelocity+=i2*(r2X*PY-r2Y*PX+this.m_motorImpulse+this.m_impulse.z)}else{this.m_impulse.SetZero();this.m_motorImpulse=0}};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.SolveVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var tMat;var tX=0;var newImpulse=0;var r1X=0;var r1Y=0;var r2X=0;var r2Y=0;var v1=bA.m_linearVelocity;var w1=bA.m_angularVelocity;var v2=bB.m_linearVelocity;var w2=bB.m_angularVelocity;var m1=bA.m_invMass;var m2=bB.m_invMass;var i1=bA.m_invI;var i2=bB.m_invI;if(this.m_enableMotor&amp;&amp;this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_equalLimits){var Cdot=w2-w1-this.m_motorSpeed;var impulse=this.m_motorMass*-Cdot;var oldImpulse=this.m_motorImpulse;var maxImpulse=step.dt*this.m_maxMotorTorque;this.m_motorImpulse=Box2D.Common.Math.b2Math.Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;w1-=i1*impulse;w2+=i2*impulse}if(this.m_enableLimit&amp;&amp;this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit){tMat=bA.m_xf.R;r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var Cdot1X=v2.x+-w2*r2Y-v1.x- -w1*r1Y;var Cdot1Y=v2.y+w2*r2X-v1.y-w1*r1X;var Cdot2=w2-w1;this.m_mass.Solve33(this.impulse3,-Cdot1X,-Cdot1Y,-Cdot2);if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_equalLimits){this.m_impulse.Add(this.impulse3)}else if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit){newImpulse=this.m_impulse.z+this.impulse3.z;if(newImpulse&lt;0){this.m_mass.Solve22(this.reduced,-Cdot1X,-Cdot1Y);this.impulse3.x=this.reduced.x;this.impulse3.y=this.reduced.y;this.impulse3.z=-this.m_impulse.z;this.m_impulse.x+=this.reduced.x;this.m_impulse.y+=this.reduced.y;this.m_impulse.z=0}}else if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){newImpulse=this.m_impulse.z+this.impulse3.z;if(newImpulse&gt;0){this.m_mass.Solve22(this.reduced,-Cdot1X,-Cdot1Y);this.impulse3.x=this.reduced.x;this.impulse3.y=this.reduced.y;this.impulse3.z=-this.m_impulse.z;this.m_impulse.x+=this.reduced.x;this.m_impulse.y+=this.reduced.y;this.m_impulse.z=0}}v1.x-=m1*this.impulse3.x;v1.y-=m1*this.impulse3.y;w1-=i1*(r1X*this.impulse3.y-r1Y*this.impulse3.x+this.impulse3.z);v2.x+=m2*this.impulse3.x;v2.y+=m2*this.impulse3.y;w2+=i2*(r2X*this.impulse3.y-r2Y*this.impulse3.x+this.impulse3.z)}else{tMat=bA.m_xf.R;r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var CdotX=v2.x+-w2*r2Y-v1.x- -w1*r1Y;var CdotY=v2.y+w2*r2X-v1.y-w1*r1X;this.m_mass.Solve22(this.impulse2,-CdotX,-CdotY);this.m_impulse.x+=this.impulse2.x;this.m_impulse.y+=this.impulse2.y;v1.x-=m1*this.impulse2.x;v1.y-=m1*this.impulse2.y;w1-=i1*(r1X*this.impulse2.y-r1Y*this.impulse2.x);v2.x+=m2*this.impulse2.x;v2.y+=m2*this.impulse2.y;w2+=i2*(r2X*this.impulse2.y-r2Y*this.impulse2.x)}bA.m_linearVelocity.SetV(v1);bA.m_angularVelocity=w1;bB.m_linearVelocity.SetV(v2);bB.m_angularVelocity=w2};Box2D.Dynamics.Joints.b2RevoluteJoint.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;var oldLimitImpulse=0;var C=0;var tMat;var bA=this.m_bodyA;var bB=this.m_bodyB;var angularError=0;var positionError=0;var tX=0;var impulseX=0;var impulseY=0;if(this.m_enableLimit&amp;&amp;this.m_limitState!=Box2D.Dynamics.Joints.b2Joint.e_inactiveLimit){var angle=bB.m_sweep.a-bA.m_sweep.a-this.m_referenceAngle;var limitImpulse=0;if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_equalLimits){C=Box2D.Common.Math.b2Math.Clamp(angle-this.m_lowerAngle,-Box2D.Common.b2Settings.b2_maxAngularCorrection,Box2D.Common.b2Settings.b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C;angularError=Math.abs(C)}else if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_atLowerLimit){C=angle-this.m_lowerAngle;angularError=-C;C=Box2D.Common.Math.b2Math.Clamp(C+Box2D.Common.b2Settings.b2_angularSlop,-Box2D.Common.b2Settings.b2_maxAngularCorrection,0);limitImpulse=-this.m_motorMass*C}else if(this.m_limitState==Box2D.Dynamics.Joints.b2Joint.e_atUpperLimit){C=angle-this.m_upperAngle;angularError=C;C=Box2D.Common.Math.b2Math.Clamp(C-Box2D.Common.b2Settings.b2_angularSlop,0,Box2D.Common.b2Settings.b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C}bA.m_sweep.a-=bA.m_invI*limitImpulse;bB.m_sweep.a+=bB.m_invI*limitImpulse;bA.SynchronizeTransform();bB.SynchronizeTransform()}tMat=bA.m_xf.R;var r1X=this.m_localAnchor1.x-bA.m_sweep.localCenter.x;var r1Y=this.m_localAnchor1.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*r1X+tMat.col2.x*r1Y;r1Y=tMat.col1.y*r1X+tMat.col2.y*r1Y;r1X=tX;tMat=bB.m_xf.R;var r2X=this.m_localAnchor2.x-bB.m_sweep.localCenter.x;var r2Y=this.m_localAnchor2.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*r2X+tMat.col2.x*r2Y;r2Y=tMat.col1.y*r2X+tMat.col2.y*r2Y;r2X=tX;var CX=bB.m_sweep.c.x+r2X-bA.m_sweep.c.x-r1X;var CY=bB.m_sweep.c.y+r2Y-bA.m_sweep.c.y-r1Y;var CLengthSquared=CX*CX+CY*CY;var CLength=Math.sqrt(CLengthSquared);positionError=CLength;var invMass1=bA.m_invMass;var invMass2=bB.m_invMass;var invI1=bA.m_invI;var invI2=bB.m_invI;var k_allowedStretch=10*Box2D.Common.b2Settings.b2_linearSlop;if(CLengthSquared&gt;k_allowedStretch*k_allowedStretch){var uX=CX/CLength;var uY=CY/CLength;var k=invMass1+invMass2;var m=1/k;impulseX=m*-CX;impulseY=m*-CY;var k_beta=.5;bA.m_sweep.c.x-=k_beta*invMass1*impulseX;bA.m_sweep.c.y-=k_beta*invMass1*impulseY;bB.m_sweep.c.x+=k_beta*invMass2*impulseX;bB.m_sweep.c.y+=k_beta*invMass2*impulseY;CX=bB.m_sweep.c.x+r2X-bA.m_sweep.c.x-r1X;CY=bB.m_sweep.c.y+r2Y-bA.m_sweep.c.y-r1Y}this.K1.col1.x=invMass1+invMass2;this.K1.col2.x=0;this.K1.col1.y=0;this.K1.col2.y=invMass1+invMass2;this.K2.col1.x=invI1*r1Y*r1Y;this.K2.col2.x=-invI1*r1X*r1Y;this.K2.col1.y=-invI1*r1X*r1Y;this.K2.col2.y=invI1*r1X*r1X;this.K3.col1.x=invI2*r2Y*r2Y;this.K3.col2.x=-invI2*r2X*r2Y;this.K3.col1.y=-invI2*r2X*r2Y;this.K3.col2.y=invI2*r2X*r2X;this.K.SetM(this.K1);this.K.AddM(this.K2);this.K.AddM(this.K3);this.K.Solve(Box2D.Dynamics.Joints.b2RevoluteJoint.tImpulse,-CX,-CY);impulseX=Box2D.Dynamics.Joints.b2RevoluteJoint.tImpulse.x;impulseY=Box2D.Dynamics.Joints.b2RevoluteJoint.tImpulse.y;bA.m_sweep.c.x-=bA.m_invMass*impulseX;bA.m_sweep.c.y-=bA.m_invMass*impulseY;bA.m_sweep.a-=bA.m_invI*(r1X*impulseY-r1Y*impulseX);bB.m_sweep.c.x+=bB.m_invMass*impulseX;bB.m_sweep.c.y+=bB.m_invMass*impulseY;bB.m_sweep.a+=bB.m_invI*(r2X*impulseY-r2Y*impulseX);bA.SynchronizeTransform();bB.SynchronizeTransform();return positionError&lt;=Box2D.Common.b2Settings.b2_linearSlop&amp;&amp;angularError&lt;=Box2D.Common.b2Settings.b2_angularSlop};Box2D.Dynamics.Joints.b2RevoluteJoint.tImpulse=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Dynamics.Joints.b2RevoluteJointDef=function(){Box2D.Dynamics.Joints.b2JointDef.call(this);this.localAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.type=Box2D.Dynamics.Joints.b2Joint.e_revoluteJoint;this.localAnchorA.SetZero();this.localAnchorB.SetZero();this.referenceAngle=0;this.lowerAngle=0;this.upperAngle=0;this.maxMotorTorque=0;this.motorSpeed=0;this.enableLimit=false;this.enableMotor=false};Box2D.inherits(Box2D.Dynamics.Joints.b2RevoluteJointDef,Box2D.Dynamics.Joints.b2JointDef);Box2D.Dynamics.Joints.b2RevoluteJointDef.prototype.Initialize=function(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.localAnchorA=this.bodyA.GetLocalPoint(anchor);this.localAnchorB=this.bodyB.GetLocalPoint(anchor);this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle()};Box2D.Dynamics.Joints.b2RevoluteJointDef.prototype.Create=function(){return new Box2D.Dynamics.Joints.b2RevoluteJoint(this)};Box2D.Dynamics.Joints.b2WeldJoint=function(def){Box2D.Dynamics.Joints.b2Joint.call(this,def);this.m_localAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_impulse=Box2D.Common.Math.b2Vec3.Get(0,0,0);this.m_mass=new Box2D.Common.Math.b2Mat33;this.m_localAnchorA.SetV(def.localAnchorA);this.m_localAnchorB.SetV(def.localAnchorB);this.m_referenceAngle=def.referenceAngle};Box2D.inherits(Box2D.Dynamics.Joints.b2WeldJoint,Box2D.Dynamics.Joints.b2Joint);Box2D.Dynamics.Joints.b2WeldJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA)};Box2D.Dynamics.Joints.b2WeldJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB)};Box2D.Dynamics.Joints.b2WeldJoint.prototype.GetReactionForce=function(inv_dt){return Box2D.Common.Math.b2Vec2.Get(inv_dt*this.m_impulse.x,inv_dt*this.m_impulse.y)};Box2D.Dynamics.Joints.b2WeldJoint.prototype.GetReactionTorque=function(inv_dt){return inv_dt*this.m_impulse.z};Box2D.Dynamics.Joints.b2WeldJoint.prototype.InitVelocityConstraints=function(step){var tMat;var tX=0;var bA=this.m_bodyA;var bB=this.m_bodyB;tMat=bA.m_xf.R;var rAX=this.m_localAnchorA.x-bA.m_sweep.localCenter.x;var rAY=this.m_localAnchorA.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*rAX+tMat.col2.x*rAY;rAY=tMat.col1.y*rAX+tMat.col2.y*rAY;rAX=tX;tMat=bB.m_xf.R;var rBX=this.m_localAnchorB.x-bB.m_sweep.localCenter.x;var rBY=this.m_localAnchorB.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*rBX+tMat.col2.x*rBY;rBY=tMat.col1.y*rBX+tMat.col2.y*rBY;rBX=tX;var mA=bA.m_invMass;var mB=bB.m_invMass;var iA=bA.m_invI;var iB=bB.m_invI;this.m_mass.col1.x=mA+mB+rAY*rAY*iA+rBY*rBY*iB;this.m_mass.col2.x=-rAY*rAX*iA-rBY*rBX*iB;this.m_mass.col3.x=-rAY*iA-rBY*iB;this.m_mass.col1.y=this.m_mass.col2.x;this.m_mass.col2.y=mA+mB+rAX*rAX*iA+rBX*rBX*iB;this.m_mass.col3.y=rAX*iA+rBX*iB;this.m_mass.col1.z=this.m_mass.col3.x;this.m_mass.col2.z=this.m_mass.col3.y;this.m_mass.col3.z=iA+iB;if(step.warmStarting){this.m_impulse.x*=step.dtRatio;this.m_impulse.y*=step.dtRatio;this.m_impulse.z*=step.dtRatio;bA.m_linearVelocity.x-=mA*this.m_impulse.x;bA.m_linearVelocity.y-=mA*this.m_impulse.y;bA.m_angularVelocity-=iA*(rAX*this.m_impulse.y-rAY*this.m_impulse.x+this.m_impulse.z);bB.m_linearVelocity.x+=mB*this.m_impulse.x;bB.m_linearVelocity.y+=mB*this.m_impulse.y;bB.m_angularVelocity+=iB*(rBX*this.m_impulse.y-rBY*this.m_impulse.x+this.m_impulse.z)}else{this.m_impulse.SetZero()}};Box2D.Dynamics.Joints.b2WeldJoint.prototype.SolveVelocityConstraints=function(step){var tMat;var tX=0;var bA=this.m_bodyA;var bB=this.m_bodyB;var vA=bA.m_linearVelocity;var wA=bA.m_angularVelocity;var vB=bB.m_linearVelocity;var wB=bB.m_angularVelocity;var mA=bA.m_invMass;var mB=bB.m_invMass;var iA=bA.m_invI;var iB=bB.m_invI;tMat=bA.m_xf.R;var rAX=this.m_localAnchorA.x-bA.m_sweep.localCenter.x;var rAY=this.m_localAnchorA.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*rAX+tMat.col2.x*rAY;rAY=tMat.col1.y*rAX+tMat.col2.y*rAY;rAX=tX;tMat=bB.m_xf.R;var rBX=this.m_localAnchorB.x-bB.m_sweep.localCenter.x;var rBY=this.m_localAnchorB.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*rBX+tMat.col2.x*rBY;rBY=tMat.col1.y*rBX+tMat.col2.y*rBY;rBX=tX;var Cdot1X=vB.x-wB*rBY-vA.x+wA*rAY;var Cdot1Y=vB.y+wB*rBX-vA.y-wA*rAX;var Cdot2=wB-wA;var impulse=Box2D.Common.Math.b2Vec3.Get(0,0,0);this.m_mass.Solve33(impulse,-Cdot1X,-Cdot1Y,-Cdot2);this.m_impulse.Add(impulse);vA.x-=mA*impulse.x;vA.y-=mA*impulse.y;wA-=iA*(rAX*impulse.y-rAY*impulse.x+impulse.z);vB.x+=mB*impulse.x;vB.y+=mB*impulse.y;wB+=iB*(rBX*impulse.y-rBY*impulse.x+impulse.z);Box2D.Common.Math.b2Vec3.Free(impulse);bA.m_angularVelocity=wA;bB.m_angularVelocity=wB};Box2D.Dynamics.Joints.b2WeldJoint.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;var tMat;var tX=0;var bA=this.m_bodyA;var bB=this.m_bodyB;tMat=bA.m_xf.R;var rAX=this.m_localAnchorA.x-bA.m_sweep.localCenter.x;var rAY=this.m_localAnchorA.y-bA.m_sweep.localCenter.y;tX=tMat.col1.x*rAX+tMat.col2.x*rAY;rAY=tMat.col1.y*rAX+tMat.col2.y*rAY;rAX=tX;tMat=bB.m_xf.R;var rBX=this.m_localAnchorB.x-bB.m_sweep.localCenter.x;var rBY=this.m_localAnchorB.y-bB.m_sweep.localCenter.y;tX=tMat.col1.x*rBX+tMat.col2.x*rBY;rBY=tMat.col1.y*rBX+tMat.col2.y*rBY;rBX=tX;var mA=bA.m_invMass;var mB=bB.m_invMass;var iA=bA.m_invI;var iB=bB.m_invI;var C1X=bB.m_sweep.c.x+rBX-bA.m_sweep.c.x-rAX;var C1Y=bB.m_sweep.c.y+rBY-bA.m_sweep.c.y-rAY;var C2=bB.m_sweep.a-bA.m_sweep.a-this.m_referenceAngle;var k_allowedStretch=10*Box2D.Common.b2Settings.b2_linearSlop;var positionError=Math.sqrt(C1X*C1X+C1Y*C1Y);var angularError=Math.abs(C2);if(positionError&gt;k_allowedStretch){iA*=1;iB*=1}this.m_mass.col1.x=mA+mB+rAY*rAY*iA+rBY*rBY*iB;this.m_mass.col2.x=-rAY*rAX*iA-rBY*rBX*iB;this.m_mass.col3.x=-rAY*iA-rBY*iB;this.m_mass.col1.y=this.m_mass.col2.x;this.m_mass.col2.y=mA+mB+rAX*rAX*iA+rBX*rBX*iB;this.m_mass.col3.y=rAX*iA+rBX*iB;this.m_mass.col1.z=this.m_mass.col3.x;this.m_mass.col2.z=this.m_mass.col3.y;this.m_mass.col3.z=iA+iB;var impulse=Box2D.Common.Math.b2Vec3.Get(0,0,0);this.m_mass.Solve33(impulse,-C1X,-C1Y,-C2);bA.m_sweep.c.x-=mA*impulse.x;bA.m_sweep.c.y-=mA*impulse.y;bA.m_sweep.a-=iA*(rAX*impulse.y-rAY*impulse.x+impulse.z);bB.m_sweep.c.x+=mB*impulse.x;bB.m_sweep.c.y+=mB*impulse.y;bB.m_sweep.a+=iB*(rBX*impulse.y-rBY*impulse.x+impulse.z);Box2D.Common.Math.b2Vec3.Free(impulse);bA.SynchronizeTransform();bB.SynchronizeTransform();return positionError&lt;=Box2D.Common.b2Settings.b2_linearSlop&amp;&amp;angularError&lt;=Box2D.Common.b2Settings.b2_angularSlop};Box2D.Dynamics.Joints.b2WeldJointDef=function(){Box2D.Dynamics.Joints.b2JointDef.call(this);this.localAnchorA=Box2D.Common.Math.b2Vec2.Get(0,0);this.localAnchorB=Box2D.Common.Math.b2Vec2.Get(0,0);this.type=Box2D.Dynamics.Joints.b2Joint.e_weldJoint;this.referenceAngle=0};Box2D.inherits(Box2D.Dynamics.Joints.b2WeldJointDef,Box2D.Dynamics.Joints.b2JointDef);Box2D.Dynamics.Joints.b2WeldJointDef.prototype.Initialize=function(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.localAnchorA.SetV(this.bodyA.GetLocalPoint(anchor));this.localAnchorB.SetV(this.bodyB.GetLocalPoint(anchor));this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle()};Box2D.Dynamics.Joints.b2WeldJointDef.prototype.Create=function(){return new Box2D.Dynamics.Joints.b2WeldJoint(this)};Box2D.Dynamics.Contacts.b2PositionSolverManifold=function(){this.m_normal=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_separations=Box2D.Array.Get();this.m_points=Box2D.Array.Get();for(var i=0;i&lt;Box2D.Common.b2Settings.b2_maxManifoldPoints;i++){this.m_points[i]=Box2D.Common.Math.b2Vec2.Get(0,0)}};Box2D.Dynamics.Contacts.b2PositionSolverManifold.prototype.Initialize=function(cc){switch(cc.type){case Box2D.Collision.b2Manifold.e_circles:this._InitializeCircles(cc);break;case Box2D.Collision.b2Manifold.e_faceA:this._InitializeFaceA(cc);break;case Box2D.Collision.b2Manifold.e_faceB:this._InitializeFaceB(cc);break}};Box2D.Dynamics.Contacts.b2PositionSolverManifold.prototype._InitializeCircles=function(cc){var tMat=cc.bodyA.m_xf.R;var tVec=cc.localPoint;var pointAX=cc.bodyA.m_xf.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var pointAY=cc.bodyA.m_xf.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tMat=cc.bodyB.m_xf.R;tVec=cc.points[0].localPoint;var pointBX=cc.bodyB.m_xf.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var pointBY=cc.bodyB.m_xf.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);var dX=pointBX-pointAX;var dY=pointBY-pointAY;var d2=dX*dX+dY*dY;if(d2&gt;Box2D.Common.b2Settings.MIN_VALUE_SQUARED){var d=Math.sqrt(d2);this.m_normal.x=dX/d;this.m_normal.y=dY/d}else{this.m_normal.x=1;this.m_normal.y=0}this.m_points[0].x=.5*(pointAX+pointBX);this.m_points[0].y=.5*(pointAY+pointBY);this.m_separations[0]=dX*this.m_normal.x+dY*this.m_normal.y-cc.radius};Box2D.Dynamics.Contacts.b2PositionSolverManifold.prototype._InitializeFaceA=function(cc){this.m_normal.x=cc.bodyA.m_xf.R.col1.x*cc.localPlaneNormal.x+cc.bodyA.m_xf.R.col2.x*cc.localPlaneNormal.y;this.m_normal.y=cc.bodyA.m_xf.R.col1.y*cc.localPlaneNormal.x+cc.bodyA.m_xf.R.col2.y*cc.localPlaneNormal.y;var planePointX=cc.bodyA.m_xf.position.x+(cc.bodyA.m_xf.R.col1.x*cc.localPoint.x+cc.bodyA.m_xf.R.col2.x*cc.localPoint.y);var planePointY=cc.bodyA.m_xf.position.y+(cc.bodyA.m_xf.R.col1.y*cc.localPoint.x+cc.bodyA.m_xf.R.col2.y*cc.localPoint.y);for(var i=0;i&lt;cc.pointCount;i++){var clipPointX=cc.bodyB.m_xf.position.x+(cc.bodyB.m_xf.R.col1.x*cc.points[i].localPoint.x+cc.bodyB.m_xf.R.col2.x*cc.points[i].localPoint.y);var clipPointY=cc.bodyB.m_xf.position.y+(cc.bodyB.m_xf.R.col1.y*cc.points[i].localPoint.x+cc.bodyB.m_xf.R.col2.y*cc.points[i].localPoint.y);this.m_separations[i]=(clipPointX-planePointX)*this.m_normal.x+(clipPointY-planePointY)*this.m_normal.y-cc.radius;this.m_points[i].x=clipPointX;this.m_points[i].y=clipPointY}};Box2D.Dynamics.Contacts.b2PositionSolverManifold.prototype._InitializeFaceB=function(cc){this.m_normal.x=cc.bodyB.m_xf.R.col1.x*cc.localPlaneNormal.x+cc.bodyB.m_xf.R.col2.x*cc.localPlaneNormal.y;this.m_normal.y=cc.bodyB.m_xf.R.col1.y*cc.localPlaneNormal.x+cc.bodyB.m_xf.R.col2.y*cc.localPlaneNormal.y;var planePointX=cc.bodyB.m_xf.position.x+(cc.bodyB.m_xf.R.col1.x*cc.localPoint.x+cc.bodyB.m_xf.R.col2.x*cc.localPoint.y);var planePointY=cc.bodyB.m_xf.position.y+(cc.bodyB.m_xf.R.col1.y*cc.localPoint.x+cc.bodyB.m_xf.R.col2.y*cc.localPoint.y);for(var i=0;i&lt;cc.pointCount;i++){var clipPointX=cc.bodyA.m_xf.position.x+(cc.bodyA.m_xf.R.col1.x*cc.points[i].localPoint.x+cc.bodyA.m_xf.R.col2.x*cc.points[i].localPoint.y);var clipPointY=cc.bodyA.m_xf.position.y+(cc.bodyA.m_xf.R.col1.y*cc.points[i].localPoint.x+cc.bodyA.m_xf.R.col2.y*cc.points[i].localPoint.y);this.m_separations[i]=(clipPointX-planePointX)*this.m_normal.x+(clipPointY-planePointY)*this.m_normal.y-cc.radius;this.m_points[i].Set(clipPointX,clipPointY)}this.m_normal.x*=-1;this.m_normal.y*=-1};Box2D.Dynamics.Controllers.b2Controller=function(){this.ID=Box2D.Dynamics.Controllers.b2Controller.NEXT_ID++;this.m_world=null;this.bodyList=new Box2D.Dynamics.b2BodyList};Box2D.Dynamics.Controllers.b2Controller.prototype.Step=function(step){};Box2D.Dynamics.Controllers.b2Controller.prototype.Draw=function(debugDraw){};Box2D.Dynamics.Controllers.b2Controller.prototype.AddBody=function(body){this.bodyList.AddBody(body);body.AddController(this)};Box2D.Dynamics.Controllers.b2Controller.prototype.RemoveBody=function(body){this.bodyList.RemoveBody(body);body.RemoveController(this)};Box2D.Dynamics.Controllers.b2Controller.prototype.Clear=function(){for(var node=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);node;node=node.GetNextNode()){this.RemoveBody(node.body)}};Box2D.Dynamics.Controllers.b2Controller.prototype.GetBodyList=function(){return this.bodyList};Box2D.Dynamics.Controllers.b2Controller.NEXT_ID=0;Box2D.Dynamics.Controllers.b2BuoyancyController=function(){Box2D.Dynamics.Controllers.b2Controller.call(this);this.normal=Box2D.Common.Math.b2Vec2.Get(0,-1);this.offset=0;this.density=0;this.velocity=Box2D.Common.Math.b2Vec2.Get(0,0);this.linearDrag=2;this.angularDrag=1;this.useDensity=false;this.useWorldGravity=true;this.gravity=null};Box2D.inherits(Box2D.Dynamics.Controllers.b2BuoyancyController,Box2D.Dynamics.Controllers.b2Controller);Box2D.Dynamics.Controllers.b2BuoyancyController.prototype.Step=function(step){if(this.useWorldGravity){this.gravity=this.m_world.GetGravity()}var areac=Box2D.Common.Math.b2Vec2.Get(0,0);var massc=Box2D.Common.Math.b2Vec2.Get(0,0);var sc=Box2D.Common.Math.b2Vec2.Get(0,0);for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.awakeBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){massc.Set(0,0);areac.Set(0,0);var body=bodyNode.body;var area=0;var mass=0;for(var fixtureNode=body.GetFixtureList().GetFirstNode();fixtureNode;fixtureNode=fixtureNode.GetNextNode()){sc.Set(0,0);var sarea=fixtureNode.fixture.GetShape().ComputeSubmergedArea(this.normal,this.offset,body.GetTransform(),sc);area+=sarea;areac.x+=sarea*sc.x;areac.y+=sarea*sc.y;var shapeDensity=0;if(this.useDensity){shapeDensity=1}else{shapeDensity=1}mass+=sarea*shapeDensity;massc.x+=sarea*sc.x*shapeDensity;massc.y+=sarea*sc.y*shapeDensity}if(area&lt;Number.MIN_VALUE){continue}areac.x/=area;areac.y/=area;massc.x/=mass;massc.y/=mass;var buoyancyForce=this.gravity.GetNegative();buoyancyForce.Multiply(this.density*area);body.ApplyForce(buoyancyForce,massc);Box2D.Common.Math.b2Vec2.Free(buoyancyForce);var dragForce=body.GetLinearVelocityFromWorldPoint(areac);dragForce.Subtract(this.velocity);dragForce.Multiply(-this.linearDrag*area);body.ApplyForce(dragForce,areac);Box2D.Common.Math.b2Vec2.Free(dragForce);body.ApplyTorque(-body.GetInertia()/body.GetMass()*area*body.GetAngularVelocity()*this.angularDrag)}Box2D.Common.Math.b2Vec2.Free(sc);Box2D.Common.Math.b2Vec2.Free(massc);Box2D.Common.Math.b2Vec2.Free(areac)};Box2D.Dynamics.Controllers.b2BuoyancyController.prototype.Draw=function(debugDraw){var r=1e3;var p1=Box2D.Common.Math.b2Vec2.Get(this.normal.x*this.offset+this.normal.y*r,this.normal.y*this.offset-this.normal.x*r);var p2=Box2D.Common.Math.b2Vec2.Get(this.normal.x*this.offset-this.normal.y*r,this.normal.y*this.offset+this.normal.x*r);debugDraw.DrawSegment(p1,p2,Box2D.Dynamics.Controllers.b2BuoyancyController.color);Box2D.Common.Math.b2Vec2.Free(p1);Box2D.Common.Math.b2Vec2.Free(p2)};Box2D.Dynamics.Controllers.b2BuoyancyController.color=new Box2D.Common.b2Color(0,0,1);Box2D.Dynamics.Controllers.b2ConstantAccelController=function(){Box2D.Dynamics.Controllers.b2Controller.call(this);this.A=Box2D.Common.Math.b2Vec2.Get(0,0)};Box2D.inherits(Box2D.Dynamics.Controllers.b2ConstantAccelController,Box2D.Dynamics.Controllers.b2Controller);Box2D.Dynamics.Controllers.b2ConstantAccelController.prototype.Step=function(step){var smallA=Box2D.Common.Math.b2Vec2.Get(this.A.x*step.dt,this.A.y*step.dt);for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.awakeBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){var body=bodyNode.body;var oldVelocity=body.GetLinearVelocity();var newVelocity=Box2D.Common.Math.b2Vec2.Get(oldVelocity.x+smallA.x,oldVelocity.y+smallA.y);body.SetLinearVelocity(newVelocity);Box2D.Common.Math.b2Vec2.Free(newVelocity)}Box2D.Common.Math.b2Vec2.Free(smallA)};Box2D.Dynamics.Controllers.b2ConstantForceController=function(){Box2D.Dynamics.Controllers.b2Controller.call(this);this.F=Box2D.Common.Math.b2Vec2.Get(0,0)};Box2D.inherits(Box2D.Dynamics.Controllers.b2ConstantForceController,Box2D.Dynamics.Controllers.b2Controller);Box2D.Dynamics.Controllers.b2ConstantForceController.prototype.Step=function(step){for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.awakeBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){var body=bodyNode.body;body.ApplyForce(this.F,body.GetWorldCenter())}};Box2D.Dynamics.Controllers.b2ControllerList=function(){this.controllerFirstNode=null;this.controllerLastNode=null;this.controllerNodeLookup={};this.controllerCount=0};Box2D.Dynamics.Controllers.b2ControllerList.prototype.GetFirstNode=function(){return this.controllerFirstNode};Box2D.Dynamics.Controllers.b2ControllerList.prototype.AddController=function(controller){var controllerID=controller.ID;if(this.controllerNodeLookup[controllerID]==null){var node=new Box2D.Dynamics.Controllers.b2ControllerListNode(controller);var prevNode=this.controllerLastNode;if(prevNode!=null){prevNode.SetNextNode(node)}else{this.controllerFirstNode=node}node.SetPreviousNode(prevNode);this.controllerLastNode=node;this.controllerNodeLookup[controllerID]=node;this.controllerCount++}};Box2D.Dynamics.Controllers.b2ControllerList.prototype.RemoveController=function(controller){var controllerID=controller.ID;var node=this.controllerNodeLookup[controllerID];if(node==null){return}var prevNode=node.GetPreviousNode();var nextNode=node.GetNextNode();if(prevNode==null){this.controllerFirstNode=nextNode}else{prevNode.SetNextNode(nextNode)}if(nextNode==null){this.controllerLastNode=prevNode}else{nextNode.SetPreviousNode(prevNode)}delete this.controllerNodeLookup[controllerID];this.controllerCount--};Box2D.Dynamics.Controllers.b2ControllerList.prototype.GetControllerCount=function(){return this.controllerCount};Box2D.Dynamics.Controllers.b2ControllerListNode=function(controller){this.controller=controller;this.next=null;this.previous=null};Box2D.Dynamics.Controllers.b2ControllerListNode.prototype.SetNextNode=function(node){this.next=node};Box2D.Dynamics.Controllers.b2ControllerListNode.prototype.SetPreviousNode=function(node){this.previous=node};Box2D.Dynamics.Controllers.b2ControllerListNode.prototype.GetNextNode=function(){return this.next};Box2D.Dynamics.Controllers.b2ControllerListNode.prototype.GetPreviousNode=function(){return this.previous};Box2D.Dynamics.Controllers.b2GravityController=function(){Box2D.Dynamics.Controllers.b2Controller.call(this);this.G=1;this.invSqr=true};Box2D.inherits(Box2D.Dynamics.Controllers.b2GravityController,Box2D.Dynamics.Controllers.b2Controller);Box2D.Dynamics.Controllers.b2GravityController.prototype.Step=function(step){var i=null;var body1=null;var p1=null;var mass1=0;var j=null;var body2=null;var p2=null;var dx=0;var dy=0;var r2=0;var f=null;if(this.invSqr){for(var body1Node=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);body1Node;body1Node=body1Node.GetNextNode()){var body1=body1Node.body;var p1=body1.GetWorldCenter();var mass1=body1.GetMass();for(var body2Node=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);body2Node;body2Node=body2Node.GetNextNode()){var body2=body2Node.body;if(!body1.IsAwake()&amp;&amp;!body2.IsAwake()){continue}var p2=body2.GetWorldCenter();var dx=p2.x-p1.x;var dy=p2.y-p1.y;var r2=dx*dx+dy*dy;if(r2&lt;Number.MIN_VALUE){continue}var f=Box2D.Common.Math.b2Vec2.Get(dx,dy);f.Multiply(this.G/r2/Math.sqrt(r2)*mass1*body2.GetMass());if(body1.IsAwake()){body1.ApplyForce(f,p1)}f.Multiply(-1);if(body2.IsAwake()){body2.ApplyForce(f,p2)}Box2D.Common.Math.b2Vec2.Free(f)}}}else{for(var body1Node=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);body1Node;body1Node=body1Node.GetNextNode()){var body1=bodyNode.body;var p1=body1.GetWorldCenter();var mass1=body1.GetMass();for(var body2Node=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);body2Node;body2Node=body2Node.GetNextNode()){var body2=bodyNode.body;if(!body1.IsAwake()&amp;&amp;!body2.IsAwake()){continue}var p2=body2.GetWorldCenter();var dx=p2.x-p1.x;var dy=p2.y-p1.y;var r2=dx*dx+dy*dy;if(r2&lt;Number.MIN_VALUE){continue}var f=Box2D.Common.Math.b2Vec2.Get(dx,dy);f.Multiply(this.G/r2*mass1*body2.GetMass());if(body1.IsAwake()){body1.ApplyForce(f,p1)}f.Multiply(-1);if(body2.IsAwake()){body2.ApplyForce(f,p2)}Box2D.Common.Math.b2Vec2.Free(f)}}}};Box2D.Dynamics.Controllers.b2TensorDampingController=function(){Box2D.Dynamics.Controllers.b2Controller.call(this);this.T=Box2D.Common.Math.b2Mat22.Get();this.maxTimestep=0};Box2D.inherits(Box2D.Dynamics.Controllers.b2TensorDampingController,Box2D.Dynamics.Controllers.b2Controller);Box2D.Dynamics.Controllers.b2TensorDampingController.prototype.SetAxisAligned=function(xDamping,yDamping){this.T.col1.x=-xDamping;this.T.col1.y=0;this.T.col2.x=0;this.T.col2.y=-yDamping;if(xDamping&gt;0||yDamping&gt;0){this.maxTimestep=1/Math.max(xDamping,yDamping)}else{this.maxTimestep=0}};Box2D.Dynamics.Controllers.b2TensorDampingController.prototype.Step=function(step){var timestep=step.dt;if(timestep&lt;=Number.MIN_VALUE)return;if(timestep&gt;this.maxTimestep&amp;&amp;this.maxTimestep&gt;0)timestep=this.maxTimestep;for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.awakeBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){var body=bodyNode.body;var lV=body.GetLocalVector(body.GetLinearVelocity());var tV=Box2D.Common.Math.b2Math.MulMV(this.T,lV);Box2D.Common.Math.b2Vec2.Free(lV);var damping=body.GetWorldVector(tV);Box2D.Common.Math.b2Vec2.Free(tV);var newV=Box2D.Common.Math.b2Vec2.Get(body.GetLinearVelocity().x+damping.x*timestep,body.GetLinearVelocity().y+damping.y*timestep);Box2D.Common.Math.b2Vec2.Free(damping);body.SetLinearVelocity(newV);Box2D.Common.Math.b2Vec2.Free(newV)}};Box2D.Collision.ClipVertex=function(){this.v=Box2D.Common.Math.b2Vec2.Get(0,0);this.id=new Box2D.Collision.b2ContactID};Box2D.Collision.ClipVertex.prototype.Set=function(other){this.v.SetV(other.v);this.id.Set(other.id)};Box2D.Collision.IBroadPhase="Box2D.Collision.IBroadPhase";Box2D.Collision.b2ContactID=function(){this._key=0;this._referenceEdge=0;this._incidentEdge=0;this._incidentVertex=0};Box2D.Collision.b2ContactID.prototype.GetKey=function(){return this._key};Box2D.Collision.b2ContactID.prototype.SetKey=function(key){this._key=key;this._referenceEdge=this._key&amp;255;this._incidentEdge=(this._key&amp;65280)&gt;&gt;8&amp;255;this._incidentVertex=(this._key&amp;16711680)&gt;&gt;16&amp;255;this._flip=(this._key&amp;4278190080)&gt;&gt;24&amp;255};Box2D.Collision.b2ContactID.prototype.Set=function(id){this.SetKey(id._key)};Box2D.Collision.b2ContactID.prototype.SetReferenceEdge=function(edge){this._referenceEdge=edge;this._key=this._key&amp;4294967040|this._referenceEdge&amp;255};Box2D.Collision.b2ContactID.prototype.SetIncidentEdge=function(edge){this._incidentEdge=edge;this._key=this._key&amp;4294902015|this._incidentEdge&lt;&lt;8&amp;65280};Box2D.Collision.b2ContactID.prototype.SetIncidentVertex=function(vertex){this._incidentVertex=vertex;this._key=this._key&amp;4278255615|this._incidentVertex&lt;&lt;16&amp;16711680};Box2D.Collision.b2ContactID.prototype.SetFlip=function(flip){this._flip=flip;this._key=this._key&amp;16777215|this._flip&lt;&lt;24&amp;4278190080};Box2D.Collision.b2ContactID.prototype.Copy=function(){var id=new Box2D.Collision.b2ContactID;id.Set(this);return id};Box2D.Collision.b2ContactPoint=function(){this.position=Box2D.Common.Math.b2Vec2.Get(0,0);this.velocity=Box2D.Common.Math.b2Vec2.Get(0,0);this.normal=Box2D.Common.Math.b2Vec2.Get(0,0);this.id=new Box2D.Collision.b2ContactID};Box2D.Collision.b2Collision={};Box2D.Collision.b2Collision.s_maxSeparationA={};Box2D.Collision.b2Collision.s_maxSeparationB={};Box2D.Collision.b2Collision.ClipSegmentToLine=function(vOut,vIn,normal,offset){var numOut=0;var vIn0=vIn[0].v;var vIn1=vIn[1].v;var distance0=normal.x*vIn0.x+normal.y*vIn0.y-offset;var distance1=normal.x*vIn1.x+normal.y*vIn1.y-offset;if(distance0&lt;=0){vOut[numOut++].Set(vIn[0])}if(distance1&lt;=0){vOut[numOut++].Set(vIn[1])}if(distance0*distance1&lt;0){var interp=distance0/(distance0-distance1);var tVec=vOut[numOut].v;tVec.x=vIn0.x+interp*(vIn1.x-vIn0.x);tVec.y=vIn0.y+interp*(vIn1.y-vIn0.y);if(distance0&gt;0){vOut[numOut].id=vIn[0].id}else{vOut[numOut].id=vIn[1].id}numOut++}return numOut};Box2D.Collision.b2Collision.EdgeSeparation=function(poly1,xf1,edge1,poly2,xf2){var normal1WorldX=xf1.R.col1.x*poly1.GetNormal(edge1).x+xf1.R.col2.x*poly1.GetNormal(edge1).y;var normal1WorldY=xf1.R.col1.y*poly1.GetNormal(edge1).x+xf1.R.col2.y*poly1.GetNormal(edge1).y;var normal1X=xf2.R.col1.x*normal1WorldX+xf2.R.col1.y*normal1WorldY;var normal1Y=xf2.R.col2.x*normal1WorldX+xf2.R.col2.y*normal1WorldY;var index=0;var minDot=Number.MAX_VALUE;for(var i=0;i&lt;poly2.m_vertexCount;i++){var dot=poly2.GetVertex(i).x*normal1X+poly2.GetVertex(i).y*normal1Y;if(dot&lt;minDot){minDot=dot;index=i}}var v1X=xf1.position.x+(xf1.R.col1.x*poly1.GetVertex(edge1).x+xf1.R.col2.x*poly1.GetVertex(edge1).y);var v1Y=xf1.position.y+(xf1.R.col1.y*poly1.GetVertex(edge1).x+xf1.R.col2.y*poly1.GetVertex(edge1).y);var v2X=xf2.position.x+(xf2.R.col1.x*poly2.GetVertex(index).x+xf2.R.col2.x*poly2.GetVertex(index).y);var v2Y=xf2.position.y+(xf2.R.col1.y*poly2.GetVertex(index).x+xf2.R.col2.y*poly2.GetVertex(index).y);var separation=(v2X-v1X)*normal1WorldX+(v2Y-v1Y)*normal1WorldY;return separation};Box2D.Collision.b2Collision.FindMaxSeparation=function(poly1,xf1,poly2,xf2,result){var dX=xf2.position.x+(xf2.R.col1.x*poly2.GetCentroid().x+xf2.R.col2.x*poly2.GetCentroid().y);var dY=xf2.position.y+(xf2.R.col1.y*poly2.GetCentroid().x+xf2.R.col2.y*poly2.GetCentroid().y);dX-=xf1.position.x+(xf1.R.col1.x*poly1.GetCentroid().x+xf1.R.col2.x*poly1.GetCentroid().y);dY-=xf1.position.y+(xf1.R.col1.y*poly1.GetCentroid().x+xf1.R.col2.y*poly1.GetCentroid().y);var dLocal1X=dX*xf1.R.col1.x+dY*xf1.R.col1.y;var dLocal1Y=dX*xf1.R.col2.x+dY*xf1.R.col2.y;var edge=0;var maxDot=-Number.MAX_VALUE;for(var i=0;i&lt;poly1.m_vertexCount;++i){var dot=poly1.GetNormal(i).x*dLocal1X+poly1.GetNormal(i).y*dLocal1Y;if(dot&gt;maxDot){maxDot=dot;edge=i}}var s=Box2D.Collision.b2Collision.EdgeSeparation(poly1,xf1,edge,poly2,xf2);var prevEdge=edge-1;if(prevEdge&lt;0){prevEdge=poly1.m_vertexCount-1}var sPrev=Box2D.Collision.b2Collision.EdgeSeparation(poly1,xf1,prevEdge,poly2,xf2);var nextEdge=edge+1;if(nextEdge&gt;=poly1.m_vertexCount){nextEdge=0}var sNext=Box2D.Collision.b2Collision.EdgeSeparation(poly1,xf1,nextEdge,poly2,xf2);var bestEdge=0;var bestSeparation=0;if(sPrev&gt;s&amp;&amp;sPrev&gt;sNext){bestEdge=prevEdge;bestSeparation=sPrev;while(true){edge=bestEdge-1;if(edge&lt;0){edge=poly1.m_vertexCount-1}s=Box2D.Collision.b2Collision.EdgeSeparation(poly1,xf1,edge,poly2,xf2);if(s&gt;bestSeparation){bestEdge=edge;bestSeparation=s}else{break}}}else if(sNext&gt;s){bestEdge=nextEdge;bestSeparation=sNext;while(true){edge=bestEdge+1;if(edge&gt;=poly1.m_vertexCount){edge=0}s=Box2D.Collision.b2Collision.EdgeSeparation(poly1,xf1,edge,poly2,xf2);if(s&gt;bestSeparation){bestEdge=edge;bestSeparation=s}else{break}}}else{bestEdge=edge;bestSeparation=s}result.bestEdge=bestEdge;result.separation=bestSeparation;return result};Box2D.Collision.b2Collision.FindIncidentEdge=function(c,poly1,xf1,edge1,poly2,xf2){var normal1X=xf1.R.col1.x*poly1.GetNormal(edge1).x+xf1.R.col2.x*poly1.GetNormal(edge1).y;var normal1Y=xf1.R.col1.y*poly1.GetNormal(edge1).x+xf1.R.col2.y*poly1.GetNormal(edge1).y;var tX=xf2.R.col1.x*normal1X+xf2.R.col1.y*normal1Y;normal1Y=xf2.R.col2.x*normal1X+xf2.R.col2.y*normal1Y;normal1X=tX;var i1=0;var minDot=Number.MAX_VALUE;for(var i=0;i&lt;poly2.m_vertexCount;i++){var dot=normal1X*poly2.GetNormal(i).x+normal1Y*poly2.GetNormal(i).y;if(dot&lt;minDot){minDot=dot;i1=i}}var i2=i1+1;if(i2&gt;=poly2.m_vertexCount){i2=0}c[0].v.x=xf2.position.x+(xf2.R.col1.x*poly2.GetVertex(i1).x+xf2.R.col2.x*poly2.GetVertex(i1).y);c[0].v.y=xf2.position.y+(xf2.R.col1.y*poly2.GetVertex(i1).x+xf2.R.col2.y*poly2.GetVertex(i1).y);c[0].id.SetReferenceEdge(edge1);c[0].id.SetIncidentEdge(i1);c[0].id.SetIncidentVertex(0);c[1].v.x=xf2.position.x+(xf2.R.col1.x*poly2.GetVertex(i2).x+xf2.R.col2.x*poly2.GetVertex(i2).y);c[1].v.y=xf2.position.y+(xf2.R.col1.y*poly2.GetVertex(i2).x+xf2.R.col2.y*poly2.GetVertex(i2).y);c[1].id.SetReferenceEdge(edge1);c[1].id.SetIncidentEdge(i2);c[1].id.SetIncidentVertex(1)};Box2D.Collision.b2Collision.MakeClipPointVector=function(){return[new Box2D.Collision.ClipVertex,new Box2D.Collision.ClipVertex]};Box2D.Collision.b2Collision.CollidePolygons=function(manifold,polyA,xfA,polyB,xfB){manifold.SetPointCount(0);var totalRadius=polyA.GetRadius()+polyB.GetRadius();var separationEdgeA=Box2D.Collision.b2Collision.FindMaxSeparation(polyA,xfA,polyB,xfB,Box2D.Collision.b2Collision.s_maxSeparationA);if(separationEdgeA.separation&gt;totalRadius){return}var separationEdgeB=Box2D.Collision.b2Collision.FindMaxSeparation(polyB,xfB,polyA,xfA,Box2D.Collision.b2Collision.s_maxSeparationB);if(separationEdgeB.separation&gt;totalRadius){return}var poly1=polyA;var poly2=polyB;var xf1=xfA;var xf2=xfB;var flip=0;var edge1=separationEdgeA.bestEdge;manifold.SetType(Box2D.Collision.b2Manifold.e_faceA);if(separationEdgeB.separation&gt;.98*separationEdgeA.separation+.001){poly1=polyB;poly2=polyA;xf1=xfB;xf2=xfA;edge1=separationEdgeB.bestEdge;manifold.SetType(Box2D.Collision.b2Manifold.e_faceB);flip=1}var incidentEdge=Box2D.Collision.b2Collision.s_incidentEdge;Box2D.Collision.b2Collision.FindIncidentEdge(incidentEdge,poly1,xf1,edge1,poly2,xf2);var local_v11=poly1.GetVertex(edge1);var local_v12;if(edge1+1&lt;poly1.m_vertexCount){local_v12=poly1.GetVertex(edge1+1)}else{local_v12=poly1.GetVertex(0)}Box2D.Collision.b2Collision.s_localTangent.Set(local_v12.x-local_v11.x,local_v12.y-local_v11.y);Box2D.Collision.b2Collision.s_localTangent.Normalize();Box2D.Collision.b2Collision.s_localNormal.x=Box2D.Collision.b2Collision.s_localTangent.y;Box2D.Collision.b2Collision.s_localNormal.y=-Box2D.Collision.b2Collision.s_localTangent.x;Box2D.Collision.b2Collision.s_planePoint.Set(.5*(local_v11.x+local_v12.x),.5*(local_v11.y+local_v12.y));Box2D.Collision.b2Collision.s_tangent.x=xf1.R.col1.x*Box2D.Collision.b2Collision.s_localTangent.x+xf1.R.col2.x*Box2D.Collision.b2Collision.s_localTangent.y;Box2D.Collision.b2Collision.s_tangent.y=xf1.R.col1.y*Box2D.Collision.b2Collision.s_localTangent.x+xf1.R.col2.y*Box2D.Collision.b2Collision.s_localTangent.y;Box2D.Collision.b2Collision.s_tangent2.x=-Box2D.Collision.b2Collision.s_tangent.x;Box2D.Collision.b2Collision.s_tangent2.y=-Box2D.Collision.b2Collision.s_tangent.y;Box2D.Collision.b2Collision.s_normal.x=Box2D.Collision.b2Collision.s_tangent.y;Box2D.Collision.b2Collision.s_normal.y=-Box2D.Collision.b2Collision.s_tangent.x;Box2D.Collision.b2Collision.s_v11.x=xf1.position.x+(xf1.R.col1.x*local_v11.x+xf1.R.col2.x*local_v11.y);Box2D.Collision.b2Collision.s_v11.y=xf1.position.y+(xf1.R.col1.y*local_v11.x+xf1.R.col2.y*local_v11.y);Box2D.Collision.b2Collision.s_v12.x=xf1.position.x+(xf1.R.col1.x*local_v12.x+xf1.R.col2.x*local_v12.y);Box2D.Collision.b2Collision.s_v12.y=xf1.position.y+(xf1.R.col1.y*local_v12.x+xf1.R.col2.y*local_v12.y);var sideOffset1=-Box2D.Collision.b2Collision.s_tangent.x*Box2D.Collision.b2Collision.s_v11.x-Box2D.Collision.b2Collision.s_tangent.y*Box2D.Collision.b2Collision.s_v11.y+totalRadius;if(Box2D.Collision.b2Collision.ClipSegmentToLine(Box2D.Collision.b2Collision.s_clipPoints1,incidentEdge,Box2D.Collision.b2Collision.s_tangent2,sideOffset1)&lt;2){return}var sideOffset2=Box2D.Collision.b2Collision.s_tangent.x*Box2D.Collision.b2Collision.s_v12.x+Box2D.Collision.b2Collision.s_tangent.y*Box2D.Collision.b2Collision.s_v12.y+totalRadius;if(Box2D.Collision.b2Collision.ClipSegmentToLine(Box2D.Collision.b2Collision.s_clipPoints2,Box2D.Collision.b2Collision.s_clipPoints1,Box2D.Collision.b2Collision.s_tangent,sideOffset2)&lt;2){return}manifold.m_localPlaneNormal.SetV(Box2D.Collision.b2Collision.s_localNormal);manifold.m_localPoint.SetV(Box2D.Collision.b2Collision.s_planePoint);var frontOffset=Box2D.Collision.b2Collision.s_normal.x*Box2D.Collision.b2Collision.s_v11.x+Box2D.Collision.b2Collision.s_normal.y*Box2D.Collision.b2Collision.s_v11.y;var pointCount=0;for(var i=0;i&lt;Box2D.Common.b2Settings.b2_maxManifoldPoints;++i){var separation=Box2D.Collision.b2Collision.s_normal.x*Box2D.Collision.b2Collision.s_clipPoints2[i].v.x+Box2D.Collision.b2Collision.s_normal.y*Box2D.Collision.b2Collision.s_clipPoints2[i].v.y-frontOffset;if(separation&lt;=totalRadius){var tX=Box2D.Collision.b2Collision.s_clipPoints2[i].v.x-xf2.position.x;var tY=Box2D.Collision.b2Collision.s_clipPoints2[i].v.y-xf2.position.y;manifold.m_points[pointCount].m_localPoint.x=tX*xf2.R.col1.x+tY*xf2.R.col1.y;manifold.m_points[pointCount].m_localPoint.y=tX*xf2.R.col2.x+tY*xf2.R.col2.y;manifold.m_points[pointCount].m_id.Set(Box2D.Collision.b2Collision.s_clipPoints2[i].id);manifold.m_points[pointCount].m_id.SetFlip(flip);pointCount++}}manifold.SetPointCount(pointCount)};Box2D.Collision.b2Collision.CollideCircles=function(manifold,circle1,xf1,circle2,xf2){manifold.SetPointCount(0);var p1X=xf1.position.x+(xf1.R.col1.x*circle1.GetLocalPosition().x+xf1.R.col2.x*circle1.GetLocalPosition().y);var p1Y=xf1.position.y+(xf1.R.col1.y*circle1.GetLocalPosition().x+xf1.R.col2.y*circle1.GetLocalPosition().y);var p2X=xf2.position.x+(xf2.R.col1.x*circle2.GetLocalPosition().x+xf2.R.col2.x*circle2.GetLocalPosition().y);var p2Y=xf2.position.y+(xf2.R.col1.y*circle2.GetLocalPosition().x+xf2.R.col2.y*circle2.GetLocalPosition().y);var dX=p2X-p1X;var dY=p2Y-p1Y;var distSqr=dX*dX+dY*dY;var radius=circle1.GetRadius()+circle2.GetRadius();if(distSqr&gt;radius*radius){return}manifold.SetType(Box2D.Collision.b2Manifold.e_circles);manifold.m_localPoint.SetV(circle1.GetLocalPosition());manifold.m_localPlaneNormal.SetZero();manifold.SetPointCount(1);manifold.m_points[0].m_localPoint.SetV(circle2.GetLocalPosition());manifold.m_points[0].m_id.SetKey(0)};Box2D.Collision.b2Collision.CollidePolygonAndCircle=function(manifold,polygon,xf1,circle,xf2){manifold.SetPointCount(0);var dX=xf2.position.x+(xf2.R.col1.x*circle.GetLocalPosition().x+xf2.R.col2.x*circle.GetLocalPosition().y)-xf1.position.x;var dY=xf2.position.y+(xf2.R.col1.y*circle.GetLocalPosition().x+xf2.R.col2.y*circle.GetLocalPosition().y)-xf1.position.y;var cLocalX=dX*xf1.R.col1.x+dY*xf1.R.col1.y;var cLocalY=dX*xf1.R.col2.x+dY*xf1.R.col2.y;var normalIndex=0;var separation=-Number.MAX_VALUE;var radius=polygon.GetRadius()+circle.GetRadius();for(var i=0;i&lt;polygon.m_vertexCount;++i){var s=polygon.GetNormal(i).x*(cLocalX-polygon.GetVertex(i).x)+polygon.GetNormal(i).y*(cLocalY-polygon.GetVertex(i).y);if(s&gt;radius){return}if(s&gt;separation){separation=s;normalIndex=i}}var vertIndex2=normalIndex+1;if(vertIndex2&gt;=polygon.m_vertexCount){vertIndex2=0}var v1=polygon.GetVertex(normalIndex);var v2=polygon.GetVertex(vertIndex2);if(separation&lt;Number.MIN_VALUE){manifold.SetPointCount(1);manifold.SetType(Box2D.Collision.b2Manifold.e_faceA);manifold.m_localPlaneNormal.SetV(polygon.GetNormal(normalIndex));manifold.m_localPoint.x=.5*(v1.x+v2.x);manifold.m_localPoint.y=.5*(v1.y+v2.y);manifold.m_points[0].m_localPoint.SetV(circle.GetLocalPosition());manifold.m_points[0].m_id.SetKey(0)}else{var u1=(cLocalX-v1.x)*(v2.x-v1.x)+(cLocalY-v1.y)*(v2.y-v1.y);if(u1&lt;=0){if((cLocalX-v1.x)*(cLocalX-v1.x)+(cLocalY-v1.y)*(cLocalY-v1.y)&gt;radius*radius)return;manifold.SetPointCount(1);manifold.SetType(Box2D.Collision.b2Manifold.e_faceA);manifold.m_localPlaneNormal.x=cLocalX-v1.x;manifold.m_localPlaneNormal.y=cLocalY-v1.y;manifold.m_localPlaneNormal.Normalize();manifold.m_localPoint.SetV(v1);manifold.m_points[0].m_localPoint.SetV(circle.GetLocalPosition());manifold.m_points[0].m_id.SetKey(0)}else{var u2=(cLocalX-v2.x)*(v1.x-v2.x)+(cLocalY-v2.y)*(v1.y-v2.y);if(u2&lt;=0){if((cLocalX-v2.x)*(cLocalX-v2.x)+(cLocalY-v2.y)*(cLocalY-v2.y)&gt;radius*radius)return;manifold.SetPointCount(1);manifold.SetType(Box2D.Collision.b2Manifold.e_faceA);manifold.m_localPlaneNormal.x=cLocalX-v2.x;manifold.m_localPlaneNormal.y=cLocalY-v2.y;manifold.m_localPlaneNormal.Normalize();manifold.m_localPoint.SetV(v2);manifold.m_points[0].m_localPoint.SetV(circle.GetLocalPosition());manifold.m_points[0].m_id.SetKey(0)}else{var faceCenterX=.5*(v1.x+v2.x);var faceCenterY=.5*(v1.y+v2.y);separation=(cLocalX-faceCenterX)*polygon.GetNormal(normalIndex).x+(cLocalY-faceCenterY)*polygon.GetNormal(normalIndex).y;if(separation&gt;radius)return;manifold.SetPointCount(1);manifold.SetType(Box2D.Collision.b2Manifold.e_faceA);manifold.m_localPlaneNormal.x=polygon.GetNormal(normalIndex).x;manifold.m_localPlaneNormal.y=polygon.GetNormal(normalIndex).y;manifold.m_localPlaneNormal.Normalize();manifold.m_localPoint.Set(faceCenterX,faceCenterY);manifold.m_points[0].m_localPoint.SetV(circle.GetLocalPosition());manifold.m_points[0].m_id.SetKey(0)}}}};Box2D.Collision.b2Collision.s_incidentEdge=Box2D.Collision.b2Collision.MakeClipPointVector();Box2D.Collision.b2Collision.s_clipPoints1=Box2D.Collision.b2Collision.MakeClipPointVector();Box2D.Collision.b2Collision.s_clipPoints2=Box2D.Collision.b2Collision.MakeClipPointVector();Box2D.Collision.b2Collision.s_localTangent=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Collision.b2Collision.s_localNormal=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Collision.b2Collision.s_planePoint=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Collision.b2Collision.s_normal=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Collision.b2Collision.s_tangent=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Collision.b2Collision.s_tangent2=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Collision.b2Collision.s_v11=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Collision.b2Collision.s_v12=Box2D.Common.Math.b2Vec2.Get(0,0);Box2D.Collision.b2Distance={};Box2D.Collision.b2Distance.s_save=[];Box2D.Collision.b2Distance.s_saveCapacity=0;var b2Distance_d=b2Vec2Get(0,0);var b2Distance_negD=b2Vec2Get(0,0);var b2Distance_aNegD=b2Vec2Get(0,0);var b2Distance_bD=b2Vec2Get(0,0);var b2Distance_distanceV=b2Vec2Get(0,0);var b2Distance_temp=b2Vec2Get(0,0);Box2D.Collision.b2Distance.Distance=function(output,cache,input){var s_simplex=Box2D.Collision.b2Simplex.Get();s_simplex.ReadCache(cache,input.proxyA,input.transformA,input.proxyB,input.transformB);if(s_simplex.m_count&lt;1||s_simplex.m_count&gt;3){Box2D.Common.b2Settings.b2Assert(false)}var iter=0;while(iter&lt;20){var save=Box2D.Collision.b2Distance.s_save;while(s_simplex.m_count&gt;Box2D.Collision.b2Distance.s_saveCapacity){save.push({});Box2D.Collision.b2Distance.s_saveCapacity++}for(var i=0;i&lt;s_simplex.m_count;i++){save[i].indexA=s_simplex.m_vertices[i].indexA;save[i].indexB=s_simplex.m_vertices[i].indexB}var saveLength=s_simplex.m_count;if(s_simplex.m_count==2){s_simplex.Solve2()}else if(s_simplex.m_count==3){s_simplex.Solve3()}if(s_simplex.m_count==3){break}s_simplex.GetSearchDirectionInPlace(b2Distance_d);if(b2Distance_d.LengthSquared()&lt;Box2D.Common.b2Settings.MIN_VALUE_SQUARED){break}var vert=s_simplex.m_vertices[s_simplex.m_count];b2Distance_negD.x=-b2Distance_d.x;b2Distance_negD.y=-b2Distance_d.y;b2MathMulTMVInPlace(input.transformA.R,b2Distance_negD,b2Distance_aNegD);vert.indexA=input.proxyA.GetSupport(b2Distance_aNegD);b2MathMulXInPlace(input.transformA,input.proxyA.GetVertex(vert.indexA),vert.wA);b2MathMulTMVInPlace(input.transformB.R,b2Distance_d,b2Distance_bD);vert.indexB=input.proxyB.GetSupport(b2Distance_bD);b2MathMulXInPlace(input.transformB,input.proxyB.GetVertex(vert.indexB),vert.wB);b2MathSubtractVVInPlace(vert.wB,vert.wA,vert.w);iter++;var duplicate=false;for(var i=0;i&lt;saveLength;i++){if(vert.indexA==save[i].indexA&amp;&amp;vert.indexB==save[i].indexB){duplicate=true;break}}if(duplicate){break}s_simplex.m_count++}s_simplex.GetWitnessPoints(output.pointA,output.pointB);b2MathSubtractVVInPlace(output.pointA,output.pointB,b2Distance_distanceV);output.distance=b2Distance_distanceV.Length();s_simplex.WriteCache(cache);Box2D.Collision.b2Simplex.Free(s_simplex);if(input.useRadii){var rA=input.proxyA.GetRadius();var rB=input.proxyB.GetRadius();if(output.distance&gt;rA+rB&amp;&amp;output.distance&gt;Number.MIN_VALUE){output.distance-=rA+rB;b2MathSubtractVVInPlace(output.pointB,output.pointA,b2Distance_temp);b2Distance_temp.Normalize();output.pointA.x+=rA*b2Distance_temp.x;output.pointA.y+=rA*b2Distance_temp.y;output.pointB.x-=rB*b2Distance_temp.x;output.pointB.y-=rB*b2Distance_temp.y}else{b2Distance_temp.x=.5*(output.pointA.x+output.pointB.x);b2Distance_temp.y=.5*(output.pointA.y+output.pointB.y);output.pointA.x=output.pointB.x=b2Distance_temp.x;output.pointA.y=output.pointB.y=b2Distance_temp.y;output.distance=0}}};Box2D.Collision.b2DistanceInput=function(){this.useRadii=false;this.proxyA=null;this.proxyB=null;this.transformA=null;this.transformB=null};Box2D.Collision.b2DistanceInput._freeCache=[];Box2D.Collision.b2DistanceInput.Get=function(){if(Box2D.Collision.b2DistanceInput._freeCache.length&gt;0){var obj=Box2D.Collision.b2DistanceInput._freeCache.pop();obj.useRadii=false;obj.proxyA=null;obj.proxyB=null;obj.transformA=null;obj.transformB=null;return obj}return new Box2D.Collision.b2DistanceInput};Box2D.Collision.b2DistanceInput.Free=function(obj){if(obj!=null){Box2D.Collision.b2DistanceInput._freeCache.push(obj)}};Box2D.Collision.b2DistanceOutput=function(){this.pointA=Box2D.Common.Math.b2Vec2.Get(0,0);this.pointB=Box2D.Common.Math.b2Vec2.Get(0,0);this.distance=0};Box2D.Collision.b2DistanceOutput._freeCache=[];Box2D.Collision.b2DistanceOutput.Get=function(){if(Box2D.Collision.b2DistanceOutput._freeCache.length&gt;0){var obj=Box2D.Collision.b2DistanceOutput._freeCache.pop();obj.pointA.Set(0,0);obj.pointB.Set(0,0);obj.distance=0;return obj}return new Box2D.Collision.b2DistanceOutput};Box2D.Collision.b2DistanceOutput.Free=function(obj){if(obj!=null){Box2D.Collision.b2DistanceOutput._freeCache.push(obj)}};Box2D.Collision.b2DistanceProxy=function(){this.m_count=0;this.m_radius=0;this.m_vertices=null};Box2D.Collision.b2DistanceProxy.prototype.SetValues=function(count,radius,vertices){this.m_count=count;this.m_radius=radius;this.m_vertices=vertices};Box2D.Collision.b2DistanceProxy.prototype.Set=function(shape){shape.SetDistanceProxy(this)};Box2D.Collision.b2DistanceProxy.prototype.GetSupport=function(d){var bestIndex=0;var bestValue=this.m_vertices[0].x*d.x+this.m_vertices[0].y*d.y;for(var i=1;i&lt;this.m_count;i++){var value=this.m_vertices[i].x*d.x+this.m_vertices[i].y*d.y;if(value&gt;bestValue){bestIndex=i;bestValue=value}}return bestIndex};Box2D.Collision.b2DistanceProxy.prototype.GetSupportVertex=function(d){return this.m_vertices[this.GetSupport(d)]};Box2D.Collision.b2DistanceProxy.prototype.GetVertexCount=function(){return this.m_count};Box2D.Collision.b2DistanceProxy.prototype.GetVertex=function(index){if(index===undefined)index=0;return this.m_vertices[index]};Box2D.Collision.b2DistanceProxy.prototype.GetRadius=function(){return this.m_radius};Box2D.Collision.b2DistanceProxy._freeCache=[];Box2D.Collision.b2DistanceProxy.Get=function(){if(Box2D.Collision.b2DistanceProxy._freeCache.length&gt;0){var obj=Box2D.Collision.b2DistanceProxy._freeCache.pop();obj.m_count=0;obj.m_radius=0;obj.m_vertices=null;return obj}return new Box2D.Collision.b2DistanceProxy};Box2D.Collision.b2DistanceProxy.Free=function(obj){if(obj!=null){Box2D.Collision.b2DistanceProxy._freeCache.push(obj);obj.m_vertices=null}};Box2D.Collision.b2DynamicTree=function(){this.m_root=null;this.m_path=0;this.m_insertionCount=0};Box2D.Collision.b2DynamicTree.s_queryStack=[];Box2D.Collision.b2DynamicTree.prototype.CreateProxy=function(aabb,fixture){var node=Box2D.Collision.b2DynamicTreeNode.Get(fixture);var extendX=Box2D.Common.b2Settings.b2_aabbExtension;var extendY=Box2D.Common.b2Settings.b2_aabbExtension;node.GetAABB().Set(aabb.GetMinX()-extendX,aabb.GetMinY()-extendY,aabb.GetMaxX()+extendX,aabb.GetMaxY()+extendY);this.InsertLeaf(node);return node};Box2D.Collision.b2DynamicTree.prototype.DestroyProxy=function(proxy){this.RemoveLeaf(proxy);proxy.Destroy()};Box2D.Collision.b2DynamicTree.prototype.MoveProxy=function(proxy,aabb,displacement){Box2D.Common.b2Settings.b2Assert(proxy.IsLeaf());if(proxy.GetAABB().Contains(aabb)){return false}this.RemoveLeaf(proxy);var extendX=Box2D.Common.b2Settings.b2_aabbExtension+Box2D.Common.b2Settings.b2_aabbMultiplier*Math.abs(displacement.x);var extendY=Box2D.Common.b2Settings.b2_aabbExtension+Box2D.Common.b2Settings.b2_aabbMultiplier*Math.abs(displacement.y);proxy.GetAABB().Set(aabb.GetMinX()-extendX,aabb.GetMinY()-extendY,aabb.GetMaxX()+extendX,aabb.GetMaxY()+extendY);this.InsertLeaf(proxy);return true};Box2D.Collision.b2DynamicTree.prototype.Rebalance=function(iterations){if(this.m_root!==null){for(var i=0;i&lt;iterations;i++){var node=this.m_root;var bit=0;while(!node.IsLeaf()){node=this.m_path&gt;&gt;bit&amp;1?node.GetChild2():node.GetChild1();bit=bit+1&amp;31}this.m_path++;this.RemoveLeaf(node);this.InsertLeaf(node)}}};Box2D.Collision.b2DynamicTree.prototype.GetFatAABB=function(proxy){return proxy.GetAABB()};Box2D.Collision.b2DynamicTree.prototype.Query=function(callback,aabb,callbackObject){if(this.m_root!==null){var stack=Box2D.Collision.b2DynamicTree.s_queryStack;stack.length=0;stack.push(this.m_root);while(stack.length&gt;0){var node=stack.pop();if(node.GetAABB().TestOverlap(aabb)){if(node.IsLeaf()){if(!callback.call(callbackObject,node.fixture)){return}}else{stack.push(node.GetChild1());stack.push(node.GetChild2())}}}}};Box2D.Collision.b2DynamicTree.prototype.RayCast=function(callback,input){if(this.m_root===null){return}var r=Box2D.Common.Math.b2Math.SubtractVV(input.p1,input.p2);r.Normalize();var v=Box2D.Common.Math.b2Math.CrossFV(1,r);Box2D.Common.Math.b2Vec2.Free(r);var abs_v=Box2D.Common.Math.b2Math.AbsV(v);var maxFraction=input.maxFraction;var tX=input.p1.x+maxFraction*(input.p2.x-input.p1.x);var tY=input.p1.y+maxFraction*(input.p2.y-input.p1.y);var segmentAABB=Box2D.Collision.b2AABB.Get();segmentAABB.Set(Math.min(input.p1.x,tX),Math.min(input.p1.y,tY),Math.max(input.p1.x,tX),Math.max(input.p1.y,tY));var stack=Box2D.Array.Get();stack.push(this.m_root);while(stack.length&gt;0){var node=stack.pop();if(!node.GetAABB().TestOverlap(segmentAABB)){continue}var c=node.GetAABB().GetCenter();var h=node.GetAABB().GetExtents();var separation=Math.abs(v.x*(input.p1.x-c.x)+v.y*(input.p1.y-c.y))-abs_v.x*h.x-abs_v.y*h.y;Box2D.Common.Math.b2Vec2.Free(c);Box2D.Common.Math.b2Vec2.Free(h);if(separation&gt;0){continue}if(node.IsLeaf()){var subInput=new Box2D.Collision.b2RayCastInput(input.p1,input.p2,input.maxFraction);maxFraction=callback(input,node.GetFixture());if(maxFraction==0){break}if(maxFraction&gt;0){tX=input.p1.x+maxFraction*(input.p2.x-input.p1.x);tY=input.p1.y+maxFraction*(input.p2.y-input.p1.y);segmentAABB.Set(Math.min(input.p1.x,tX),Math.min(input.p1.y,tY),Math.max(input.p1.x,tX),Math.max(input.p1.y,tY))}}else{stack.push(node.GetChild1());stack.push(node.GetChild2())}}Box2D.Common.Math.b2Vec2.Free(v);Box2D.Common.Math.b2Vec2.Free(abs_v);Box2D.Collision.b2AABB.Free(segmentAABB);Box2D.Array.Free(stack)};Box2D.Collision.b2DynamicTree.prototype.InsertLeaf=function(leaf){this.m_insertionCount++;if(this.m_root===null){this.m_root=leaf;this.m_root.SetParent(null);return}var sibling=this.GetBestSibling(leaf);var parent=sibling.GetParent();var node2=Box2D.Collision.b2DynamicTreeNode.Get();node2.SetParent(parent);node2.GetAABB().Combine(leaf.GetAABB(),sibling.GetAABB());if(parent){if(sibling.GetParent().GetChild1()==sibling){parent.SetChild1(node2)}else{parent.SetChild2(node2)}node2.SetChild1(sibling);node2.SetChild2(leaf);sibling.SetParent(node2);leaf.SetParent(node2);while(parent){if(parent.GetAABB().Contains(node2.GetAABB())){break}parent.GetAABB().Combine(parent.GetChild1().GetAABB(),parent.GetChild2().GetAABB());node2=parent;parent=parent.GetParent()}}else{node2.SetChild1(sibling);node2.SetChild2(leaf);sibling.SetParent(node2);leaf.SetParent(node2);this.m_root=node2}};Box2D.Collision.b2DynamicTree.prototype.GetBestSibling=function(leaf){var center=leaf.GetAABB().GetCenter();var sibling=this.m_root;while(!sibling.IsLeaf()){var child1=sibling.GetChild1();var child2=sibling.GetChild2();var norm1=Math.abs((child1.GetAABB().GetMinX()+child1.GetAABB().GetMaxX())/2-center.x)+Math.abs((child1.GetAABB().GetMinY()+child1.GetAABB().GetMaxY())/2-center.y);var norm2=Math.abs((child2.GetAABB().GetMinX()+child2.GetAABB().GetMaxX())/2-center.x)+Math.abs((child2.GetAABB().GetMinY()+child2.GetAABB().GetMaxY())/2-center.y);if(norm1&lt;norm2){sibling=child1}else{sibling=child2}}Box2D.Common.Math.b2Vec2.Free(center);return sibling};Box2D.Collision.b2DynamicTree.prototype.RemoveLeaf=function(leaf){if(leaf==this.m_root){this.m_root=null;return}var node2=leaf.GetParent();var node1=node2.GetParent();var sibling;if(node2.GetChild1()==leaf){sibling=node2.GetChild2()}else{sibling=node2.GetChild1()}if(node1){if(node1.GetChild1()==node2){node1.SetChild1(sibling)}else{node1.SetChild2(sibling)}sibling.SetParent(node1);while(node1){var oldAABB=node1.GetAABB();node1.GetAABB().Combine(node1.GetChild1().GetAABB(),node1.GetChild2().GetAABB());if(oldAABB.Contains(node1.GetAABB())){break}node1=node1.GetParent()}}else{this.m_root=sibling;sibling.SetParent(null)}node2.Destroy()};Box2D.Collision.b2DynamicTreeBroadPhase=function(){this.m_tree=new Box2D.Collision.b2DynamicTree;this.m_moveBuffer=[];this.lastQueryFixtureA=null;this.lastQueryFixtureB=null;this.updatePairsCallback=null;this.queryProxy=null};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.CreateProxy=function(aabb,fixture){var proxy=this.m_tree.CreateProxy(aabb,fixture);this.BufferMove(proxy);return proxy};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.DestroyProxy=function(proxy){this.UnBufferMove(proxy);this.m_tree.DestroyProxy(proxy)};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.MoveProxy=function(proxy,aabb,displacement){var buffer=this.m_tree.MoveProxy(proxy,aabb,displacement);if(buffer){this.BufferMove(proxy)}};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.TestOverlap=function(proxyA,proxyB){var aabbA=this.m_tree.GetFatAABB(proxyA);var aabbB=this.m_tree.GetFatAABB(proxyB);return aabbA.TestOverlap(aabbB)};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.GetFatAABB=function(proxy){return this.m_tree.GetFatAABB(proxy)};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.GetProxyCount=function(){return this.m_tree.length};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.UpdatePairs=function(callback){this.lastQueryFixtureA=null;this.lastQueryFixtureB=null;this.updatePairsCallback=callback;while(this.m_moveBuffer.length&gt;0){this.queryProxy=this.m_moveBuffer.pop();this.m_tree.Query(this.QueryCallback,this.m_tree.GetFatAABB(this.queryProxy),this)}this.lastQueryFixtureA=null;this.lastQueryFixtureB=null;this.updatePairsCallback=null;this.queryProxy=null};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.QueryCallback=function(fixture){if(fixture!=this.queryProxy.fixture){if(!(this.queryProxy.fixture==this.lastQueryFixtureA&amp;&amp;fixture==this.lastQueryFixtureB)&amp;&amp;!(this.queryProxy.fixture==this.lastQueryFixtureB&amp;&amp;fixture==this.lastQueryFixtureA)){this.updatePairsCallback(this.queryProxy.fixture,fixture);this.lastQueryFixtureA=this.queryProxy.fixture;this.lastQueryFixtureB=fixture}}return true};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.Query=function(callback,aabb){this.m_tree.Query(callback,aabb)};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.RayCast=function(callback,input){this.m_tree.RayCast(callback,input)};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.Rebalance=function(iterations){this.m_tree.Rebalance(iterations)};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.BufferMove=function(proxy){this.m_moveBuffer.push(proxy)};Box2D.Collision.b2DynamicTreeBroadPhase.prototype.UnBufferMove=function(proxy){Box2D.Array.remove(this.m_moveBuffer,proxy)};Box2D.Collision.b2DynamicTreeBroadPhase.__implements={};Box2D.Collision.b2DynamicTreeBroadPhase.__implements[Box2D.Collision.IBroadPhase]=true;Box2D.Collision.b2DynamicTreeNode=function(fixture){this.aabb=Box2D.Collision.b2AABB.Get();this.child1=null;this.child2=null;this.parent=null;this.fixture=fixture};Box2D.Collision.b2DynamicTreeNode._freeCache=[];Box2D.Collision.b2DynamicTreeNode.Get=function(fixture){if(typeof fixture=="undefined"){fixture=null}if(Box2D.Collision.b2DynamicTreeNode._freeCache.length&gt;0){var node=Box2D.Collision.b2DynamicTreeNode._freeCache.pop();node.fixture=fixture;node.aabb.SetZero();return node}return new Box2D.Collision.b2DynamicTreeNode(fixture)};Box2D.Collision.b2DynamicTreeNode.prototype.Destroy=function(){this.child1=null;this.child2=null;this.parent=null;this.fixture=null;Box2D.Collision.b2DynamicTreeNode._freeCache.push(this)};Box2D.Collision.b2DynamicTreeNode.prototype.IsLeaf=function(){return this.child1===null};Box2D.Collision.b2DynamicTreeNode.prototype.SetChild1=function(child){this.child1=child};Box2D.Collision.b2DynamicTreeNode.prototype.GetChild1=function(){return this.child1};Box2D.Collision.b2DynamicTreeNode.prototype.SetChild2=function(child){this.child2=child};Box2D.Collision.b2DynamicTreeNode.prototype.GetChild2=function(){return this.child2};Box2D.Collision.b2DynamicTreeNode.prototype.SetParent=function(parent){this.parent=parent};Box2D.Collision.b2DynamicTreeNode.prototype.GetParent=function(){return this.parent};Box2D.Collision.b2DynamicTreeNode.prototype.GetAABB=function(){return this.aabb};Box2D.Collision.b2DynamicTreeNode.prototype.GetFixture=function(){return this.fixture};Box2D.Collision.b2DynamicTreePair=function(fixtureA,fixtureB){this.fixtureA=fixtureA;this.fixtureB=fixtureB};Box2D.Collision.b2DynamicTreePair._freeCache=[];Box2D.Collision.b2DynamicTreePair.Get=function(fixtureA,fixtureB){if(Box2D.Collision.b2DynamicTreePair._freeCache.length&gt;0){var pair=Box2D.Collision.b2DynamicTreePair._freeCache.pop();pair.fixtureA=fixtureA;pair.fixtureB=fixtureB;return pair}return new Box2D.Collision.b2DynamicTreePair(fixtureA,fixtureB)};Box2D.Collision.b2DynamicTreePair.Free=function(pair){if(pair!=null){Box2D.Collision.b2DynamicTreePair._freeCache.push(pair)}};Box2D.Collision.b2Manifold=function(){this.m_pointCount=0;this.m_type=0;this.m_points=Box2D.Array.Get();for(var i=0;i&lt;Box2D.Common.b2Settings.b2_maxManifoldPoints;i++){this.m_points[i]=new Box2D.Collision.b2ManifoldPoint}this.m_localPlaneNormal=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_localPoint=Box2D.Common.Math.b2Vec2.Get(0,0)};Box2D.Collision.b2Manifold.prototype.Reset=function(){for(var i=0;i&lt;Box2D.Common.b2Settings.b2_maxManifoldPoints;i++){this.m_points[i].Reset()}this.m_localPlaneNormal.SetZero();this.m_localPoint.SetZero();this.m_type=0;this.m_pointCount=0};Box2D.Collision.b2Manifold.prototype.Set=function(m){this.m_pointCount=m.m_pointCount;for(var i=0;i&lt;Box2D.Common.b2Settings.b2_maxManifoldPoints;i++){this.m_points[i].Set(m.m_points[i])}this.m_localPlaneNormal.SetV(m.m_localPlaneNormal);this.m_localPoint.SetV(m.m_localPoint);this.m_type=m.m_type};Box2D.Collision.b2Manifold.prototype.Copy=function(){var copy=new Box2D.Collision.b2Manifold;copy.Set(this);return copy};Box2D.Collision.b2Manifold.prototype.SetPointCount=function(count){this.m_pointCount=count};Box2D.Collision.b2Manifold.prototype.SetType=function(type){this.m_type=type};Box2D.Collision.b2Manifold.e_circles=1;Box2D.Collision.b2Manifold.e_faceA=2;Box2D.Collision.b2Manifold.e_faceB=4;Box2D.Collision.b2ManifoldPoint=function(){this.m_localPoint=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_id=new Box2D.Collision.b2ContactID;this.m_normalImpulse=0;this.m_tangentImpulse=0};Box2D.Collision.b2ManifoldPoint.prototype.Reset=function(){this.m_localPoint.SetZero();this.m_normalImpulse=0;this.m_tangentImpulse=0;this.m_id.SetKey(0)};Box2D.Collision.b2ManifoldPoint.prototype.Set=function(m){this.m_localPoint.SetV(m.m_localPoint);this.m_normalImpulse=m.m_normalImpulse;this.m_tangentImpulse=m.m_tangentImpulse;this.m_id.Set(m.m_id)};Box2D.Collision.b2RayCastInput=function(p1,p2,maxFraction){this.p1=Box2D.Common.Math.b2Vec2.Get(p1.x,p1.y);this.p2=Box2D.Common.Math.b2Vec2.Get(p2.x,p2.y);this.maxFraction=maxFraction};Box2D.Collision.b2RayCastOutput=function(){this.normal=Box2D.Common.Math.b2Vec2.Get(0,0)};Box2D.Collision.b2Segment=function(){this.p1=Box2D.Common.Math.b2Vec2.Get(0,0);this.p2=Box2D.Common.Math.b2Vec2.Get(0,0)};Box2D.Collision.b2Segment.prototype.TestSegment=function(lambda,normal,segment,maxLambda){var s=segment.p1;var rX=segment.p2.x-s.x;var rY=segment.p2.y-s.y;var dX=this.p2.x-this.p1.x;var dY=this.p2.y-this.p1.y;var nX=dY;var nY=-dX;var k_slop=100*Number.MIN_VALUE;var denom=-(rX*nX+rY*nY);if(denom&gt;k_slop){var bX=s.x-this.p1.x;var bY=s.y-this.p1.y;var a=bX*nX+bY*nY;if(0&lt;=a&amp;&amp;a&lt;=maxLambda*denom){var mu2=-rX*bY+rY*bX;if(-k_slop*denom&lt;=mu2&amp;&amp;mu2&lt;=denom*(1+k_slop)){a/=denom;var nLen=Math.sqrt(nX*nX+nY*nY);nX/=nLen;nY/=nLen;lambda[0]=a;normal.Set(nX,nY);return true}}}return false};Box2D.Collision.b2Segment.prototype.Extend=function(aabb){this.ExtendForward(aabb);this.ExtendBackward(aabb)};Box2D.Collision.b2Segment.prototype.ExtendForward=function(aabb){var dX=this.p2.x-this.p1.x;var dY=this.p2.y-this.p1.y;var lambda=Math.min(dX&gt;0?(aabb.upperBound.x-this.p1.x)/dX:dX&lt;0?(aabb.lowerBound.x-this.p1.x)/dX:Number.POSITIVE_INFINITY,dY&gt;0?(aabb.upperBound.y-this.p1.y)/dY:dY&lt;0?(aabb.lowerBound.y-this.p1.y)/dY:Number.POSITIVE_INFINITY);this.p2.x=this.p1.x+dX*lambda;this.p2.y=this.p1.y+dY*lambda};Box2D.Collision.b2Segment.prototype.ExtendBackward=function(aabb){var dX=-this.p2.x+this.p1.x;var dY=-this.p2.y+this.p1.y;var lambda=Math.min(dX&gt;0?(aabb.upperBound.x-this.p2.x)/dX:dX&lt;0?(aabb.lowerBound.x-this.p2.x)/dX:Number.POSITIVE_INFINITY,dY&gt;0?(aabb.upperBound.y-this.p2.y)/dY:dY&lt;0?(aabb.lowerBound.y-this.p2.y)/dY:Number.POSITIVE_INFINITY);this.p1.x=this.p2.x+dX*lambda;this.p1.y=this.p2.y+dY*lambda};Box2D.Collision.b2SeparationFunction=function(){this.m_localPoint=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_axis=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_proxyA=null;this.m_proxyB=null};Box2D.Collision.b2SeparationFunction.prototype.Initialize=function(cache,proxyA,transformA,proxyB,transformB){this.m_proxyA=proxyA;this.m_proxyB=proxyB;var count=cache.count;Box2D.Common.b2Settings.b2Assert(0&lt;count&amp;&amp;count&lt;3);var localPointA;var localPointA1;var localPointA2;var localPointB;var localPointB1;var localPointB2;var pointAX=0;var pointAY=0;var pointBX=0;var pointBY=0;var normalX=0;var normalY=0;var tMat;var tVec;var s=0;var sgn=0;if(count==1){this.m_type=Box2D.Collision.b2SeparationFunction.e_points;localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);tVec=localPointA;tMat=transformA.R;pointAX=transformA.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointAY=transformA.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tVec=localPointB;tMat=transformB.R;pointBX=transformB.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointBY=transformB.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);this.m_axis.x=pointBX-pointAX;this.m_axis.y=pointBY-pointAY;this.m_axis.Normalize()}else if(cache.indexB[0]==cache.indexB[1]){this.m_type=Box2D.Collision.b2SeparationFunction.e_faceA;localPointA1=this.m_proxyA.GetVertex(cache.indexA[0]);localPointA2=this.m_proxyA.GetVertex(cache.indexA[1]);localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);this.m_localPoint.x=.5*(localPointA1.x+localPointA2.x);this.m_localPoint.y=.5*(localPointA1.y+localPointA2.y);var tempVec=Box2D.Common.Math.b2Math.SubtractVV(localPointA2,localPointA1);Box2D.Common.Math.b2Vec2.Free(this.m_axis);this.m_axis=Box2D.Common.Math.b2Math.CrossVF(tempVec,1);Box2D.Common.Math.b2Vec2.Free(tempVec);this.m_axis.Normalize();tVec=this.m_axis;tMat=transformA.R;normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tVec=this.m_localPoint;tMat=transformA.R;pointAX=transformA.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointAY=transformA.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tVec=localPointB;tMat=transformB.R;pointBX=transformB.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointBY=transformB.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);s=(pointBX-pointAX)*normalX+(pointBY-pointAY)*normalY;if(s&lt;0){this.m_axis.NegativeSelf()}}else if(cache.indexA[0]==cache.indexA[0]){this.m_type=Box2D.Collision.b2SeparationFunction.e_faceB;localPointB1=this.m_proxyB.GetVertex(cache.indexB[0]);localPointB2=this.m_proxyB.GetVertex(cache.indexB[1]);localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);this.m_localPoint.x=.5*(localPointB1.x+localPointB2.x);this.m_localPoint.y=.5*(localPointB1.y+localPointB2.y);var tempVec=Box2D.Common.Math.b2Math.SubtractVV(localPointB2,localPointB1);Box2D.Common.Math.b2Vec2.Free(this.m_axis);this.m_axis=Box2D.Common.Math.b2Math.CrossVF(tempVec,1);Box2D.Common.Math.b2Vec2.Free(tempVec);this.m_axis.Normalize();tVec=this.m_axis;tMat=transformB.R;normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tVec=this.m_localPoint;tMat=transformB.R;pointBX=transformB.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointBY=transformB.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tVec=localPointA;tMat=transformA.R;pointAX=transformA.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointAY=transformA.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);s=(pointAX-pointBX)*normalX+(pointAY-pointBY)*normalY;if(s&lt;0){this.m_axis.NegativeSelf()}}else{localPointA1=this.m_proxyA.GetVertex(cache.indexA[0]);localPointA2=this.m_proxyA.GetVertex(cache.indexA[1]);localPointB1=this.m_proxyB.GetVertex(cache.indexB[0]);localPointB2=this.m_proxyB.GetVertex(cache.indexB[1]);var tempVec=Box2D.Common.Math.b2Math.SubtractVV(localPointA2,localPointA1);var dA=Box2D.Common.Math.b2Math.MulMV(transformA.R,tempVec);Box2D.Common.Math.b2Vec2.Free(tempVec);tempVec=Box2D.Common.Math.b2Math.SubtractVV(localPointB2,localPointB1);var dB=Box2D.Common.Math.b2Math.MulMV(transformB.R,tempVec);Box2D.Common.Math.b2Vec2.Free(tempVec);var a=dA.x*dA.x+dA.y*dA.y;var e=dB.x*dB.x+dB.y*dB.y;var r=Box2D.Common.Math.b2Math.SubtractVV(dB,dA);var c=dA.x*r.x+dA.y*r.y;var f=dB.x*r.x+dB.y*r.y;Box2D.Common.Math.b2Vec2.Free(r);var b=dA.x*dB.x+dA.y*dB.y;var denom=a*e-b*b;s=0;if(denom!=0){s=Box2D.Common.Math.b2Math.Clamp01((b*f-c*e)/denom)}var t=(b*s+f)/e;if(t&lt;0){t=0;s=Box2D.Common.Math.b2Math.Clamp01((b-c)/a)}localPointA=Box2D.Common.Math.b2Vec2.Get(0,0);localPointA.x=localPointA1.x+s*(localPointA2.x-localPointA1.x);localPointA.y=localPointA1.y+s*(localPointA2.y-localPointA1.y);localPointB=Box2D.Common.Math.b2Vec2.Get(0,0);localPointB.x=localPointB1.x+s*(localPointB2.x-localPointB1.x);localPointB.y=localPointB1.y+s*(localPointB2.y-localPointB1.y);if(s==0||s==1){this.m_type=Box2D.Collision.b2SeparationFunction.e_faceB;tempVec=Box2D.Common.Math.b2Math.SubtractVV(localPointB2,localPointB1);Box2D.Common.Math.b2Vec2.Free(this.m_axis);this.m_axis=Box2D.Common.Math.b2Math.CrossVF(tempVec,1);Box2D.Common.Math.b2Vec2.Free(tempVec);this.m_axis.Normalize();this.m_localPoint=localPointB;tVec=this.m_axis;tMat=transformB.R;normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tVec=this.m_localPoint;tMat=transformB.R;pointBX=transformB.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointBY=transformB.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tVec=localPointA;tMat=transformA.R;pointAX=transformA.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointAY=transformA.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);sgn=(pointAX-pointBX)*normalX+(pointAY-pointBY)*normalY;if(s&lt;0){this.m_axis.NegativeSelf()}}else{this.m_type=Box2D.Collision.b2SeparationFunction.e_faceA;tempVec=Box2D.Common.Math.b2Math.SubtractVV(localPointA2,localPointA1);Box2D.Common.Math.b2Vec2.Free(this.m_axis);this.m_axis=Box2D.Common.Math.b2Math.CrossVF(tempVec,1);Box2D.Common.Math.b2Vec2.Free(tempVec);this.m_localPoint=localPointA;tVec=this.m_axis;tMat=transformA.R;normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tVec=this.m_localPoint;tMat=transformA.R;pointAX=transformA.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointAY=transformA.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tVec=localPointB;tMat=transformB.R;pointBX=transformB.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);pointBY=transformB.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);sgn=(pointBX-pointAX)*normalX+(pointBY-pointAY)*normalY;if(s&lt;0){this.m_axis.NegativeSelf()}}Box2D.Common.Math.b2Vec2.Free(localPointA);Box2D.Common.Math.b2Vec2.Free(localPointB)}};Box2D.Collision.b2SeparationFunction.prototype.Evaluate=function(transformA,transformB){var seperation=0;switch(this.m_type){case Box2D.Collision.b2SeparationFunction.e_points:var axisA=Box2D.Common.Math.b2Math.MulTMV(transformA.R,this.m_axis);var negMAxis=this.m_axis.GetNegative();var axisB=Box2D.Common.Math.b2Math.MulTMV(transformB.R,negMAxis);Box2D.Common.Math.b2Vec2.Free(negMAxis);var localPointA=this.m_proxyA.GetSupportVertex(axisA);Box2D.Common.Math.b2Vec2.Free(axisA);var localPointB=this.m_proxyB.GetSupportVertex(axisB);Box2D.Common.Math.b2Vec2.Free(axisB);var pointA=Box2D.Common.Math.b2Math.MulX(transformA,localPointA);var pointB=Box2D.Common.Math.b2Math.MulX(transformB,localPointB);seperation=(pointB.x-pointA.x)*this.m_axis.x+(pointB.y-pointA.y)*this.m_axis.y;Box2D.Common.Math.b2Vec2.Free(pointA);Box2D.Common.Math.b2Vec2.Free(pointB);break;case Box2D.Collision.b2SeparationFunction.e_faceA:var normal=Box2D.Common.Math.b2Math.MulMV(transformA.R,this.m_axis);var negNormal=normal.GetNegative();var axisB=Box2D.Common.Math.b2Math.MulTMV(transformB.R,negNormal);Box2D.Common.Math.b2Vec2.Free(negNormal);var localPointB=this.m_proxyB.GetSupportVertex(axisB);Box2D.Common.Math.b2Vec2.Free(axisB);var pointA=Box2D.Common.Math.b2Math.MulX(transformA,this.m_localPoint);var pointB=Box2D.Common.Math.b2Math.MulX(transformB,localPointB);seperation=(pointB.x-pointA.x)*normal.x+(pointB.y-pointA.y)*normal.y;Box2D.Common.Math.b2Vec2.Free(normal);Box2D.Common.Math.b2Vec2.Free(pointA);Box2D.Common.Math.b2Vec2.Free(pointB);break;case Box2D.Collision.b2SeparationFunction.e_faceB:var normal=Box2D.Common.Math.b2Math.MulMV(transformB.R,this.m_axis);var negNormal=normal.GetNegative();var axisA=Box2D.Common.Math.b2Math.MulTMV(transformA.R,negNormal);Box2D.Common.Math.b2Vec2.Free(negNormal);var localPointA=this.m_proxyA.GetSupportVertex(axisA);Box2D.Common.Math.b2Vec2.Free(axisA);var pointA=Box2D.Common.Math.b2Math.MulX(transformA,localPointA);var pointB=Box2D.Common.Math.b2Math.MulX(transformB,this.m_localPoint);seperation=(pointA.x-pointB.x)*normal.x+(pointA.y-pointB.y)*normal.y;Box2D.Common.Math.b2Vec2.Free(normal);Box2D.Common.Math.b2Vec2.Free(pointA);Box2D.Common.Math.b2Vec2.Free(pointB);break;default:Box2D.Common.b2Settings.b2Assert(false);break}return seperation};Box2D.Collision.b2SeparationFunction.e_points=1;Box2D.Collision.b2SeparationFunction.e_faceA=2;Box2D.Collision.b2SeparationFunction.e_faceB=4;Box2D.Collision.b2Simplex=function(){this.m_v1=new Box2D.Collision.b2SimplexVertex;this.m_v2=new Box2D.Collision.b2SimplexVertex;this.m_v3=new Box2D.Collision.b2SimplexVertex;this.m_vertices=[this.m_v1,this.m_v2,this.m_v3]};Box2D.Collision.b2Simplex._freeCache=[];Box2D.Collision.b2Simplex.Get=function(){if(Box2D.Collision.b2Simplex._freeCache.length&gt;0){var simplex=Box2D.Collision.b2Simplex._freeCache.pop();var vertices=simplex.m_vertices;var numVerts=vertices.length;for(var i=0;i&lt;numVerts;i++){var v=vertices[i];var wA=v.wA;if(wA!=null){wA.x=0;wA.y=0}var wB=v.wB;if(wB!=null){wB.x=0;wB.y=0}var w=v.w;if(w!=null){w.x=0;w.y=0}v.indexA=0;v.indexB=0;v.a=0}return simplex}return new Box2D.Collision.b2Simplex};Box2D.Collision.b2Simplex.Free=function(simplex){if(simplex!=null){Box2D.Collision.b2Simplex._freeCache.push(simplex)}};Box2D.Collision.b2Simplex.prototype.ReadCache=function(cache,proxyA,transformA,proxyB,transformB){var wALocal;var wBLocal;this.m_count=cache.count;var vertices=this.m_vertices;for(var i=0;i&lt;this.m_count;i++){var v=vertices[i];v.indexA=cache.indexA[i];v.indexB=cache.indexB[i];wALocal=proxyA.GetVertex(v.indexA);wBLocal=proxyB.GetVertex(v.indexB);var wA=v.wA;var wB=v.wB;var w=v.w;b2MathMulXInPlace(transformA,wALocal,wA);b2MathMulXInPlace(transformB,wBLocal,wB);b2MathSubtractVVInPlace(wB,wA,w);v.a=0}if(this.m_count&gt;1){var metric1=cache.metric;var metric2=this.GetMetric();if(metric2&lt;.5*metric1||2*metric1&lt;metric2||metric2&lt;Number.MIN_VALUE){this.m_count=0}}if(this.m_count==0){v=vertices[0];v.indexA=0;v.indexB=0;wALocal=proxyA.GetVertex(0);wBLocal=proxyB.GetVertex(0);b2MathMulXInPlace(transformA,wALocal,v.wA);b2MathMulXInPlace(transformB,wBLocal,v.wB);b2MathSubtractVVInPlace(v.wB,v.wA,v.w);this.m_count=1}};Box2D.Collision.b2Simplex.prototype.WriteCache=function(cache){cache.metric=this.GetMetric();cache.count=this.m_count;var vertices=this.m_vertices;for(var i=0;i&lt;this.m_count;i++){cache.indexA[i]=vertices[i].indexA;cache.indexB[i]=vertices[i].indexB}};Box2D.Collision.b2Simplex.prototype.GetSearchDirection=function(){if(this.m_count==1){return this.m_v1.w.GetNegative()}else if(this.m_count==2){var v1=this.m_v1.w;var v2=this.m_v2.w;var ret=b2Vec2Get(v2.x-v1.x,v2.y-v1.y);var sgn=ret.x*-v1.y-ret.y*-v1.x;if(sgn&gt;0){var temp=ret.x;ret.x=-1*ret.y;ret.y=temp}else{var temp=ret.y;ret.y=-1*ret.x;ret.x=temp}return ret}else{Box2D.Common.b2Settings.b2Assert(false);return b2Vec2Get(0,0)}};Box2D.Collision.b2Simplex.prototype.GetSearchDirectionInPlace=function(r){if(this.m_count==1){var v1=this.m_v1.w;r.x=-v1.x;r.y=-v1.y}else if(this.m_count==2){var v1=this.m_v1.w;var v2=this.m_v2.w;r.x=v2.x-v1.x;r.y=v2.y-v1.y;var sgn=r.x*-v1.y-r.y*-v1.x;if(sgn&gt;0){var temp=r.x;r.x=-1*r.y;r.y=temp}else{var temp=r.y;r.y=-1*r.x;r.x=temp}}else{Box2D.Common.b2Settings.b2Assert(false);r.x=0;r.y=0}};Box2D.Collision.b2Simplex.prototype.GetClosestPoint=function(){if(this.m_count==1){return this.m_v1.w}else if(this.m_count==2){return Box2D.Common.Math.b2Vec2.Get(this.m_v1.a*this.m_v1.w.x+this.m_v2.a*this.m_v2.w.x,this.m_v1.a*this.m_v1.w.y+this.m_v2.a*this.m_v2.w.y)}else{Box2D.Common.b2Settings.b2Assert(false);return Box2D.Common.Math.b2Vec2.Get(0,0)}};Box2D.Collision.b2Simplex.prototype.GetWitnessPoints=function(pA,pB){if(this.m_count==1){pA.SetV(this.m_v1.wA);pB.SetV(this.m_v1.wB)}else if(this.m_count==2){pA.x=this.m_v1.a*this.m_v1.wA.x+this.m_v2.a*this.m_v2.wA.x;pA.y=this.m_v1.a*this.m_v1.wA.y+this.m_v2.a*this.m_v2.wA.y;pB.x=this.m_v1.a*this.m_v1.wB.x+this.m_v2.a*this.m_v2.wB.x;pB.y=this.m_v1.a*this.m_v1.wB.y+this.m_v2.a*this.m_v2.wB.y}else if(this.m_count==3){pB.x=pA.x=this.m_v1.a*this.m_v1.wA.x+this.m_v2.a*this.m_v2.wA.x+this.m_v3.a*this.m_v3.wA.x;pB.y=pA.y=this.m_v1.a*this.m_v1.wA.y+this.m_v2.a*this.m_v2.wA.y+this.m_v3.a*this.m_v3.wA.y}else{Box2D.Common.b2Settings.b2Assert(false)}};Box2D.Collision.b2Simplex.prototype.GetMetric=function(){if(this.m_count==1){return 0}else if(this.m_count==2){var v=Box2D.Common.Math.b2Math.SubtractVV(this.m_v1.w,this.m_v2.w);var metric=v.Length();Box2D.Common.Math.b2Vec2.Free(v);return metric}else if(this.m_count==3){var vA=Box2D.Common.Math.b2Math.SubtractVV(this.m_v2.w,this.m_v1.w);var vB=Box2D.Common.Math.b2Math.SubtractVV(this.m_v3.w,this.m_v1.w);var metric=Box2D.Common.Math.b2Math.CrossVV(vA,vB);Box2D.Common.Math.b2Vec2.Free(vA);Box2D.Common.Math.b2Vec2.Free(vB);return metric}else{Box2D.Common.b2Settings.b2Assert(false);return 0}};Box2D.Collision.b2Simplex.prototype.Solve2=function(){var w1=this.m_v1.w;var w2=this.m_v2.w;var e12=Box2D.Common.Math.b2Math.SubtractVV(w2,w1);var d12_2=-(w1.x*e12.x+w1.y*e12.y);if(d12_2&lt;=0){Box2D.Common.Math.b2Vec2.Free(e12);this.m_v1.a=1;this.m_count=1;return}var d12_1=w2.x*e12.x+w2.y*e12.y;Box2D.Common.Math.b2Vec2.Free(e12);if(d12_1&lt;=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Set(this.m_v2);return}var inv_d12=1/(d12_1+d12_2);this.m_v1.a=d12_1*inv_d12;this.m_v2.a=d12_2*inv_d12;this.m_count=2};Box2D.Collision.b2Simplex.prototype.Solve3=function(){var w1=this.m_v1.w;var w2=this.m_v2.w;var w3=this.m_v3.w;var e12=Box2D.Common.Math.b2Math.SubtractVV(w2,w1);var w1e12=Box2D.Common.Math.b2Math.Dot(w1,e12);var w2e12=Box2D.Common.Math.b2Math.Dot(w2,e12);var d12_1=w2e12;var d12_2=-w1e12;var e13=Box2D.Common.Math.b2Math.SubtractVV(w3,w1);var w1e13=Box2D.Common.Math.b2Math.Dot(w1,e13);var w3e13=Box2D.Common.Math.b2Math.Dot(w3,e13);var n123=Box2D.Common.Math.b2Math.CrossVV(e12,e13);Box2D.Common.Math.b2Vec2.Free(e12);Box2D.Common.Math.b2Vec2.Free(e13);var d13_1=w3e13;var d13_2=-w1e13;var e23=Box2D.Common.Math.b2Math.SubtractVV(w3,w2);var w2e23=Box2D.Common.Math.b2Math.Dot(w2,e23);var w3e23=Box2D.Common.Math.b2Math.Dot(w3,e23);Box2D.Common.Math.b2Vec2.Free(e23);var d23_1=w3e23;var d23_2=-w2e23;var d123_1=n123*Box2D.Common.Math.b2Math.CrossVV(w2,w3);var d123_2=n123*Box2D.Common.Math.b2Math.CrossVV(w3,w1);var d123_3=n123*Box2D.Common.Math.b2Math.CrossVV(w1,w2);if(d12_2&lt;=0&amp;&amp;d13_2&lt;=0){this.m_v1.a=1;this.m_count=1;return}if(d12_1&gt;0&amp;&amp;d12_2&gt;0&amp;&amp;d123_3&lt;=0){var inv_d12=1/(d12_1+d12_2);this.m_v1.a=d12_1*inv_d12;this.m_v2.a=d12_2*inv_d12;this.m_count=2;return}if(d13_1&gt;0&amp;&amp;d13_2&gt;0&amp;&amp;d123_2&lt;=0){var inv_d13=1/(d13_1+d13_2);this.m_v1.a=d13_1*inv_d13;this.m_v3.a=d13_2*inv_d13;this.m_count=2;this.m_v2.Set(this.m_v3);return}if(d12_1&lt;=0&amp;&amp;d23_2&lt;=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Set(this.m_v2);return}if(d13_1&lt;=0&amp;&amp;d23_1&lt;=0){this.m_v3.a=1;this.m_count=1;this.m_v1.Set(this.m_v3);return}if(d23_1&gt;0&amp;&amp;d23_2&gt;0&amp;&amp;d123_1&lt;=0){var inv_d23=1/(d23_1+d23_2);this.m_v2.a=d23_1*inv_d23;this.m_v3.a=d23_2*inv_d23;this.m_count=2;this.m_v1.Set(this.m_v3);return}var inv_d123=1/(d123_1+d123_2+d123_3);this.m_v1.a=d123_1*inv_d123;this.m_v2.a=d123_2*inv_d123;this.m_v3.a=d123_3*inv_d123;this.m_count=3};Box2D.Collision.b2SimplexCache=function(){this.count=0;this.indexA=[0,0,0];this.indexB=[0,0,0]};Box2D.Collision.b2SimplexCache._freeCache=[];Box2D.Collision.b2SimplexCache.Get=function(){if(Box2D.Collision.b2SimplexCache._freeCache.length&gt;0){var obj=Box2D.Collision.b2SimplexCache._freeCache.pop();for(var i=0;i&lt;3;i++){obj.indexA[i]=0;obj.indexB[i]=0}obj.count=0;return obj}return new Box2D.Collision.b2SimplexCache};Box2D.Collision.b2SimplexCache.Free=function(obj){if(obj!=null){Box2D.Collision.b2SimplexCache._freeCache.push(obj)}};Box2D.Collision.b2SimplexVertex=function(){this.wA=Box2D.Common.Math.b2Vec2.Get(0,0);this.wB=Box2D.Common.Math.b2Vec2.Get(0,0);this.w=Box2D.Common.Math.b2Vec2.Get(0,0);this.a=0;this.indexA=0;this.indexB=0};Box2D.Collision.b2SimplexVertex.prototype.Set=function(other){this.wA.SetV(other.wA);this.wB.SetV(other.wB);this.w.SetV(other.w);this.a=other.a;this.indexA=other.indexA;this.indexB=other.indexB};Box2D.Collision.b2TOIInput=function(){this.proxyA=Box2D.Collision.b2DistanceProxy.Get();this.proxyB=Box2D.Collision.b2DistanceProxy.Get();this.sweepA=new Box2D.Common.Math.b2Sweep;this.sweepB=new Box2D.Common.Math.b2Sweep};Box2D.Collision.b2TimeOfImpact={};Box2D.Collision.b2TimeOfImpact.TimeOfImpact=function(input){Box2D.Collision.b2TimeOfImpact.b2_toiCalls++;var proxyA=input.proxyA;var proxyB=input.proxyB;var sweepA=input.sweepA;var sweepB=input.sweepB;Box2D.Common.b2Settings.b2Assert(sweepA.t0==sweepB.t0);Box2D.Common.b2Settings.b2Assert(1-sweepA.t0&gt;Number.MIN_VALUE);var radius=proxyA.m_radius+proxyB.m_radius;var tolerance=input.tolerance;var alpha=0;var k_maxIterations=1e3;var iter=0;var target=0;Box2D.Collision.b2TimeOfImpact.s_cache.count=0;Box2D.Collision.b2TimeOfImpact.s_distanceInput.useRadii=false;for(;;){sweepA.GetTransform(Box2D.Collision.b2TimeOfImpact.s_xfA,alpha);sweepB.GetTransform(Box2D.Collision.b2TimeOfImpact.s_xfB,alpha);Box2D.Collision.b2TimeOfImpact.s_distanceInput.proxyA=proxyA;Box2D.Collision.b2TimeOfImpact.s_distanceInput.proxyB=proxyB;Box2D.Collision.b2TimeOfImpact.s_distanceInput.transformA=Box2D.Collision.b2TimeOfImpact.s_xfA;Box2D.Collision.b2TimeOfImpact.s_distanceInput.transformB=Box2D.Collision.b2TimeOfImpact.s_xfB;Box2D.Collision.b2Distance.Distance(Box2D.Collision.b2TimeOfImpact.s_distanceOutput,Box2D.Collision.b2TimeOfImpact.s_cache,Box2D.Collision.b2TimeOfImpact.s_distanceInput);if(Box2D.Collision.b2TimeOfImpact.s_distanceOutput.distance&lt;=0){alpha=1;break}Box2D.Collision.b2TimeOfImpact.s_fcn.Initialize(Box2D.Collision.b2TimeOfImpact.s_cache,proxyA,Box2D.Collision.b2TimeOfImpact.s_xfA,proxyB,Box2D.Collision.b2TimeOfImpact.s_xfB);var separation=Box2D.Collision.b2TimeOfImpact.s_fcn.Evaluate(Box2D.Collision.b2TimeOfImpact.s_xfA,Box2D.Collision.b2TimeOfImpact.s_xfB);if(separation&lt;=0){alpha=1;break}if(iter==0){if(separation&gt;radius){target=Math.max(radius-tolerance,.75*radius)}else{target=Math.max(separation-tolerance,.02*radius)}}if(separation-target&lt;.5*tolerance){if(iter==0){alpha=1;break}break}var newAlpha=alpha;{var x1=alpha;var x2=1;var f1=separation;sweepA.GetTransform(Box2D.Collision.b2TimeOfImpact.s_xfA,x2);sweepB.GetTransform(Box2D.Collision.b2TimeOfImpact.s_xfB,x2);var f2=Box2D.Collision.b2TimeOfImpact.s_fcn.Evaluate(Box2D.Collision.b2TimeOfImpact.s_xfA,Box2D.Collision.b2TimeOfImpact.s_xfB);if(f2&gt;=target){alpha=1;break}var rootIterCount=0;for(;;){var x=0;if(rootIterCount&amp;1){x=x1+(target-f1)*(x2-x1)/(f2-f1)}else{x=.5*(x1+x2)}sweepA.GetTransform(Box2D.Collision.b2TimeOfImpact.s_xfA,x);sweepB.GetTransform(Box2D.Collision.b2TimeOfImpact.s_xfB,x);var f=Box2D.Collision.b2TimeOfImpact.s_fcn.Evaluate(Box2D.Collision.b2TimeOfImpact.s_xfA,Box2D.Collision.b2TimeOfImpact.s_xfB);if(Math.abs(f-target)&lt;.025*tolerance){newAlpha=x;break}if(f&gt;target){x1=x;f1=f}else{x2=x;f2=f}rootIterCount++;Box2D.Collision.b2TimeOfImpact.b2_toiRootIters++;if(rootIterCount==50){break}}Box2D.Collision.b2TimeOfImpact.b2_toiMaxRootIters=Math.max(Box2D.Collision.b2TimeOfImpact.b2_toiMaxRootIters,rootIterCount)}if(newAlpha&lt;(1+100*Number.MIN_VALUE)*alpha){break}alpha=newAlpha;iter++;Box2D.Collision.b2TimeOfImpact.b2_toiIters++;if(iter==k_maxIterations){break}}Box2D.Collision.b2TimeOfImpact.b2_toiMaxIters=Math.max(Box2D.Collision.b2TimeOfImpact.b2_toiMaxIters,iter);return alpha};Box2D.Collision.b2TimeOfImpact.b2_toiCalls=0;Box2D.Collision.b2TimeOfImpact.b2_toiIters=0;Box2D.Collision.b2TimeOfImpact.b2_toiMaxIters=0;Box2D.Collision.b2TimeOfImpact.b2_toiRootIters=0;Box2D.Collision.b2TimeOfImpact.b2_toiMaxRootIters=0;Box2D.Collision.b2TimeOfImpact.s_cache=new Box2D.Collision.b2SimplexCache;Box2D.Collision.b2TimeOfImpact.s_distanceInput=new Box2D.Collision.b2DistanceInput;Box2D.Collision.b2TimeOfImpact.s_xfA=new Box2D.Common.Math.b2Transform;Box2D.Collision.b2TimeOfImpact.s_xfB=new Box2D.Common.Math.b2Transform;Box2D.Collision.b2TimeOfImpact.s_fcn=new Box2D.Collision.b2SeparationFunction;Box2D.Collision.b2TimeOfImpact.s_distanceOutput=new Box2D.Collision.b2DistanceOutput;Box2D.Collision.b2WorldManifold=function(){this.m_normal=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_points=[];this.m_pointCount=0;for(var i=0;i&lt;Box2D.Common.b2Settings.b2_maxManifoldPoints;i++){this.m_points[i]=Box2D.Common.Math.b2Vec2.Get(0,0)}};Box2D.Collision.b2WorldManifold.prototype.Initialize=function(manifold,xfA,radiusA,xfB,radiusB){if(manifold.m_pointCount==0){return}var i=0;var tVec;var tMat;var normalX=0;var normalY=0;var planePointX=0;var planePointY=0;var clipPointX=0;var clipPointY=0;switch(manifold.m_type){case Box2D.Collision.b2Manifold.e_circles:tMat=xfA.R;tVec=manifold.m_localPoint;var pointAX=xfA.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var pointAY=xfA.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=xfB.R;tVec=manifold.m_points[0].m_localPoint;var pointBX=xfB.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var pointBY=xfB.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;var dX=pointBX-pointAX;var dY=pointBY-pointAY;var d2=dX*dX+dY*dY;if(d2&gt;Box2D.Common.b2Settings.MIN_VALUE_SQUARED){var d=Math.sqrt(d2);this.m_normal.x=dX/d;this.m_normal.y=dY/d}else{this.m_normal.x=1;this.m_normal.y=0}var cAX=pointAX+radiusA*this.m_normal.x;var cAY=pointAY+radiusA*this.m_normal.y;var cBX=pointBX-radiusB*this.m_normal.x;var cBY=pointBY-radiusB*this.m_normal.y;this.m_points[0].x=.5*(cAX+cBX);this.m_points[0].y=.5*(cAY+cBY);break;case Box2D.Collision.b2Manifold.e_faceA:tMat=xfA.R;tVec=manifold.m_localPlaneNormal;normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=xfA.R;tVec=manifold.m_localPoint;planePointX=xfA.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;planePointY=xfA.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;this.m_normal.x=normalX;this.m_normal.y=normalY;for(i=0;i&lt;manifold.m_pointCount;i++){tMat=xfB.R;tVec=manifold.m_points[i].m_localPoint;clipPointX=xfB.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;clipPointY=xfB.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;this.m_points[i].x=clipPointX+.5*(radiusA-(clipPointX-planePointX)*normalX-(clipPointY-planePointY)*normalY-radiusB)*normalX;this.m_points[i].y=clipPointY+.5*(radiusA-(clipPointX-planePointX)*normalX-(clipPointY-planePointY)*normalY-radiusB)*normalY}break;case Box2D.Collision.b2Manifold.e_faceB:tMat=xfB.R;tVec=manifold.m_localPlaneNormal;normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=xfB.R;tVec=manifold.m_localPoint;planePointX=xfB.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;planePointY=xfB.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;this.m_normal.x=-normalX;this.m_normal.y=-normalY;for(i=0;i&lt;manifold.m_pointCount;i++){tMat=xfA.R;tVec=manifold.m_points[i].m_localPoint;clipPointX=xfA.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;clipPointY=xfA.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;this.m_points[i].x=clipPointX+.5*(radiusB-(clipPointX-planePointX)*normalX-(clipPointY-planePointY)*normalY-radiusA)*normalX;this.m_points[i].y=clipPointY+.5*(radiusB-(clipPointX-planePointX)*normalX-(clipPointY-planePointY)*normalY-radiusA)*normalY}break}};Box2D.Collision.Shapes.b2Shape=function(){this.m_radius=Box2D.Common.b2Settings.b2_linearSlop};Box2D.Collision.Shapes.b2Shape.prototype.GetTypeName=Box2D.abstractMethod;Box2D.Collision.Shapes.b2Shape.prototype.Copy=Box2D.abstractMethod;Box2D.Collision.Shapes.b2Shape.prototype.Set=function(other){this.m_radius=other.m_radius};Box2D.Collision.Shapes.b2Shape.prototype.Destroy=function(){};Box2D.Collision.Shapes.b2Shape.prototype.TestPoint=Box2D.abstractMethod;Box2D.Collision.Shapes.b2Shape.prototype.RayCast=Box2D.abstractMethod;Box2D.Collision.Shapes.b2Shape.prototype.ComputeAABB=Box2D.abstractMethod;Box2D.Collision.Shapes.b2Shape.prototype.ComputeMass=Box2D.abstractMethod;Box2D.Collision.Shapes.b2Shape.prototype.ComputeSubmergedArea=Box2D.abstractMethod;Box2D.Collision.Shapes.b2Shape.prototype.SetDistanceProxy=Box2D.abstractMethod;Box2D.Collision.Shapes.b2Shape.TestOverlap=function(shape1,transform1,shape2,transform2){var input=Box2D.Collision.b2DistanceInput.Get();input.proxyA=Box2D.Collision.b2DistanceProxy.Get();input.proxyA.Set(shape1);input.proxyB=Box2D.Collision.b2DistanceProxy.Get();input.proxyB.Set(shape2);input.transformA=transform1;input.transformB=transform2;input.useRadii=true;var simplexCache=Box2D.Collision.b2SimplexCache.Get();simplexCache.count=0;var output=Box2D.Collision.b2DistanceOutput.Get();Box2D.Collision.b2Distance.Distance(output,simplexCache,input);Box2D.Collision.b2SimplexCache.Free(simplexCache);Box2D.Collision.b2DistanceProxy.Free(input.proxyA);Box2D.Collision.b2DistanceProxy.Free(input.proxyB);Box2D.Collision.b2DistanceInput.Free(input);Box2D.Collision.b2DistanceOutput.Free(output);return output.distance&lt;10*Number.MIN_VALUE};Box2D.Collision.Shapes.b2Shape.prototype.GetRadius=function(){return this.m_radius};Box2D.Collision.Shapes.b2Shape.e_startsInsideCollide=-1;Box2D.Collision.Shapes.b2Shape.e_missCollide=0;Box2D.Collision.Shapes.b2Shape.e_hitCollide=1;Box2D.Collision.Shapes.b2CircleShape=function(radius){Box2D.Collision.Shapes.b2Shape.call(this);this.m_radius=radius;this.m_radiusSquared=radius*radius;this.m_p=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_vertices=Box2D.Array.Get();this.m_vertices[0]=this.m_p};Box2D.inherits(Box2D.Collision.Shapes.b2CircleShape,Box2D.Collision.Shapes.b2Shape);Box2D.Collision.Shapes.b2CircleShape._freeCache=[];Box2D.Collision.Shapes.b2CircleShape.Get=function(radius){var cache=this._freeCache;var o;if(cache.length&gt;0){o=cache.pop();o.SetRadius(radius)}else{o=new this(radius)}return o};Box2D.Collision.Shapes.b2CircleShape.Free=function(o){this._freeCache.push(o)};Box2D.Collision.Shapes.b2CircleShape.prototype.GetTypeName=function(){return Box2D.Collision.Shapes.b2CircleShape.NAME};Box2D.Collision.Shapes.b2CircleShape.prototype.Copy=function(){var s=Box2D.Collision.Shapes.b2CircleShape.Get(this.m_radius);s.Set(this);return s};Box2D.Collision.Shapes.b2CircleShape.prototype.Set=function(other){Box2D.Collision.Shapes.b2Shape.prototype.Set.call(this,other);if(other instanceof Box2D.Collision.Shapes.b2CircleShape){this.m_p.SetV(other.m_p)}};Box2D.Collision.Shapes.b2CircleShape.prototype.Destroy=function(){Box2D.Collision.Shapes.b2CircleShape.Free(this)};Box2D.Collision.Shapes.b2CircleShape.prototype.TestPoint=function(transform,p){var dX=p.x-(transform.position.x+(transform.R.col1.x*this.m_p.x+transform.R.col2.x*this.m_p.y));var dY=p.y-(transform.position.y+(transform.R.col1.y*this.m_p.x+transform.R.col2.y*this.m_p.y));return dX*dX+dY*dY&lt;=this.m_radiusSquared};Box2D.Collision.Shapes.b2CircleShape.prototype.RayCast=function(output,input,transform){var tMat=transform.R;var positionX=transform.position.x+(tMat.col1.x*this.m_p.x+tMat.col2.x*this.m_p.y);var positionY=transform.position.y+(tMat.col1.y*this.m_p.x+tMat.col2.y*this.m_p.y);var sX=input.p1.x-positionX;var sY=input.p1.y-positionY;var b=sX*sX+sY*sY-this.m_radiusSquared;var rX=input.p2.x-input.p1.x;var rY=input.p2.y-input.p1.y;var c=sX*rX+sY*rY;var rr=rX*rX+rY*rY;var sigma=c*c-rr*b;if(sigma&lt;0||rr&lt;Number.MIN_VALUE){return false}var a=-(c+Math.sqrt(sigma));if(0&lt;=a&amp;&amp;a&lt;=input.maxFraction*rr){a/=rr;output.fraction=a;output.normal.x=sX+a*rX;output.normal.y=sY+a*rY;output.normal.Normalize();return true}return false};Box2D.Collision.Shapes.b2CircleShape.prototype.ComputeAABB=function(aabb,transform){var tMat=transform.R;var transformPosition=transform.position;var col1=tMat.col1;var col2=tMat.col2;var p=this.m_p;var x=p.x;var y=p.y;var pX=transformPosition.x+(col1.x*x+col2.x*y);var pY=transformPosition.y+(col1.y*x+col2.y*y);var lowerBound=aabb.lowerBound;var upperBound=aabb.upperBound;var radius=this.m_radius;lowerBound.x=pX-radius;lowerBound.y=pY-radius;upperBound.x=pX+radius;upperBound.y=pY+radius};Box2D.Collision.Shapes.b2CircleShape.prototype.ComputeMass=function(massData,density){var mass=density*Math.PI*this.m_radiusSquared;massData.SetV(mass,this.m_p,mass*(.5*this.m_radiusSquared+(this.m_p.x*this.m_p.x+this.m_p.y*this.m_p.y)))};Box2D.Collision.Shapes.b2CircleShape.prototype.ComputeSubmergedArea=function(normal,offset,xf,c){var p=Box2D.Common.Math.b2Math.MulX(xf,this.m_p);var l=-(Box2D.Common.Math.b2Math.Dot(normal,p)-offset);if(l&lt;-this.m_radius+Number.MIN_VALUE){Box2D.Common.Math.b2Vec2.Free(p);return 0}if(l&gt;this.m_radius){Box2D.Common.Math.b2Vec2.Free(p);c.SetV(p);return Math.PI*this.m_radiusSquared}var l2=l*l;var area=this.m_radiusSquared*(Math.asin(l/this.m_radius)+Math.PI/2)+l*Math.sqrt(this.m_radiusSquared-l2);var com=-2/3*Math.pow(this.m_radiusSquared-l2,1.5)/area;c.x=p.x+normal.x*com;c.y=p.y+normal.y*com;Box2D.Common.Math.b2Vec2.Free(p);return area};Box2D.Collision.Shapes.b2CircleShape.prototype.SetDistanceProxy=function(proxy){proxy.SetValues(1,this.m_radius,this.m_vertices)};Box2D.Collision.Shapes.b2CircleShape.prototype.GetLocalPosition=function(){return this.m_p};Box2D.Collision.Shapes.b2CircleShape.prototype.SetLocalPosition=function(position){this.m_p.SetV(position)};Box2D.Collision.Shapes.b2CircleShape.prototype.GetRadius=function(){return this.m_radius};Box2D.Collision.Shapes.b2CircleShape.prototype.SetRadius=function(radius){this.m_radius=radius;this.m_radiusSquared=radius*radius};Box2D.Collision.Shapes.b2CircleShape.NAME="b2CircleShape";Box2D.Collision.Shapes.b2EdgeChainDef=function(){this.vertexCount=0;this.isALoop=true;this.vertices=Box2D.Array.Get()};Box2D.Collision.Shapes.b2EdgeShape=function(v1,v2){Box2D.Collision.Shapes.b2Shape.call(this);this.m_prevEdge=null;this.m_nextEdge=null;this.m_v1=v1;this.m_v2=v2;this.m_direction=Box2D.Common.Math.b2Vec2.Get(this.m_v2.x-this.m_v1.x,this.m_v2.y-this.m_v1.y);this.m_length=this.m_direction.Normalize();this.m_normal=Box2D.Common.Math.b2Vec2.Get(this.m_direction.y,-this.m_direction.x);this.m_coreV1=Box2D.Common.Math.b2Vec2.Get(-Box2D.Common.b2Settings.b2_toiSlop*(this.m_normal.x-this.m_direction.x)+this.m_v1.x,-Box2D.Common.b2Settings.b2_toiSlop*(this.m_normal.y-this.m_direction.y)+this.m_v1.y);this.m_coreV2=Box2D.Common.Math.b2Vec2.Get(-Box2D.Common.b2Settings.b2_toiSlop*(this.m_normal.x+this.m_direction.x)+this.m_v2.x,-Box2D.Common.b2Settings.b2_toiSlop*(this.m_normal.y+this.m_direction.y)+this.m_v2.y);this.m_cornerDir1=this.m_normal;this.m_cornerDir2=Box2D.Common.Math.b2Vec2.Get(-this.m_normal.x,-this.m_normal.y);this.m_cornerConvex1=false;this.m_cornerConvex2=false};Box2D.inherits(Box2D.Collision.Shapes.b2EdgeShape,Box2D.Collision.Shapes.b2Shape);Box2D.Collision.Shapes.b2EdgeShape.prototype.GetTypeName=function(){return Box2D.Collision.Shapes.b2EdgeShape.NAME};Box2D.Collision.Shapes.b2EdgeShape.prototype.TestPoint=function(transform,p){return false};Box2D.Collision.Shapes.b2EdgeShape.prototype.RayCast=function(output,input,transform){var rX=input.p2.x-input.p1.x;var rY=input.p2.y-input.p1.y;var tMat=transform.R;var v1X=transform.position.x+(tMat.col1.x*this.m_v1.x+tMat.col2.x*this.m_v1.y);var v1Y=transform.position.y+(tMat.col1.y*this.m_v1.x+tMat.col2.y*this.m_v1.y);var nX=transform.position.y+(tMat.col1.y*this.m_v2.x+tMat.col2.y*this.m_v2.y)-v1Y;var nY=-(transform.position.x+(tMat.col1.x*this.m_v2.x+tMat.col2.x*this.m_v2.y)-v1X);var k_slop=100*Number.MIN_VALUE;var denom=-(rX*nX+rY*nY);if(denom&gt;k_slop){var bX=input.p1.x-v1X;var bY=input.p1.y-v1Y;var a=bX*nX+bY*nY;if(0&lt;=a&amp;&amp;a&lt;=input.maxFraction*denom){var mu2=-rX*bY+rY*bX;if(-k_slop*denom&lt;=mu2&amp;&amp;mu2&lt;=denom*(1+k_slop)){a/=denom;output.fraction=a;var nLen=Math.sqrt(nX*nX+nY*nY);output.normal.x=nX/nLen;output.normal.y=nY/nLen;return true}}}return false};Box2D.Collision.Shapes.b2EdgeShape.prototype.ComputeAABB=function(aabb,transform){var tMat=transform.R;var v1X=transform.position.x+(tMat.col1.x*this.m_v1.x+tMat.col2.x*this.m_v1.y);var v1Y=transform.position.y+(tMat.col1.y*this.m_v1.x+tMat.col2.y*this.m_v1.y);var v2X=transform.position.x+(tMat.col1.x*this.m_v2.x+tMat.col2.x*this.m_v2.y);var v2Y=transform.position.y+(tMat.col1.y*this.m_v2.x+tMat.col2.y*this.m_v2.y);if(v1X&lt;v2X){aabb.lowerBound.x=v1X;aabb.upperBound.x=v2X}else{aabb.lowerBound.x=v2X;aabb.upperBound.x=v1X}if(v1Y&lt;v2Y){aabb.lowerBound.y=v1Y;aabb.upperBound.y=v2Y}else{aabb.lowerBound.y=v2Y;aabb.upperBound.y=v1Y}};Box2D.Collision.Shapes.b2EdgeShape.prototype.ComputeMass=function(massData,density){massData.mass=0;massData.center.SetV(this.m_v1);massData.I=0};Box2D.Collision.Shapes.b2EdgeShape.prototype.ComputeSubmergedArea=function(normal,offset,xf,c){if(offset===undefined)offset=0;var v0=Box2D.Common.Math.b2Vec2.Get(normal.x*offset,normal.y*offset);var v1=Box2D.Common.Math.b2Math.MulX(xf,this.m_v1);var v2=Box2D.Common.Math.b2Math.MulX(xf,this.m_v2);var d1=Box2D.Common.Math.b2Math.Dot(normal,v1)-offset;var d2=Box2D.Common.Math.b2Math.Dot(normal,v2)-offset;if(d1&gt;0){if(d2&gt;0){return 0}else{v1.x=-d2/(d1-d2)*v1.x+d1/(d1-d2)*v2.x;v1.y=-d2/(d1-d2)*v1.y+d1/(d1-d2)*v2.y}}else{if(d2&gt;0){v2.x=-d2/(d1-d2)*v1.x+d1/(d1-d2)*v2.x;v2.y=-d2/(d1-d2)*v1.y+d1/(d1-d2)*v2.y}}c.x=(v0.x+v1.x+v2.x)/3;c.y=(v0.y+v1.y+v2.y)/3;return.5*((v1.x-v0.x)*(v2.y-v0.y)-(v1.y-v0.y)*(v2.x-v0.x))};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetLength=function(){return this.m_length};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetVertex1=function(){return this.m_v1};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetVertex2=function(){return this.m_v2};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetCoreVertex1=function(){return this.m_coreV1};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetCoreVertex2=function(){return this.m_coreV2};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetNormalVector=function(){return this.m_normal};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetDirectionVector=function(){return this.m_direction};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetCorner1Vector=function(){return this.m_cornerDir1};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetCorner2Vector=function(){return this.m_cornerDir2};Box2D.Collision.Shapes.b2EdgeShape.prototype.Corner1IsConvex=function(){return this.m_cornerConvex1};Box2D.Collision.Shapes.b2EdgeShape.prototype.Corner2IsConvex=function(){return this.m_cornerConvex2};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetFirstVertex=function(xf){var tMat=xf.R;return Box2D.Common.Math.b2Vec2.Get(xf.position.x+(tMat.col1.x*this.m_coreV1.x+tMat.col2.x*this.m_coreV1.y),xf.position.y+(tMat.col1.y*this.m_coreV1.x+tMat.col2.y*this.m_coreV1.y))};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetNextEdge=function(){return this.m_nextEdge};Box2D.Collision.Shapes.b2EdgeShape.prototype.GetPrevEdge=function(){return this.m_prevEdge};Box2D.Collision.Shapes.b2EdgeShape.prototype.Support=function(xf,dX,dY){var tMat=xf.R;var v1X=xf.position.x+(tMat.col1.x*this.m_coreV1.x+tMat.col2.x*this.m_coreV1.y);var v1Y=xf.position.y+(tMat.col1.y*this.m_coreV1.x+tMat.col2.y*this.m_coreV1.y);var v2X=xf.position.x+(tMat.col1.x*this.m_coreV2.x+tMat.col2.x*this.m_coreV2.y);var v2Y=xf.position.y+(tMat.col1.y*this.m_coreV2.x+tMat.col2.y*this.m_coreV2.y);if(v1X*dX+v1Y*dY&gt;v2X*dX+v2Y*dY){return Box2D.Common.Math.b2Vec2.Get(v1X,v1Y)}else{return Box2D.Common.Math.b2Vec2.Get(v2X,v2Y)}};Box2D.Collision.Shapes.b2EdgeShape.prototype.SetPrevEdge=function(edge,core,cornerDir,convex){this.m_prevEdge=edge;this.m_coreV1=core;this.m_cornerDir1=cornerDir;this.m_cornerConvex1=convex};Box2D.Collision.Shapes.b2EdgeShape.prototype.SetNextEdge=function(edge,core,cornerDir,convex){this.m_nextEdge=edge;this.m_coreV2=core;this.m_cornerDir2=cornerDir;this.m_cornerConvex2=convex};Box2D.Collision.Shapes.b2EdgeShape.NAME="b2EdgeShape";Box2D.Collision.Shapes.b2MassData=function(){this.mass=0;this.center=Box2D.Common.Math.b2Vec2.Get(0,0);this.I=0};Box2D.Collision.Shapes.b2MassData._freeCache=[];Box2D.Collision.Shapes.b2MassData.Get=function(){if(Box2D.Collision.Shapes.b2MassData._freeCache.length&gt;0){var md=Box2D.Collision.Shapes.b2MassData._freeCache.pop();md.mass=0;md.center.SetZero();md.I=0;return md}return new Box2D.Collision.Shapes.b2MassData};Box2D.Collision.Shapes.b2MassData.Free=function(md){if(md!=null){Box2D.Collision.Shapes.b2MassData._freeCache.push(md)}};Box2D.Collision.Shapes.b2MassData.prototype.SetV=function(mass,center,I){this.mass=mass;this.center.SetV(center);this.I=I};Box2D.Collision.Shapes.b2MassData.prototype.Set=function(mass,x,y,I){this.mass=mass;this.center.Set(x,y);this.I=I};Box2D.Collision.Shapes.b2PolygonShape=function(){Box2D.Collision.Shapes.b2Shape.call(this);this.m_centroid=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_vertices=Box2D.Array.Get();this.m_normals=Box2D.Array.Get()};Box2D.inherits(Box2D.Collision.Shapes.b2PolygonShape,Box2D.Collision.Shapes.b2Shape);Box2D.Collision.Shapes.b2PolygonShape._freeCache=[];Box2D.Collision.Shapes.b2PolygonShape.Get=function(){var cache=this._freeCache;var o;if(cache.length&gt;0){o=cache.pop()}else{o=new this}return o};Box2D.Collision.Shapes.b2PolygonShape.Free=function(o){this._freeCache.push(o)};Box2D.Collision.Shapes.b2PolygonShape.prototype.GetTypeName=function(){return Box2D.Collision.Shapes.b2PolygonShape.NAME};Box2D.Collision.Shapes.b2PolygonShape.prototype.Copy=function(){var s=Box2D.Collision.Shapes.b2PolygonShape.Get();s.Set(this);return s};Box2D.Collision.Shapes.b2PolygonShape.prototype.Set=function(other){Box2D.Collision.Shapes.b2Shape.prototype.Set.call(this,other);if(other instanceof Box2D.Collision.Shapes.b2PolygonShape){this.m_centroid.SetV(other.m_centroid);this.m_vertexCount=other.m_vertexCount;this.Reserve(this.m_vertexCount);for(var i=0;i&lt;this.m_vertexCount;i++){this.m_vertices[i].SetV(other.m_vertices[i]);this.m_normals[i].SetV(other.m_normals[i])}}};Box2D.Collision.Shapes.b2PolygonShape.prototype.Destroy=function(){Box2D.Collision.Shapes.b2PolygonShape.Free(this)};Box2D.Collision.Shapes.b2PolygonShape.prototype.SetAsArray=function(vertices){this.SetAsVector(vertices)};Box2D.Collision.Shapes.b2PolygonShape.AsArray=function(vertices){var polygonShape=new Box2D.Collision.Shapes.b2PolygonShape;polygonShape.SetAsArray(vertices);return polygonShape};Box2D.Collision.Shapes.b2PolygonShape.prototype.SetAsVector=function(vertices){var vertexCount=vertices.length;Box2D.Common.b2Settings.b2Assert(3&lt;=vertexCount);this.m_vertexCount=vertexCount;this.Reserve(vertexCount);var i=0;for(i=0;i&lt;vertexCount;i++){this.m_vertices[i].SetV(vertices[i])}for(i=0;i&lt;vertexCount;++i){var i1=i;var i2=i+1&lt;vertexCount?i+1:0;var edge=Box2D.Common.Math.b2Math.SubtractVV(this.m_vertices[i2],this.m_vertices[i1]);Box2D.Common.b2Settings.b2Assert(edge.LengthSquared()&gt;Number.MIN_VALUE);var edgeCross=Box2D.Common.Math.b2Math.CrossVF(edge,1);Box2D.Common.Math.b2Vec2.Free(edge);this.m_normals[i].SetV(edgeCross);Box2D.Common.Math.b2Vec2.Free(edgeCross);this.m_normals[i].Normalize()}this.m_centroid=Box2D.Collision.Shapes.b2PolygonShape.ComputeCentroid(this.m_vertices,this.m_vertexCount)};Box2D.Collision.Shapes.b2PolygonShape.AsVector=function(vertices){var polygonShape=new Box2D.Collision.Shapes.b2PolygonShape;polygonShape.SetAsVector(vertices);return polygonShape};Box2D.Collision.Shapes.b2PolygonShape.prototype.SetAsBox=function(hx,hy){this.m_vertexCount=4;this.Reserve(4);this.m_vertices[0].Set(-hx,-hy);this.m_vertices[1].Set(hx,-hy);this.m_vertices[2].Set(hx,hy);this.m_vertices[3].Set(-hx,hy);this.m_normals[0].Set(0,-1);this.m_normals[1].Set(1,0);this.m_normals[2].Set(0,1);this.m_normals[3].Set(-1,0);this.m_centroid.SetZero()};Box2D.Collision.Shapes.b2PolygonShape.AsBox=function(hx,hy){var polygonShape=new Box2D.Collision.Shapes.b2PolygonShape;polygonShape.SetAsBox(hx,hy);return polygonShape};Box2D.Collision.Shapes.b2PolygonShape.prototype.SetAsOrientedBox=function(hx,hy,center,angle){this.m_vertexCount=4;this.Reserve(4);this.m_vertices[0].Set(-hx,-hy);this.m_vertices[1].Set(hx,-hy);this.m_vertices[2].Set(hx,hy);this.m_vertices[3].Set(-hx,hy);this.m_normals[0].Set(0,-1);this.m_normals[1].Set(1,0);this.m_normals[2].Set(0,1);this.m_normals[3].Set(-1,0);this.m_centroid=center;var mat=Box2D.Common.Math.b2Mat22.Get();mat.Set(angle);var xf=new Box2D.Common.Math.b2Transform(center,mat);for(var i=0;i&lt;this.m_vertexCount;++i){this.m_vertices[i]=Box2D.Common.Math.b2Math.MulX(xf,this.m_vertices[i]);this.m_normals[i]=Box2D.Common.Math.b2Math.MulMV(xf.R,this.m_normals[i])}};Box2D.Collision.Shapes.b2PolygonShape.AsOrientedBox=function(hx,hy,center,angle){var polygonShape=new Box2D.Collision.Shapes.b2PolygonShape;polygonShape.SetAsOrientedBox(hx,hy,center,angle);return polygonShape};Box2D.Collision.Shapes.b2PolygonShape.prototype.SetAsEdge=function(v1,v2){this.m_vertexCount=2;this.Reserve(2);this.m_vertices[0].SetV(v1);this.m_vertices[1].SetV(v2);this.m_centroid.x=.5*(v1.x+v2.x);this.m_centroid.y=.5*(v1.y+v2.y);var d=Box2D.Common.Math.b2Math.SubtractVV(v2,v1);var crossD=Box2D.Common.Math.b2Math.CrossVF(d,1);Box2D.Common.Math.b2Vec2.Free(d);this.m_normals[0]=crossD;this.m_normals[0].Normalize();this.m_normals[1].x=-this.m_normals[0].x;this.m_normals[1].y=-this.m_normals[0].y};Box2D.Collision.Shapes.b2PolygonShape.AsEdge=function(v1,v2){var polygonShape=new Box2D.Collision.Shapes.b2PolygonShape;polygonShape.SetAsEdge(v1,v2);return polygonShape};Box2D.Collision.Shapes.b2PolygonShape.prototype.TestPoint=function(xf,p){var tVec;var tMat=xf.R;var tX=p.x-xf.position.x;var tY=p.y-xf.position.y;var pLocalX=tX*tMat.col1.x+tY*tMat.col1.y;var pLocalY=tX*tMat.col2.x+tY*tMat.col2.y;for(var i=0;i&lt;this.m_vertexCount;++i){tVec=this.m_vertices[i];tX=pLocalX-tVec.x;tY=pLocalY-tVec.y;tVec=this.m_normals[i];var dot=tVec.x*tX+tVec.y*tY;if(dot&gt;0){return false}}return true};Box2D.Collision.Shapes.b2PolygonShape.prototype.RayCast=function(output,input,transform){var lower=0;var upper=input.maxFraction;var tX=0;var tY=0;var tMat;var tVec;tX=input.p1.x-transform.position.x;tY=input.p1.y-transform.position.y;tMat=transform.R;var p1X=tX*tMat.col1.x+tY*tMat.col1.y;var p1Y=tX*tMat.col2.x+tY*tMat.col2.y;tX=input.p2.x-transform.position.x;tY=input.p2.y-transform.position.y;tMat=transform.R;var p2X=tX*tMat.col1.x+tY*tMat.col1.y;var p2Y=tX*tMat.col2.x+tY*tMat.col2.y;var dX=p2X-p1X;var dY=p2Y-p1Y;var index=-1;for(var i=0;i&lt;this.m_vertexCount;++i){tVec=this.m_vertices[i];tX=tVec.x-p1X;tY=tVec.y-p1Y;tVec=this.m_normals[i];var numerator=tVec.x*tX+tVec.y*tY;var denominator=tVec.x*dX+tVec.y*dY;if(denominator==0){if(numerator&lt;0){return false}}else{if(denominator&lt;0&amp;&amp;numerator&lt;lower*denominator){lower=numerator/denominator;index=i}else if(denominator&gt;0&amp;&amp;numerator&lt;upper*denominator){upper=numerator/denominator}}if(upper&lt;lower-Number.MIN_VALUE){return false}}if(index&gt;=0){output.fraction=lower;tMat=transform.R;tVec=this.m_normals[index];output.normal.x=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;output.normal.y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;return true}return false};Box2D.Collision.Shapes.b2PolygonShape.prototype.ComputeAABB=function(aabb,xf){var tMat=xf.R;var tVec=this.m_vertices[0];var lowerX=xf.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var lowerY=xf.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);var upperX=lowerX;var upperY=lowerY;for(var i=1;i&lt;this.m_vertexCount;++i){tVec=this.m_vertices[i];var vX=xf.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var vY=xf.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);lowerX=lowerX&lt;vX?lowerX:vX;lowerY=lowerY&lt;vY?lowerY:vY;upperX=upperX&gt;vX?upperX:vX;upperY=upperY&gt;vY?upperY:vY}aabb.lowerBound.x=lowerX-this.m_radius;aabb.lowerBound.y=lowerY-this.m_radius;aabb.upperBound.x=upperX+this.m_radius;aabb.upperBound.y=upperY+this.m_radius};Box2D.Collision.Shapes.b2PolygonShape.prototype.ComputeMass=function(massData,density){if(this.m_vertexCount==2){massData.center.x=.5*(this.m_vertices[0].x+this.m_vertices[1].x);massData.center.y=.5*(this.m_vertices[0].y+this.m_vertices[1].y);massData.mass=0;massData.I=0;return}var centerX=0;var centerY=0;var area=0;var I=0;var p1X=0;var p1Y=0;var k_inv3=1/3;for(var i=0;i&lt;this.m_vertexCount;++i){var p2=this.m_vertices[i];var p3=i+1&lt;this.m_vertexCount?this.m_vertices[i+1]:this.m_vertices[0];var e1X=p2.x-p1X;var e1Y=p2.y-p1Y;var e2X=p3.x-p1X;var e2Y=p3.y-p1Y;var D=e1X*e2Y-e1Y*e2X;var triangleArea=.5*D;area+=triangleArea;centerX+=triangleArea*k_inv3*(p1X+p2.x+p3.x);centerY+=triangleArea*k_inv3*(p1Y+p2.y+p3.y);var px=p1X;var py=p1Y;var ex1=e1X;var ey1=e1Y;var ex2=e2X;var ey2=e2Y;var intx2=k_inv3*(.25*(ex1*ex1+ex2*ex1+ex2*ex2)+(px*ex1+px*ex2))+.5*px*px;var inty2=k_inv3*(.25*(ey1*ey1+ey2*ey1+ey2*ey2)+(py*ey1+py*ey2))+.5*py*py;I+=D*(intx2+inty2)}centerX*=1/area;centerY*=1/area;massData.Set(density*area,centerX,centerY,density*I)};Box2D.Collision.Shapes.b2PolygonShape.prototype.ComputeSubmergedArea=function(normal,offset,xf,c){var normalL=Box2D.Common.Math.b2Math.MulTMV(xf.R,normal);var offsetL=offset-Box2D.Common.Math.b2Math.Dot(normal,xf.position);var depths=Box2D.Array.Get();var diveCount=0;var intoIndex=-1;var outoIndex=-1;var lastSubmerged=false;var i=0;for(i=0;i&lt;this.m_vertexCount;++i){depths[i]=Box2D.Common.Math.b2Math.Dot(normalL,this.m_vertices[i])-offsetL;var isSubmerged=depths[i]&lt;-Number.MIN_VALUE;if(i&gt;0){if(isSubmerged){if(!lastSubmerged){intoIndex=i-1;diveCount++}}else{if(lastSubmerged){outoIndex=i-1;diveCount++}}}lastSubmerged=isSubmerged}Box2D.Common.Math.b2Vec2.Free(normalL);switch(diveCount){case 0:if(lastSubmerged){var md=Box2D.Collision.Shapes.b2MassData.Get();this.ComputeMass(md,1);var newV=Box2D.Common.Math.b2Math.MulX(xf,md.center);c.SetV(newV);Box2D.Common.Math.b2Vec2.Free(newV);var mass=md.mass;Box2D.Collision.Shapes.b2MassData.Free(md);return mass}else{return 0}break;case 1:if(intoIndex==-1){intoIndex=this.m_vertexCount-1}else{outoIndex=this.m_vertexCount-1}break}var intoIndex2=(intoIndex+1)%this.m_vertexCount;var outoIndex2=(outoIndex+1)%this.m_vertexCount;var intoLamdda=(0-depths[intoIndex])/(depths[intoIndex2]-depths[intoIndex]);var outoLamdda=(0-depths[outoIndex])/(depths[outoIndex2]-depths[outoIndex]);var intoVec=Box2D.Common.Math.b2Vec2.Get(this.m_vertices[intoIndex].x*(1-intoLamdda)+this.m_vertices[intoIndex2].x*intoLamdda,this.m_vertices[intoIndex].y*(1-intoLamdda)+this.m_vertices[intoIndex2].y*intoLamdda);var outoVec=Box2D.Common.Math.b2Vec2.Get(this.m_vertices[outoIndex].x*(1-outoLamdda)+this.m_vertices[outoIndex2].x*outoLamdda,this.m_vertices[outoIndex].y*(1-outoLamdda)+this.m_vertices[outoIndex2].y*outoLamdda);var area=0;var center=Box2D.Common.Math.b2Vec2.Get(0,0);var p2=this.m_vertices[intoIndex2];var p3;i=intoIndex2;while(i!=outoIndex2){i=(i+1)%this.m_vertexCount;if(i==outoIndex2)p3=outoVec;else p3=this.m_vertices[i];var triangleArea=.5*((p2.x-intoVec.x)*(p3.y-intoVec.y)-(p2.y-intoVec.y)*(p3.x-intoVec.x));area+=triangleArea;center.x+=triangleArea*(intoVec.x+p2.x+p3.x)/3;center.y+=triangleArea*(intoVec.y+p2.y+p3.y)/3;p2=p3}Box2D.Common.Math.b2Vec2.Free(intoVec);Box2D.Common.Math.b2Vec2.Free(outoVec);center.Multiply(1/area);var newV=Box2D.Common.Math.b2Math.MulX(xf,center);Box2D.Common.Math.b2Vec2.Free(center);c.SetV(newV);Box2D.Common.Math.b2Vec2.Free(newV);return area};Box2D.Collision.Shapes.b2PolygonShape.prototype.SetDistanceProxy=function(proxy){proxy.SetValues(this.m_vertexCount,this.m_radius,this.m_vertices)};Box2D.Collision.Shapes.b2PolygonShape.prototype.GetVertexCount=function(){return this.m_vertexCount};Box2D.Collision.Shapes.b2PolygonShape.prototype.GetVertices=function(){return this.m_vertices};Box2D.Collision.Shapes.b2PolygonShape.prototype.GetVertex=function(edge){return this.m_vertices[edge]};Box2D.Collision.Shapes.b2PolygonShape.prototype.GetNormals=function(){return this.m_normals};Box2D.Collision.Shapes.b2PolygonShape.prototype.GetNormal=function(edge){return this.m_normals[edge]};Box2D.Collision.Shapes.b2PolygonShape.prototype.GetCentroid=function(){return this.m_centroid};Box2D.Collision.Shapes.b2PolygonShape.prototype.GetSupport=function(d){var bestIndex=0;var bestValue=this.m_vertices[0].x*d.x+this.m_vertices[0].y*d.y;for(var i=1;i&lt;this.m_vertexCount;++i){var value=this.m_vertices[i].x*d.x+this.m_vertices[i].y*d.y;if(value&gt;bestValue){bestIndex=i;bestValue=value}}return bestIndex};Box2D.Collision.Shapes.b2PolygonShape.prototype.GetSupportVertex=function(d){var bestIndex=0;var bestValue=this.m_vertices[0].x*d.x+this.m_vertices[0].y*d.y;for(var i=1;i&lt;this.m_vertexCount;++i){var value=this.m_vertices[i].x*d.x+this.m_vertices[i].y*d.y;if(value&gt;bestValue){bestIndex=i;bestValue=value}}return this.m_vertices[bestIndex]};Box2D.Collision.Shapes.b2PolygonShape.prototype.Reserve=function(count){for(var i=0;i&lt;this.m_vertices.length;i++){Box2D.Common.Math.b2Vec2.Free(this.m_vertices[i]);Box2D.Common.Math.b2Vec2.Free(this.m_normals[i])}this.m_vertices.length=0;this.m_normals.length=0;for(var i=0;i&lt;count;i++){this.m_vertices[i]=Box2D.Common.Math.b2Vec2.Get(0,0);this.m_normals[i]=Box2D.Common.Math.b2Vec2.Get(0,0)}};Box2D.Collision.Shapes.b2PolygonShape.ComputeCentroid=function(vs,count){var c=Box2D.Common.Math.b2Vec2.Get(0,0);var area=0;var p1X=0;var p1Y=0;var inv3=1/3;for(var i=0;i&lt;count;++i){var p2=vs[i];var p3=i+1&lt;count?vs[i+1]:vs[0];var e1X=p2.x-p1X;var e1Y=p2.y-p1Y;var e2X=p3.x-p1X;var e2Y=p3.y-p1Y;var D=e1X*e2Y-e1Y*e2X;var triangleArea=.5*D;area+=triangleArea;c.x+=triangleArea*inv3*(p1X+p2.x+p3.x);c.y+=triangleArea*inv3*(p1Y+p2.y+p3.y)}c.x*=1/area;c.y*=1/area;return c};Box2D.Collision.Shapes.b2PolygonShape.s_mat=Box2D.Common.Math.b2Mat22.Get();Box2D.Collision.Shapes.b2PolygonShape.NAME="b2PolygonShape";Box2D.Dynamics.Contacts.b2Contact=function(fixtureA,fixtureB){this.ID=Box2D.Dynamics.Contacts.b2Contact.NEXT_ID++;this.m_manifold=new Box2D.Collision.b2Manifold;this.m_oldManifold=new Box2D.Collision.b2Manifold;this.touching=false;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();this.continuous=bodyA.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody||bodyA.IsBullet()||bodyB.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody||bodyB.IsBullet();this.sensor=fixtureA.IsSensor()||fixtureB.IsSensor();this.filtering=false;this.m_fixtureA=fixtureA;this.m_fixtureB=fixtureB;this.enabled=true;this.bodyAList=bodyA.GetContactList();this.bodyBList=bodyB.GetContactList();this.worldList=bodyB.GetWorld().GetContactList();this.AddToLists()};Box2D.Dynamics.Contacts.b2Contact.prototype.Reset=function(fixtureA,fixtureB){this.m_manifold.Reset();this.m_oldManifold.Reset();this.touching=false;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();this.continuous=bodyA.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody||bodyA.IsBullet()||bodyB.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody||bodyB.IsBullet();this.sensor=fixtureA.IsSensor()||fixtureB.IsSensor();this.filtering=false;this.m_fixtureA=fixtureA;this.m_fixtureB=fixtureB;this.enabled=true;this.bodyAList=bodyA.GetContactList();this.bodyBList=bodyB.GetContactList();this.worldList=bodyB.GetWorld().GetContactList();this.AddToLists()};Box2D.Dynamics.Contacts.b2Contact.prototype.AddToLists=function(){this.bodyAList.AddContact(this);this.bodyBList.AddContact(this);this.worldList.AddContact(this);this.UpdateLists()};Box2D.Dynamics.Contacts.b2Contact.prototype.UpdateLists=function(){var nonSensorEnabledTouching=false;var nonSensorEnabledContinuous=false;if(!this.IsSensor()&amp;&amp;this.IsEnabled()){if(this.IsTouching()){nonSensorEnabledTouching=true}if(this.IsContinuous()){nonSensorEnabledContinuous=true}}this.bodyAList.UpdateContact(this,nonSensorEnabledTouching,nonSensorEnabledContinuous);this.bodyBList.UpdateContact(this,nonSensorEnabledTouching,nonSensorEnabledContinuous);this.worldList.UpdateContact(this,nonSensorEnabledTouching,nonSensorEnabledContinuous)};Box2D.Dynamics.Contacts.b2Contact.prototype.RemoveFromLists=function(){this.bodyAList.RemoveContact(this);this.bodyBList.RemoveContact(this);this.worldList.RemoveContact(this)};Box2D.Dynamics.Contacts.b2Contact.prototype.GetManifold=function(){return this.m_manifold};Box2D.Dynamics.Contacts.b2Contact.prototype.GetWorldManifold=function(worldManifold){var bodyA=this.m_fixtureA.GetBody();var bodyB=this.m_fixtureB.GetBody();var shapeA=this.m_fixtureA.GetShape();var shapeB=this.m_fixtureB.GetShape();worldManifold.Initialize(this.m_manifold,bodyA.GetTransform(),shapeA.m_radius,bodyB.GetTransform(),shapeB.m_radius)};Box2D.Dynamics.Contacts.b2Contact.prototype.IsTouching=function(){return this.touching};Box2D.Dynamics.Contacts.b2Contact.prototype.IsContinuous=function(){return this.continuous};Box2D.Dynamics.Contacts.b2Contact.prototype.SetSensor=function(sensor){this.sensor=sensor;this.UpdateLists()};Box2D.Dynamics.Contacts.b2Contact.prototype.IsSensor=function(){return this.sensor};Box2D.Dynamics.Contacts.b2Contact.prototype.SetEnabled=function(flag){this.enabled=flag;this.UpdateLists()};Box2D.Dynamics.Contacts.b2Contact.prototype.IsEnabled=function(){return this.enabled};Box2D.Dynamics.Contacts.b2Contact.prototype.GetNext=function(){return this.m_next};Box2D.Dynamics.Contacts.b2Contact.prototype.GetFixtureA=function(){return this.m_fixtureA};Box2D.Dynamics.Contacts.b2Contact.prototype.GetFixtureB=function(){return this.m_fixtureB};Box2D.Dynamics.Contacts.b2Contact.prototype.GetOther=function(body){var bodyA=this.m_fixtureA.GetBody();if(bodyA!=body){return bodyA}else{return this.m_fixtureB.GetBody()}};Box2D.Dynamics.Contacts.b2Contact.prototype.FlagForFiltering=function(){this.filtering=true};Box2D.Dynamics.Contacts.b2Contact.prototype.ClearFiltering=function(){this.filtering=false};Box2D.Dynamics.Contacts.b2Contact.prototype.IsFiltering=function(){return this.filtering};Box2D.Dynamics.Contacts.b2Contact.prototype.Update=function(listener){var tManifold=this.m_oldManifold;this.m_oldManifold=this.m_manifold;this.m_manifold=tManifold;this.enabled=true;var touching=false;var wasTouching=this.IsTouching();var bodyA=this.m_fixtureA.m_body;var bodyB=this.m_fixtureB.m_body;var aabbOverlap=this.m_fixtureA.m_aabb.TestOverlap(this.m_fixtureB.m_aabb);if(this.sensor){if(aabbOverlap){touching=Box2D.Collision.Shapes.b2Shape.TestOverlap(this.m_fixtureA.GetShape(),bodyA.GetTransform(),this.m_fixtureB.GetShape(),bodyB.GetTransform())}this.m_manifold.m_pointCount=0}else{if(bodyA.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody||bodyA.IsBullet()||bodyB.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody||bodyB.IsBullet()){this.continuous=true}else{this.continuous=false}if(aabbOverlap){this.Evaluate();touching=this.m_manifold.m_pointCount&gt;0;for(var i=0;i&lt;this.m_manifold.m_pointCount;i++){var mp2=this.m_manifold.m_points[i];mp2.m_normalImpulse=0;mp2.m_tangentImpulse=0;for(var j=0;j&lt;this.m_oldManifold.m_pointCount;j++){var mp1=this.m_oldManifold.m_points[j];if(mp1.m_id.GetKey()==mp2.m_id.GetKey()){mp2.m_normalImpulse=mp1.m_normalImpulse;mp2.m_tangentImpulse=mp1.m_tangentImpulse;break}}}}else{this.m_manifold.m_pointCount=0}if(touching!=wasTouching){bodyA.SetAwake(true);bodyB.SetAwake(true)}}this.touching=touching;if(touching!=wasTouching){this.UpdateLists()}if(!wasTouching&amp;&amp;touching){listener.BeginContact(this)}if(wasTouching&amp;&amp;!touching){listener.EndContact(this)}if(!this.sensor){listener.PreSolve(this,this.m_oldManifold)}};Box2D.Dynamics.Contacts.b2Contact.prototype.Evaluate=function(){};Box2D.Dynamics.Contacts.b2Contact.prototype.ComputeTOI=function(sweepA,sweepB){Box2D.Dynamics.Contacts.b2Contact.s_input.proxyA.Set(this.m_fixtureA.GetShape());Box2D.Dynamics.Contacts.b2Contact.s_input.proxyB.Set(this.m_fixtureB.GetShape());Box2D.Dynamics.Contacts.b2Contact.s_input.sweepA=sweepA;Box2D.Dynamics.Contacts.b2Contact.s_input.sweepB=sweepB;Box2D.Dynamics.Contacts.b2Contact.s_input.tolerance=Box2D.Common.b2Settings.b2_linearSlop;return Box2D.Collision.b2TimeOfImpact.TimeOfImpact(Box2D.Dynamics.Contacts.b2Contact.s_input)};Box2D.Dynamics.Contacts.b2Contact.s_input=new Box2D.Collision.b2TOIInput;Box2D.Dynamics.Contacts.b2Contact.NEXT_ID=0;Box2D.Dynamics.Contacts.b2CircleContact=function(fixtureA,fixtureB){Box2D.Dynamics.Contacts.b2Contact.call(this,fixtureA,fixtureB)};Box2D.inherits(Box2D.Dynamics.Contacts.b2CircleContact,Box2D.Dynamics.Contacts.b2Contact);Box2D.Dynamics.Contacts.b2CircleContact.prototype.Reset=function(fixtureA,fixtureB){Box2D.Dynamics.Contacts.b2Contact.prototype.Reset.call(this,fixtureA,fixtureB)};Box2D.Dynamics.Contacts.b2CircleContact.prototype.Evaluate=function(){var shapeA=this.m_fixtureA.GetShape();var shapeB=this.m_fixtureB.GetShape();Box2D.Collision.b2Collision.CollideCircles(this.m_manifold,shapeA,this.m_fixtureA.GetBody().GetTransform(),shapeB,this.m_fixtureB.GetBody().GetTransform())};Box2D.Dynamics.Contacts.b2ContactConstraint=function(){this.localPlaneNormal=Box2D.Common.Math.b2Vec2.Get(0,0);this.localPoint=Box2D.Common.Math.b2Vec2.Get(0,0);this.normal=Box2D.Common.Math.b2Vec2.Get(0,0);this.normalMass=Box2D.Common.Math.b2Mat22.Get();this.K=Box2D.Common.Math.b2Mat22.Get();this.points=Box2D.Array.Get();for(var i=0;i&lt;Box2D.Common.b2Settings.b2_maxManifoldPoints;i++){this.points[i]=new Box2D.Dynamics.Contacts.b2ContactConstraintPoint}};Box2D.Dynamics.Contacts.b2ContactConstraintPoint=function(){this.localPoint=Box2D.Common.Math.b2Vec2.Get(0,0);this.rA=Box2D.Common.Math.b2Vec2.Get(0,0);this.rB=Box2D.Common.Math.b2Vec2.Get(0,0);this.normalImpulse=0;this.tangentImpulse=0};Box2D.Dynamics.Contacts.b2ContactConstraintPoint.prototype.Reset=function(){this.localPoint.Set(0,0);this.rA.Set(0,0);this.rB.Set(0,0);this.normalImpulse=0;this.tangentImpulse=0};Box2D.Dynamics.Contacts.b2ContactList=function(){this.contactFirstNodes=Box2D.Array.Get();for(var i=0;i&lt;=Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts;i++){this.contactFirstNodes[i]=null}this.contactLastNodes=Box2D.Array.Get();for(var i=0;i&lt;=Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts;i++){this.contactLastNodes[i]=null}this.contactNodeLookup={};this.contactCount=0};Box2D.Dynamics.Contacts.b2ContactList.prototype.GetFirstNode=function(type){return this.contactFirstNodes[type]};Box2D.Dynamics.Contacts.b2ContactList.prototype.AddContact=function(contact){var contactID=contact.ID;if(this.contactNodeLookup[contactID]==null){this.contactNodeLookup[contactID]=Box2D.Array.Get();for(var i=0;i&lt;=Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts;i++){this.contactNodeLookup[contactID][i]=null}this.CreateNode(contact,contactID,Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);this.contactCount++}};Box2D.Dynamics.Contacts.b2ContactList.prototype.UpdateContact=function(contact,nonSensorEnabledTouching,nonSensorEnabledContinuous){if(nonSensorEnabledTouching){this.CreateNode(contact,contact.ID,Box2D.Dynamics.Contacts.b2ContactList.TYPES.nonSensorEnabledTouchingContacts)}else{this.RemoveNode(contact.ID,Box2D.Dynamics.Contacts.b2ContactList.TYPES.nonSensorEnabledTouchingContacts)}if(nonSensorEnabledContinuous){this.CreateNode(contact,contact.ID,Box2D.Dynamics.Contacts.b2ContactList.TYPES.nonSensorEnabledContinuousContacts)}else{this.RemoveNode(contact.ID,Box2D.Dynamics.Contacts.b2ContactList.TYPES.nonSensorEnabledContinuousContacts)}};Box2D.Dynamics.Contacts.b2ContactList.prototype.RemoveContact=function(contact){var contactID=contact.ID;if(this.contactNodeLookup[contactID]!=null){for(var i=0;i&lt;=Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts;i++){this.RemoveNode(contactID,i)}Box2D.Array.Free(this.contactNodeLookup[contactID]);delete this.contactNodeLookup[contactID];this.contactCount--}};Box2D.Dynamics.Contacts.b2ContactList.prototype.RemoveNode=function(contactID,type){var nodeList=this.contactNodeLookup[contactID];if(nodeList==null){return}var node=nodeList[type];if(node==null){return}nodeList[type]=null;var prevNode=node.GetPreviousNode();var nextNode=node.GetNextNode();if(prevNode==null){this.contactFirstNodes[type]=nextNode}else{prevNode.SetNextNode(nextNode)}if(nextNode==null){this.contactLastNodes[type]=prevNode}else{nextNode.SetPreviousNode(prevNode)}Box2D.Dynamics.Contacts.b2ContactListNode.FreeNode(node)};Box2D.Dynamics.Contacts.b2ContactList.prototype.CreateNode=function(contact,contactID,type){var nodeList=this.contactNodeLookup[contactID];if(nodeList[type]==null){nodeList[type]=Box2D.Dynamics.Contacts.b2ContactListNode.GetNode(contact);var prevNode=this.contactLastNodes[type];if(prevNode!=null){prevNode.SetNextNode(nodeList[type]);nodeList[type].SetPreviousNode(prevNode)}else{this.contactFirstNodes[type]=nodeList[type]}this.contactLastNodes[type]=nodeList[type]}};Box2D.Dynamics.Contacts.b2ContactList.prototype.GetContactCount=function(){return this.contactCount};Box2D.Dynamics.Contacts.b2ContactList.TYPES={nonSensorEnabledTouchingContacts:0,nonSensorEnabledContinuousContacts:1,allContacts:2};Box2D.Dynamics.Contacts.b2ContactListNode=function(contact){this.contact=contact;this.next=null;this.previous=null};Box2D.Dynamics.Contacts.b2ContactListNode.freeNodes=[];Box2D.Dynamics.Contacts.b2ContactListNode.GetNode=function(contact){if(Box2D.Dynamics.Contacts.b2ContactListNode.freeNodes.length&gt;0){var node=Box2D.Dynamics.Contacts.b2ContactListNode.freeNodes.pop();node.next=null;node.previous=null;node.contact=contact;return node}else{return new Box2D.Dynamics.Contacts.b2ContactListNode(contact)}};Box2D.Dynamics.Contacts.b2ContactListNode.FreeNode=function(node){Box2D.Dynamics.Contacts.b2ContactListNode.freeNodes.push(node)};Box2D.Dynamics.Contacts.b2ContactListNode.prototype.SetNextNode=function(node){this.next=node};Box2D.Dynamics.Contacts.b2ContactListNode.prototype.SetPreviousNode=function(node){this.previous=node};Box2D.Dynamics.Contacts.b2ContactListNode.prototype.GetContact=function(){return this.contact};Box2D.Dynamics.Contacts.b2ContactListNode.prototype.GetNextNode=function(){return this.next};Box2D.Dynamics.Contacts.b2ContactListNode.prototype.GetPreviousNode=function(){return this.previous};Box2D.Dynamics.Contacts.b2ContactRegister=function(){this.pool=null;this.poolCount=0};Box2D.Dynamics.Contacts.b2ContactSolver=function(){this.m_constraints=Box2D.Array.Get()};Box2D.Dynamics.Contacts.b2ContactSolver.prototype.Initialize=function(step,contacts,contactCount){this.m_constraintCount=contactCount;while(this.m_constraints.length&lt;this.m_constraintCount){this.m_constraints[this.m_constraints.length]=new Box2D.Dynamics.Contacts.b2ContactConstraint}var s_worldManifold=Box2D.Dynamics.Contacts.b2ContactSolver.s_worldManifold;for(var i=0;i&lt;contactCount;i++){var contact=contacts[i];var fixtureA=contact.m_fixtureA;var fixtureB=contact.m_fixtureB;var shapeA=fixtureA.m_shape;var shapeB=fixtureB.m_shape;var radiusA=shapeA.m_radius;var radiusB=shapeB.m_radius;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();var bodyACenter=bodyA.m_sweep.c;var bodyBCenter=bodyB.m_sweep.c;var manifold=contact.GetManifold();var friction=Box2D.Common.b2Settings.b2MixFriction(fixtureA.GetFriction(),fixtureB.GetFriction());var restitution=Box2D.Common.b2Settings.b2MixRestitution(fixtureA.GetRestitution(),fixtureB.GetRestitution());var vAX=bodyA.m_linearVelocity.x;var vAY=bodyA.m_linearVelocity.y;var vBX=bodyB.m_linearVelocity.x;var vBY=bodyB.m_linearVelocity.y;var wA=bodyA.m_angularVelocity;var wB=bodyB.m_angularVelocity;s_worldManifold.Initialize(manifold,bodyA.GetTransform(),radiusA,bodyB.GetTransform(),radiusB);var normalX=s_worldManifold.m_normal.x;var normalY=s_worldManifold.m_normal.y;var cc=this.m_constraints[i];cc.bodyA=bodyA;cc.bodyB=bodyB;cc.manifold=manifold;cc.normal.x=normalX;cc.normal.y=normalY;cc.pointCount=manifold.m_pointCount;cc.friction=friction;cc.restitution=restitution;cc.localPlaneNormal.x=manifold.m_localPlaneNormal.x;cc.localPlaneNormal.y=manifold.m_localPlaneNormal.y;cc.localPoint.x=manifold.m_localPoint.x;cc.localPoint.y=manifold.m_localPoint.y;cc.radius=radiusA+radiusB;cc.type=manifold.m_type;for(var k=0;k&lt;cc.pointCount;++k){var cp=manifold.m_points[k];var ccp=cc.points[k];ccp.normalImpulse=cp.m_normalImpulse;ccp.tangentImpulse=cp.m_tangentImpulse;ccp.localPoint.SetV(cp.m_localPoint);var manifoldPoint=s_worldManifold.m_points[k];var rAX=ccp.rA.x=manifoldPoint.x-bodyACenter.x;var rAY=ccp.rA.y=manifoldPoint.y-bodyACenter.y;var rBX=ccp.rB.x=manifoldPoint.x-bodyBCenter.x;var rBY=ccp.rB.y=manifoldPoint.y-bodyBCenter.y;var rnA=rAX*normalY-rAY*normalX;var rnB=rBX*normalY-rBY*normalX;rnA*=rnA;rnB*=rnB;var kNormal=bodyA.m_invMass+bodyB.m_invMass+bodyA.m_invI*rnA+bodyB.m_invI*rnB;ccp.normalMass=1/kNormal;var kEqualized=bodyA.m_mass*bodyA.m_invMass+bodyB.m_mass*bodyB.m_invMass;kEqualized+=bodyA.m_mass*bodyA.m_invI*rnA+bodyB.m_mass*bodyB.m_invI*rnB;ccp.equalizedMass=1/kEqualized;var tangentX=normalY;var tangentY=-normalX;var rtA=rAX*tangentY-rAY*tangentX;var rtB=rBX*tangentY-rBY*tangentX;rtA*=rtA;rtB*=rtB;var kTangent=bodyA.m_invMass+bodyB.m_invMass+bodyA.m_invI*rtA+bodyB.m_invI*rtB;ccp.tangentMass=1/kTangent;ccp.velocityBias=0;var tX=vBX+-wB*rBY-vAX- -wA*rAY;var tY=vBY+wB*rBX-vAY-wA*rAX;var vRel=cc.normal.x*tX+cc.normal.y*tY;if(vRel&lt;-Box2D.Common.b2Settings.b2_velocityThreshold){ccp.velocityBias+=-cc.restitution*vRel}}if(cc.pointCount==2){var ccp1=cc.points[0];var ccp2=cc.points[1];var invMassA=bodyA.m_invMass;var invIA=bodyA.m_invI;var invMassB=bodyB.m_invMass;var invIB=bodyB.m_invI;var rn1A=ccp1.rA.x*normalY-ccp1.rA.y*normalX;var rn1B=ccp1.rB.x*normalY-ccp1.rB.y*normalX;var rn2A=ccp2.rA.x*normalY-ccp2.rA.y*normalX;var rn2B=ccp2.rB.x*normalY-ccp2.rB.y*normalX;var k11=invMassA+invMassB+invIA*rn1A*rn1A+invIB*rn1B*rn1B;var k22=invMassA+invMassB+invIA*rn2A*rn2A+invIB*rn2B*rn2B;var k12=invMassA+invMassB+invIA*rn1A*rn2A+invIB*rn1B*rn2B;var k_maxConditionNumber=100;if(k11*k11&lt;k_maxConditionNumber*(k11*k22-k12*k12)){cc.K.col1.Set(k11,k12);cc.K.col2.Set(k12,k22);cc.K.GetInverse(cc.normalMass)}else{cc.pointCount=1}}}};Box2D.Dynamics.Contacts.b2ContactSolver.prototype.InitVelocityConstraints=function(step){for(var i=0;i&lt;this.m_constraintCount;++i){var c=this.m_constraints[i];var bodyA=c.bodyA;var bodyB=c.bodyB;var invMassA=bodyA.m_invMass;var invIA=bodyA.m_invI;var invMassB=bodyB.m_invMass;var invIB=bodyB.m_invI;var normalX=c.normal.x;var normalY=c.normal.y;var tangentX=normalY;var tangentY=-normalX;var tX=0;var j=0;var tCount=0;if(step.warmStarting){tCount=c.pointCount;for(j=0;j&lt;tCount;++j){var ccp=c.points[j];ccp.normalImpulse*=step.dtRatio;ccp.tangentImpulse*=step.dtRatio;var PX=ccp.normalImpulse*normalX+ccp.tangentImpulse*tangentX;var PY=ccp.normalImpulse*normalY+ccp.tangentImpulse*tangentY;bodyA.m_angularVelocity-=invIA*(ccp.rA.x*PY-ccp.rA.y*PX);bodyA.m_linearVelocity.x-=invMassA*PX;bodyA.m_linearVelocity.y-=invMassA*PY;bodyB.m_angularVelocity+=invIB*(ccp.rB.x*PY-ccp.rB.y*PX);bodyB.m_linearVelocity.x+=invMassB*PX;bodyB.m_linearVelocity.y+=invMassB*PY}}else{tCount=c.pointCount;for(j=0;j&lt;tCount;++j){var ccp2=c.points[j];ccp2.normalImpulse=0;ccp2.tangentImpulse=0}}}};Box2D.Dynamics.Contacts.b2ContactSolver.prototype.SolveVelocityConstraints=function(){for(var i=0;i&lt;this.m_constraintCount;i++){this.SolveVelocityConstraints_Constraint(this.m_constraints[i])}};Box2D.Dynamics.Contacts.b2ContactSolver.prototype.SolveVelocityConstraints_Constraint=function(c){var normalX=c.normal.x;var normalY=c.normal.y;for(var j=0;j&lt;c.pointCount;j++){Box2D.Dynamics.Contacts.b2ContactSolver.prototype.SolveVelocityConstraints_ConstraintPoint(c,c.points[j])}if(c.pointCount==1){var ccp=c.points[0];var dvX=c.bodyB.m_linearVelocity.x-c.bodyB.m_angularVelocity*ccp.rB.y-c.bodyA.m_linearVelocity.x+c.bodyA.m_angularVelocity*ccp.rA.y;var dvY=c.bodyB.m_linearVelocity.y+c.bodyB.m_angularVelocity*ccp.rB.x-c.bodyA.m_linearVelocity.y-c.bodyA.m_angularVelocity*ccp.rA.x;var vn=dvX*normalX+dvY*normalY;var newImpulse=ccp.normalImpulse-ccp.normalMass*(vn-ccp.velocityBias);newImpulse=newImpulse&gt;0?newImpulse:0;var impulseLambda=newImpulse-ccp.normalImpulse;var PX=impulseLambda*normalX;var PY=impulseLambda*normalY;c.bodyA.m_linearVelocity.x-=c.bodyA.m_invMass*PX;c.bodyA.m_linearVelocity.y-=c.bodyA.m_invMass*PY;c.bodyA.m_angularVelocity-=c.bodyA.m_invI*(ccp.rA.x*PY-ccp.rA.y*PX);c.bodyB.m_linearVelocity.x+=c.bodyB.m_invMass*PX;c.bodyB.m_linearVelocity.y+=c.bodyB.m_invMass*PY;c.bodyB.m_angularVelocity+=c.bodyB.m_invI*(ccp.rB.x*PY-ccp.rB.y*PX);ccp.normalImpulse=newImpulse}else{var cp1=c.points[0];var cp2=c.points[1];var aX=cp1.normalImpulse;var aY=cp2.normalImpulse;var dv1X=c.bodyB.m_linearVelocity.x-c.bodyB.m_angularVelocity*cp1.rB.y-c.bodyA.m_linearVelocity.x+c.bodyA.m_angularVelocity*cp1.rA.y;var dv1Y=c.bodyB.m_linearVelocity.y+c.bodyB.m_angularVelocity*cp1.rB.x-c.bodyA.m_linearVelocity.y-c.bodyA.m_angularVelocity*cp1.rA.x;var dv2X=c.bodyB.m_linearVelocity.x-c.bodyB.m_angularVelocity*cp2.rB.y-c.bodyA.m_linearVelocity.x+c.bodyA.m_angularVelocity*cp2.rA.y;var dv2Y=c.bodyB.m_linearVelocity.y+c.bodyB.m_angularVelocity*cp2.rB.x-c.bodyA.m_linearVelocity.y-c.bodyA.m_angularVelocity*cp2.rA.x;var bX=dv1X*normalX+dv1Y*normalY-cp1.velocityBias;var bY=dv2X*normalX+dv2Y*normalY-cp2.velocityBias;bX-=c.K.col1.x*aX+c.K.col2.x*aY;bY-=c.K.col1.y*aX+c.K.col2.y*aY;for(;;){var firstX=-(c.normalMass.col1.x*bX+c.normalMass.col2.x*bY);if(firstX&gt;=0){var firstY=-(c.normalMass.col1.y*bX+c.normalMass.col2.y*bY);if(firstY&gt;=0){var dX=firstX-aX;var dY=firstY-aY;this.SolveVelocityConstraints_ConstraintPointUpdate(c,cp1,cp2,firstX-aX,firstY-aY);cp1.normalImpulse=firstX;cp2.normalImpulse=firstY;break}}var secondX=-cp1.normalMass*bX;if(secondX&gt;=0){if(c.K.col1.y*secondX+bY&gt;=0){var dX=secondX-aX;var dY=-aY;this.SolveVelocityConstraints_ConstraintPointUpdate(c,cp1,cp2,secondX-aX,-aY);cp1.normalImpulse=secondX;cp2.normalImpulse=0;break}}var secondY=-cp2.normalMass*bY;if(secondY&gt;=0){if(c.K.col2.x*secondY+bX&gt;=0){this.SolveVelocityConstraints_ConstraintPointUpdate(c,cp1,cp2,-aX,secondY-aY);cp1.normalImpulse=0;cp2.normalImpulse=secondY;break}}if(bX&gt;=0&amp;&amp;bY&gt;=0){this.SolveVelocityConstraints_ConstraintPointUpdate(c,cp1,cp2,-aX,-aY);cp1.normalImpulse=0;cp2.normalImpulse=0;break}break}}};Box2D.Dynamics.Contacts.b2ContactSolver.prototype.SolveVelocityConstraints_ConstraintPoint=function(c,ccp){var tangentX=c.normal.y;var tangentY=-c.normal.x;var dvX=c.bodyB.m_linearVelocity.x-c.bodyB.m_angularVelocity*ccp.rB.y-c.bodyA.m_linearVelocity.x+c.bodyA.m_angularVelocity*ccp.rA.y;var dvY=c.bodyB.m_linearVelocity.y+c.bodyB.m_angularVelocity*ccp.rB.x-c.bodyA.m_linearVelocity.y-c.bodyA.m_angularVelocity*ccp.rA.x;var vt=dvX*tangentX+dvY*tangentY;var maxFriction=c.friction*ccp.normalImpulse;var newImpulse=Box2D.Common.Math.b2Math.Clamp(ccp.tangentImpulse-ccp.tangentMass*vt,-maxFriction,maxFriction);var impulseLambda=newImpulse-ccp.tangentImpulse;var PX=impulseLambda*tangentX;var PY=impulseLambda*tangentY;c.bodyA.m_linearVelocity.x-=c.bodyA.m_invMass*PX;c.bodyA.m_linearVelocity.y-=c.bodyA.m_invMass*PY;c.bodyA.m_angularVelocity-=c.bodyA.m_invI*(ccp.rA.x*PY-ccp.rA.y*PX);c.bodyB.m_linearVelocity.x+=c.bodyB.m_invMass*PX;c.bodyB.m_linearVelocity.y+=c.bodyB.m_invMass*PY;c.bodyB.m_angularVelocity+=c.bodyB.m_invI*(ccp.rB.x*PY-ccp.rB.y*PX);ccp.tangentImpulse=newImpulse};Box2D.Dynamics.Contacts.b2ContactSolver.prototype.SolveVelocityConstraints_ConstraintPointUpdate=function(c,cp1,cp2,dX,dY){var P1X=dX*c.normal.x;var P1Y=dX*c.normal.y;var P2X=dY*c.normal.x;var P2Y=dY*c.normal.y;c.bodyA.m_linearVelocity.x-=c.bodyA.m_invMass*(P1X+P2X);c.bodyA.m_linearVelocity.y-=c.bodyA.m_invMass*(P1Y+P2Y);c.bodyA.m_angularVelocity-=c.bodyA.m_invI*(cp1.rA.x*P1Y-cp1.rA.y*P1X+cp2.rA.x*P2Y-cp2.rA.y*P2X);c.bodyB.m_linearVelocity.x+=c.bodyB.m_invMass*(P1X+P2X);c.bodyB.m_linearVelocity.y+=c.bodyB.m_invMass*(P1Y+P2Y);c.bodyB.m_angularVelocity+=c.bodyB.m_invI*(cp1.rB.x*P1Y-cp1.rB.y*P1X+cp2.rB.x*P2Y-cp2.rB.y*P2X);cp1.normalImpulse=0;cp2.normalImpulse=0};Box2D.Dynamics.Contacts.b2ContactSolver.prototype.FinalizeVelocityConstraints=function(){for(var i=0;i&lt;this.m_constraintCount;++i){var c=this.m_constraints[i];var m=c.manifold;for(var j=0;j&lt;c.pointCount;++j){var point1=m.m_points[j];var point2=c.points[j];point1.m_normalImpulse=point2.normalImpulse;point1.m_tangentImpulse=point2.tangentImpulse}}};Box2D.Dynamics.Contacts.b2ContactSolver.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;var minSeparation=0;var s_psm=Box2D.Dynamics.Contacts.b2ContactSolver.s_psm;for(var i=0;i&lt;this.m_constraintCount;i++){var c=this.m_constraints[i];var bodyA=c.bodyA;var bodyB=c.bodyB;var invMassA=bodyA.m_mass*bodyA.m_invMass;var invIA=bodyA.m_mass*bodyA.m_invI;var invMassB=bodyB.m_mass*bodyB.m_invMass;var invIB=bodyB.m_mass*bodyB.m_invI;var bodyACenter=bodyA.m_sweep.c;var bodyBCenter=bodyB.m_sweep.c;var syncTransforms=false;s_psm.Initialize(c);var normal=s_psm.m_normal;for(var j=0;j&lt;c.pointCount;j++){var ccp=c.points[j];var point=s_psm.m_points[j];var separation=s_psm.m_separations[j];var rAX=point.x-bodyACenter.x;var rAY=point.y-bodyACenter.y;var rBX=point.x-bodyBCenter.x;var rBY=point.y-bodyBCenter.y;minSeparation=minSeparation&lt;separation?minSeparation:separation;var C=Box2D.Common.Math.b2Math.Clamp(baumgarte*(separation+Box2D.Common.b2Settings.b2_linearSlop),-Box2D.Common.b2Settings.b2_maxLinearCorrection,0);var impulse=-ccp.equalizedMass*C;var PX=impulse*normal.x;var PY=impulse*normal.y;bodyACenter.x-=invMassA*PX;bodyACenter.y-=invMassA*PY;bodyA.SetCalculatedAngle(bodyA.GetAngle()-invIA*(rAX*PY-rAY*PX));bodyBCenter.x+=invMassB*PX;bodyBCenter.y+=invMassB*PY;bodyB.SetCalculatedAngle(bodyB.GetAngle()+invIB*(rBX*PY-rBY*PX));syncTransforms=true}if(syncTransforms){bodyA.SynchronizeTransform();bodyB.SynchronizeTransform()}}return minSeparation&gt;-1.5*Box2D.Common.b2Settings.b2_linearSlop};Box2D.Dynamics.Contacts.b2ContactSolver.prototype.SolvePositionConstraints_NEW=function(baumgarte){if(baumgarte===undefined)baumgarte=0;var minSeparation=0;for(var i=0;i&lt;this.m_constraintCount;i++){var c=this.m_constraints[i];var bodyA=c.bodyA;var bodyB=c.bodyB;var invMassA=bodyA.m_mass*bodyA.m_invMass;var invIA=bodyA.m_mass*bodyA.m_invI;var invMassB=bodyB.m_mass*bodyB.m_invMass;var invIB=bodyB.m_mass*bodyB.m_invI;Box2D.Dynamics.Contacts.b2ContactSolver.s_psm.Initialize(c);var normal=Box2D.Dynamics.Contacts.b2ContactSolver.s_psm.m_normal;for(var j=0;j&lt;c.pointCount;j++){var ccp=c.points[j];var point=Box2D.Dynamics.Contacts.b2ContactSolver.s_psm.m_points[j];var separation=Box2D.Dynamics.Contacts.b2ContactSolver.s_psm.m_separations[j];var rAX=point.x-bodyA.GetWorldCenter().x;var rAY=point.y-bodyA.GetWorldCenter().y;var rBX=point.x-bodyB.GetWorldCenter().x;var rBY=point.y-bodyB.GetWorldCenter().y;if(separation&lt;minSeparation){minSeparation=separation}var C=0;if(baumgarte!=0){Box2D.Common.Math.b2Math.Clamp(baumgarte*(separation+Box2D.Common.b2Settings.b2_linearSlop),-Box2D.Common.b2Settings.b2_maxLinearCorrection,0)}var impulse=-ccp.equalizedMass*C;var PX=impulse*normal.x;var PY=impulse*normal.y;bodyA.GetWorldCenter().x-=invMassA*PX;bodyA.GetWorldCenter().y-=invMassA*PY;bodyA.SetAngle(bodyA.GetAngle()-invIA*(rAX*PY-rAY*PX));bodyA.SynchronizeTransform();bodyB.GetWorldCenter().x+=invMassB*PX;bodyB.GetWorldCenter().y+=invMassB*PY;bodyB.SetAngle(bodyB.GetAngle()+invIB*(rBX*PY-rBY*PX));bodyB.SynchronizeTransform()}}return minSeparation&gt;-1.5*Box2D.Common.b2Settings.b2_linearSlop};Box2D.Dynamics.Contacts.b2ContactSolver.s_worldManifold=new Box2D.Collision.b2WorldManifold;Box2D.Dynamics.Contacts.b2ContactSolver.s_psm=new Box2D.Dynamics.Contacts.b2PositionSolverManifold;Box2D.Dynamics.Contacts.b2ContactSolver.singleton=new Box2D.Dynamics.Contacts.b2ContactSolver;Box2D.Dynamics.Contacts.b2EdgeAndCircleContact=function(fixtureA,fixtureB){Box2D.Dynamics.Contacts.b2Contact.call(this,fixtureA,fixtureB)};Box2D.inherits(Box2D.Dynamics.Contacts.b2EdgeAndCircleContact,Box2D.Dynamics.Contacts.b2Contact);Box2D.Dynamics.Contacts.b2EdgeAndCircleContact.prototype.Reset=function(fixtureA,fixtureB){Box2D.Dynamics.Contacts.b2Contact.prototype.Reset.call(this,fixtureA,fixtureB)};Box2D.Dynamics.Contacts.b2EdgeAndCircleContact.prototype.Evaluate=function(){var bA=this.m_fixtureA.GetBody();var bB=this.m_fixtureB.GetBody();this.b2CollideEdgeAndCircle(this.m_manifold,this.m_fixtureA.GetShape(),this.m_fixtureA.GetBody().GetTransform(),this.m_fixtureB.GetShape(),this.m_fixtureB.GetBody().GetTransform())};Box2D.Dynamics.Contacts.b2EdgeAndCircleContact.prototype.b2CollideEdgeAndCircle=function(manifold,edge,xf1,circle,xf2){};Box2D.Dynamics.Contacts.b2PolyAndCircleContact=function(fixtureA,fixtureB){Box2D.Common.b2Settings.b2Assert(fixtureA.GetShape()instanceof Box2D.Collision.Shapes.b2PolygonShape);Box2D.Common.b2Settings.b2Assert(fixtureB.GetShape()instanceof Box2D.Collision.Shapes.b2CircleShape);Box2D.Dynamics.Contacts.b2Contact.call(this,fixtureA,fixtureB)};Box2D.inherits(Box2D.Dynamics.Contacts.b2PolyAndCircleContact,Box2D.Dynamics.Contacts.b2Contact);Box2D.Dynamics.Contacts.b2PolyAndCircleContact.prototype.Reset=function(fixtureA,fixtureB){Box2D.Common.b2Settings.b2Assert(fixtureA.GetShape()instanceof Box2D.Collision.Shapes.b2PolygonShape);Box2D.Common.b2Settings.b2Assert(fixtureB.GetShape()instanceof Box2D.Collision.Shapes.b2CircleShape);Box2D.Dynamics.Contacts.b2Contact.prototype.Reset.call(this,fixtureA,fixtureB)};Box2D.Dynamics.Contacts.b2PolyAndCircleContact.prototype.Evaluate=function(){var shapeA=this.m_fixtureA.GetShape();var shapeB=this.m_fixtureB.GetShape();Box2D.Collision.b2Collision.CollidePolygonAndCircle(this.m_manifold,shapeA,this.m_fixtureA.GetBody().GetTransform(),shapeB,this.m_fixtureB.GetBody().GetTransform())};Box2D.Dynamics.Contacts.b2PolyAndEdgeContact=function(fixtureA,fixtureB){Box2D.Common.b2Settings.b2Assert(fixtureA.GetShape()instanceof Box2D.Collision.Shapes.b2PolygonShape);Box2D.Common.b2Settings.b2Assert(fixtureB.GetShape()instanceof Box2D.Collision.Shapes.b2EdgeShape);Box2D.Dynamics.Contacts.b2Contact.call(this,fixtureA,fixtureB)};Box2D.inherits(Box2D.Dynamics.Contacts.b2PolyAndEdgeContact,Box2D.Dynamics.Contacts.b2Contact);Box2D.Dynamics.Contacts.b2PolyAndEdgeContact.prototype.Reset=function(fixtureA,fixtureB){Box2D.Common.b2Settings.b2Assert(fixtureA.GetShape()instanceof Box2D.Collision.Shapes.b2PolygonShape);Box2D.Common.b2Settings.b2Assert(fixtureB.GetShape()instanceof Box2D.Collision.Shapes.b2EdgeShape);Box2D.Dynamics.Contacts.b2Contact.prototype.Reset.call(this,fixtureA,fixtureB)};Box2D.Dynamics.Contacts.b2PolyAndEdgeContact.prototype.Evaluate=function(){this.b2CollidePolyAndEdge(this.m_manifold,this.m_fixtureA.GetShape(),this.m_fixtureA.GetBody().GetTransform(),this.m_fixtureB.GetShape(),this.m_fixtureB.GetBody().GetTransform())};Box2D.Dynamics.Contacts.b2PolyAndEdgeContact.prototype.b2CollidePolyAndEdge=function(manifold,polygon,xf1,edge,xf2){};Box2D.Dynamics.Contacts.b2PolygonContact=function(fixtureA,fixtureB){Box2D.Dynamics.Contacts.b2Contact.call(this,fixtureA,fixtureB)};Box2D.inherits(Box2D.Dynamics.Contacts.b2PolygonContact,Box2D.Dynamics.Contacts.b2Contact);Box2D.Dynamics.Contacts.b2PolygonContact.prototype.Reset=function(fixtureA,fixtureB){Box2D.Dynamics.Contacts.b2Contact.prototype.Reset.call(this,fixtureA,fixtureB)};Box2D.Dynamics.Contacts.b2PolygonContact.prototype.Evaluate=function(){var shapeA=this.m_fixtureA.GetShape();var shapeB=this.m_fixtureB.GetShape();Box2D.Collision.b2Collision.CollidePolygons(this.m_manifold,shapeA,this.m_fixtureA.GetBody().GetTransform(),shapeB,this.m_fixtureB.GetBody().GetTransform())};Box2D.Dynamics.Contacts.b2ContactFactory=function(){this.m_registers={};this.m_freeContacts={};this.AddType(Box2D.Dynamics.Contacts.b2CircleContact,Box2D.Collision.Shapes.b2CircleShape.NAME,Box2D.Collision.Shapes.b2CircleShape.NAME);this.AddType(Box2D.Dynamics.Contacts.b2PolyAndCircleContact,Box2D.Collision.Shapes.b2PolygonShape.NAME,Box2D.Collision.Shapes.b2CircleShape.NAME);this.AddType(Box2D.Dynamics.Contacts.b2PolygonContact,Box2D.Collision.Shapes.b2PolygonShape.NAME,Box2D.Collision.Shapes.b2PolygonShape.NAME);this.AddType(Box2D.Dynamics.Contacts.b2EdgeAndCircleContact,Box2D.Collision.Shapes.b2EdgeShape.NAME,Box2D.Collision.Shapes.b2CircleShape.NAME);this.AddType(Box2D.Dynamics.Contacts.b2PolyAndEdgeContact,Box2D.Collision.Shapes.b2PolygonShape.NAME,Box2D.Collision.Shapes.b2EdgeShape.NAME)};Box2D.Dynamics.Contacts.b2ContactFactory.prototype.AddType=function(ctor,type1,type2){this.m_freeContacts[type1]=this.m_freeContacts[type1]||{};this.m_freeContacts[type1][type2]=this.m_freeContacts[type1][type2]||Box2D.Array.Get();this.m_registers[type1]=this.m_registers[type1]||{};this.m_registers[type1][type2]=new Box2D.Dynamics.Contacts.b2ContactRegister;this.m_registers[type1][type2].ctor=ctor;this.m_registers[type1][type2].primary=true;if(type1!=type2){this.m_registers[type2]=this.m_registers[type2]||{};this.m_registers[type2][type1]=new Box2D.Dynamics.Contacts.b2ContactRegister;this.m_registers[type2][type1].ctor=ctor;this.m_registers[type2][type1].primary=false}};Box2D.Dynamics.Contacts.b2ContactFactory.prototype.Create=function(fixtureA,fixtureB){var type1=fixtureA.GetShape().GetTypeName();var type2=fixtureB.GetShape().GetTypeName();var reg=this.m_registers[type1][type2];var ctor=reg.ctor;if(ctor!=null){if(reg.primary){if(this.m_freeContacts[type1][type2].length&gt;0){var c=this.m_freeContacts[type1][type2].pop();c.Reset(fixtureA,fixtureB);return c}return new ctor(fixtureA,fixtureB)}else{if(this.m_freeContacts[type2][type1].length&gt;0){var c=this.m_freeContacts[type2][type1].pop();c.Reset(fixtureB,fixtureA);return c}return new ctor(fixtureB,fixtureA)}}else{return null}};Box2D.Dynamics.Contacts.b2ContactFactory.prototype.Destroy=function(contact){var type1=contact.GetFixtureA().GetShape().GetTypeName();var type2=contact.GetFixtureB().GetShape().GetTypeName();this.m_freeContacts[type1][type2].push(contact)};Box2D.Dynamics.Contacts.b2ContactFactory.singleton=new Box2D.Dynamics.Contacts.b2ContactFactory;Box2D.Dynamics.b2ContactManager=function(world){this.m_world=world;this.m_contactFilter=Box2D.Dynamics.b2ContactFilter.b2_defaultFilter;this.m_contactListener=Box2D.Dynamics.b2ContactListener.b2_defaultListener;this.m_contactFactory=Box2D.Dynamics.Contacts.b2ContactFactory.singleton;this.m_broadPhase=new Box2D.Collision.b2DynamicTreeBroadPhase;var self=this;this.m_addPairCallback=function(fixtureA,fixtureB){self.AddPair(fixtureA,fixtureB)}};Box2D.Dynamics.b2ContactManager.prototype.AddPair=function(fixtureA,fixtureB){var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(bodyA==bodyB){return}if(!bodyB.ShouldCollide(bodyA)){return}if(!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){return}for(var contactNode=bodyB.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){var fA=contactNode.contact.GetFixtureA();if(fA==fixtureA){var fB=contactNode.contact.GetFixtureB();if(fB==fixtureB){return}}else if(fA==fixtureB){var fB=contactNode.contact.GetFixtureB();if(fB==fixtureA){return}}}var c=this.m_contactFactory.Create(fixtureA,fixtureB)};Box2D.Dynamics.b2ContactManager.prototype.FindNewContacts=function(){this.m_broadPhase.UpdatePairs(this.m_addPairCallback)};Box2D.Dynamics.b2ContactManager.prototype.Destroy=function(c){var fixtureA=c.GetFixtureA();var fixtureB=c.GetFixtureB();var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(c.IsTouching()){this.m_contactListener.EndContact(c)}if(c.m_manifold.m_pointCount&gt;0){bodyA.SetAwake(true);bodyB.SetAwake(true)}c.RemoveFromLists();this.m_contactFactory.Destroy(c)};Box2D.Dynamics.b2ContactManager.prototype.Collide=function(){for(var contactNode=this.m_world.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){var c=contactNode.contact;var fixtureA=c.GetFixtureA();var fixtureB=c.GetFixtureB();var bodyA=fixtureA.m_body;var bodyB=fixtureB.m_body;if(!bodyA.IsAwake()&amp;&amp;!bodyB.IsAwake()){continue}if(c.IsFiltering()){if(!bodyB.ShouldCollide(bodyA)){this.Destroy(c);continue}if(!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){this.Destroy(c);continue}c.ClearFiltering()}var proxyA=fixtureA.m_proxy;var proxyB=fixtureB.m_proxy;var overlap=this.m_broadPhase.TestOverlap(proxyA,proxyB);if(!overlap){this.Destroy(c);continue}c.Update(this.m_contactListener)}};Box2D.Dynamics.b2ContactManager.s_evalCP=new Box2D.Collision.b2ContactPoint;Box2D.Dynamics.b2World=function(gravity,doSleep){if(!this.m_contactManager){this.m_contactManager=new Box2D.Dynamics.b2ContactManager(this)}if(!this.m_contactSolver){this.m_contactSolver=Box2D.Dynamics.Contacts.b2ContactSolver.singleton}this.m_isLocked=false;this.m_newFixture=false;this.m_destructionListener=null;this.m_debugDraw=null;if(!this.bodyList){this.bodyList=new Box2D.Dynamics.b2BodyList}if(!this.contactList){this.contactList=new Box2D.Dynamics.Contacts.b2ContactList}this.m_jointList=null;if(!this.controllerList){this.controllerList=new Box2D.Dynamics.Controllers.b2ControllerList}this.m_jointCount=0;this.m_warmStarting=true;this.m_continuousPhysics=true;this.m_allowSleep=doSleep;if(!this.m_gravity){this.m_gravity=Box2D.Common.Math.b2Vec2.Get(0,0)}this.m_gravity.SetV(gravity);this.m_inv_dt0=0;if(!this.m_groundBody){this.m_groundBody=this.CreateBody(new Box2D.Dynamics.b2BodyDef)}if(!this.mainTimeStep){this.mainTimeStep=new Box2D.Dynamics.b2TimeStep(0,0,0,0,this.m_warmStarting)}this.mainTimeStep.Reset(0,0,0,0,this.m_warmStarting);if(!this.islandTimeStep){this.islandTimeStep=new Box2D.Dynamics.b2TimeStep(0,0,0,0,this.m_warmStarting)}this.islandTimeStep.Reset(0,0,0,0,this.m_warmStarting);if(!this.island){this.island=new Box2D.Dynamics.b2Island(this.m_contactManager.m_contactListener,this.m_contactSolver)}};Box2D.Dynamics.b2World.MAX_TOI=1-100*Number.MIN_VALUE;Box2D.Dynamics.b2World.s_solveStack=[];Box2D.Dynamics.b2World.s_solveQueue=[];Box2D.Dynamics.b2World.s_solveTOI2Result={};Box2D.Dynamics.b2World.prototype.SetDestructionListener=function(listener){this.m_destructionListener=listener};Box2D.Dynamics.b2World.prototype.SetContactFilter=function(filter){this.m_contactManager.m_contactFilter=filter};Box2D.Dynamics.b2World.prototype.SetContactListener=function(listener){this.m_contactManager.m_contactListener=listener};Box2D.Dynamics.b2World.prototype.SetDebugDraw=function(debugDraw){this.m_debugDraw=debugDraw};Box2D.Dynamics.b2World.prototype.SetBroadPhase=function(broadPhase){var oldBroadPhase=this.m_contactManager.m_broadPhase;this.m_contactManager.m_broadPhase=broadPhase;for(var node=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);node;node=node.GetNextNode()){for(var fixtureNode=node.body.GetFixtureList().GetFirstNode();fixtureNode;fixtureNode=fixtureNode.GetNextNode()){var f=fixtureNode.fixture;f.m_proxy=broadPhase.CreateProxy(oldBroadPhase.GetFatAABB(f.m_proxy),f)}}};Box2D.Dynamics.b2World.prototype.GetProxyCount=function(){return this.m_contactManager.m_broadPhase.GetProxyCount()};Box2D.Dynamics.b2World.prototype.CreateBody=function(def){Box2D.Common.b2Settings.b2Assert(!this.IsLocked());var b=Box2D.Dynamics.b2Body.Get(def,this);this.bodyList.AddBody(b);return b};Box2D.Dynamics.b2World.prototype.DestroyBody=function(b){Box2D.Common.b2Settings.b2Assert(!this.IsLocked());var jn=b.m_jointList;while(jn){var jn0=jn;jn=jn.next;if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeJoint(jn0.joint)}this.DestroyJoint(jn0.joint)}for(var node=b.GetControllerList().GetFirstNode();node;node=node.GetNextNode()){node.controller.RemoveBody(b)}for(var contactNode=b.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){this.m_contactManager.Destroy(contactNode.contact)}for(var fixtureNode=b.GetFixtureList().GetFirstNode();fixtureNode;fixtureNode=fixtureNode.GetNextNode()){if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeFixture(fixtureNode.fixture)}b.DestroyFixture(fixtureNode.fixture)}b.Destroy();this.bodyList.RemoveBody(b)};Box2D.Dynamics.b2World.prototype.CreateJoint=function(def){var j=Box2D.Dynamics.Joints.b2Joint.Create(def);j.m_prev=null;j.m_next=this.m_jointList;if(this.m_jointList){this.m_jointList.m_prev=j}this.m_jointList=j;this.m_jointCount++;j.m_edgeA.joint=j;j.m_edgeA.other=j.m_bodyB;j.m_edgeA.prev=null;j.m_edgeA.next=j.m_bodyA.m_jointList;if(j.m_bodyA.m_jointList){j.m_bodyA.m_jointList.prev=j.m_edgeA}j.m_bodyA.m_jointList=j.m_edgeA;j.m_edgeB.joint=j;j.m_edgeB.other=j.m_bodyA;j.m_edgeB.prev=null;j.m_edgeB.next=j.m_bodyB.m_jointList;if(j.m_bodyB.m_jointList){j.m_bodyB.m_jointList.prev=j.m_edgeB}j.m_bodyB.m_jointList=j.m_edgeB;var bodyA=def.bodyA;var bodyB=def.bodyB;if(!def.collideConnected){for(var contactNode=bodyB.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){if(contactNode.contact.GetOther(bodyB)==bodyA){contactNode.contact.FlagForFiltering()}}}return j};Box2D.Dynamics.b2World.prototype.DestroyJoint=function(j){var collideConnected=j.m_collideConnected;if(j.m_prev){j.m_prev.m_next=j.m_next}if(j.m_next){j.m_next.m_prev=j.m_prev}if(j==this.m_jointList){this.m_jointList=j.m_next}j.m_next=null;j.m_prev=null;var bodyA=j.m_bodyA;var bodyB=j.m_bodyB;bodyA.SetAwake(true);bodyB.SetAwake(true);if(j.m_edgeA.prev){j.m_edgeA.prev.next=j.m_edgeA.next}if(j.m_edgeA.next){j.m_edgeA.next.prev=j.m_edgeA.prev}if(j.m_edgeA==bodyA.m_jointList){bodyA.m_jointList=j.m_edgeA.next}j.m_edgeA.prev=null;j.m_edgeA.next=null;if(j.m_edgeB.prev){j.m_edgeB.prev.next=j.m_edgeB.next}if(j.m_edgeB.next){j.m_edgeB.next.prev=j.m_edgeB.prev}if(j.m_edgeB==bodyB.m_jointList){bodyB.m_jointList=j.m_edgeB.next}j.m_edgeB.prev=null;j.m_edgeB.next=null;this.m_jointCount--;if(!collideConnected){for(var contactNode=bodyB.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){if(contactNode.contact.GetOther(bodyB)==bodyA){contactNode.contact.FlagForFiltering()}}}};Box2D.Dynamics.b2World.prototype.GetControllerList=function(){return this.controllerList};Box2D.Dynamics.b2World.prototype.AddController=function(c){if(c.m_world!==null&amp;&amp;c.m_world!=this){throw new Error("Controller can only be a member of one world")}this.controllerList.AddController(c);c.m_world=this;return c};Box2D.Dynamics.b2World.prototype.RemoveController=function(c){this.controllerList.RemoveController(c);c.m_world=null;c.Clear()};Box2D.Dynamics.b2World.prototype.CreateController=function(controller){return this.AddController(controller)};Box2D.Dynamics.b2World.prototype.DestroyController=function(controller){this.RemoveController(controller)};Box2D.Dynamics.b2World.prototype.SetWarmStarting=function(flag){this.m_warmStarting=flag};Box2D.Dynamics.b2World.prototype.SetContinuousPhysics=function(flag){this.m_continuousPhysics=flag};Box2D.Dynamics.b2World.prototype.GetBodyCount=function(){return this.bodyList.GetBodyCount()};Box2D.Dynamics.b2World.prototype.GetJointCount=function(){return this.m_jointCount};Box2D.Dynamics.b2World.prototype.GetContactCount=function(){return this.contactList.GetContactCount()};Box2D.Dynamics.b2World.prototype.SetGravity=function(gravity){this.m_gravity=gravity};Box2D.Dynamics.b2World.prototype.GetGravity=function(){return this.m_gravity};Box2D.Dynamics.b2World.prototype.GetGroundBody=function(){return this.m_groundBody};Box2D.Dynamics.b2World.prototype.Step=function(dt,velocityIterations,positionIterations){if(this.m_newFixture){this.m_contactManager.FindNewContacts();this.m_newFixture=false}this.m_isLocked=true;this.mainTimeStep.Reset(dt,this.m_inv_dt0*dt,velocityIterations,positionIterations,this.m_warmStarting);this.m_contactManager.Collide();if(this.mainTimeStep.dt&gt;0){this.Solve(this.mainTimeStep);if(this.m_continuousPhysics){this.SolveTOI(this.mainTimeStep)}this.m_inv_dt0=this.mainTimeStep.inv_dt}this.m_isLocked=false};Box2D.Dynamics.b2World.prototype.ClearForces=function(){for(var node=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.dynamicBodies);node;node=node.GetNextNode()){node.body.m_force.SetZero();node.body.m_torque=0}};Box2D.Dynamics.b2World.prototype.DrawDebugData=function(){if(this.m_debugDraw===null){return}this.m_debugDraw.Clear();var flags=this.m_debugDraw.GetFlags();if(flags&amp;Box2D.Dynamics.b2DebugDraw.e_shapeBit){var color_inactive=Box2D.Dynamics.b2World.s_color_inactive;var color_static=Box2D.Dynamics.b2World.s_color_static;var color_kinematic=Box2D.Dynamics.b2World.s_color_kinematic;var color_dynamic_sleeping=Box2D.Dynamics.b2World.s_color_dynamic_sleeping;var color_dynamic_awake=Box2D.Dynamics.b2World.s_color_dynamic_awake;for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){var b=bodyNode.body;for(var fixtureNode=b.GetFixtureList().GetFirstNode();fixtureNode;fixtureNode=fixtureNode.GetNextNode()){var f=fixtureNode.fixture;var s=f.GetShape();if(!b.IsActive()){this.DrawShape(s,b.m_xf,color_inactive)}else if(b.GetType()==Box2D.Dynamics.b2BodyDef.b2_staticBody){this.DrawShape(s,b.m_xf,color_static)}else if(b.GetType()==Box2D.Dynamics.b2BodyDef.b2_kinematicBody){this.DrawShape(s,b.m_xf,color_kinematic)}else if(!b.IsAwake()){this.DrawShape(s,b.m_xf,color_dynamic_sleeping)}else{this.DrawShape(s,b.m_xf,color_dynamic_awake)}}}}if(flags&amp;Box2D.Dynamics.b2DebugDraw.e_jointBit){for(var j=this.m_jointList;j;j=j.m_next){this.DrawJoint(j)}}if(flags&amp;Box2D.Dynamics.b2DebugDraw.e_controllerBit){for(var controllerNode=this.controllerList.GetFirstNode();controllerNode;controllerNode=controllerNode.GetNextNode()){controllerNode.controller.Draw(this.m_debugDraw)}}if(flags&amp;Box2D.Dynamics.b2DebugDraw.e_pairBit){var pairColor=Box2D.Dynamics.b2World.s_pairColor;for(var contactNode=this.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){var fixtureA=contactNode.contact.GetFixtureA();var fixtureB=contactNode.contact.GetFixtureB();var cA=fixtureA.GetAABB().GetCenter();var cB=fixtureB.GetAABB().GetCenter();this.m_debugDraw.DrawSegment(cA,cB,pairColor);Box2D.Common.Math.b2Vec2.Free(cA);Box2D.Common.Math.b2Vec2.Free(cB)}}if(flags&amp;Box2D.Dynamics.b2DebugDraw.e_aabbBit){var aabbColor=Box2D.Dynamics.b2World.s_aabbColor;for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.activeBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){var b=bodyNode.body;for(var fixtureNode=b.GetFixtureList().GetFirstNode();fixtureNode;fixtureNode=fixtureNode.GetNextNode()){var f=fixtureNode.fixture;var aabb=this.m_contactManager.m_broadPhase.GetFatAABB(f.m_proxy);var vs=[Box2D.Common.Math.b2Vec2.Get(aabb.lowerBound.x,aabb.lowerBound.y),Box2D.Common.Math.b2Vec2.Get(aabb.upperBound.x,aabb.lowerBound.y),Box2D.Common.Math.b2Vec2.Get(aabb.upperBound.x,aabb.upperBound.y),Box2D.Common.Math.b2Vec2.Get(aabb.lowerBound.x,aabb.upperBound.y)];this.m_debugDraw.DrawPolygon(vs,4,aabbColor);Box2D.Common.Math.b2Vec2.Free(vs[0]);Box2D.Common.Math.b2Vec2.Free(vs[1]);Box2D.Common.Math.b2Vec2.Free(vs[2]);Box2D.Common.Math.b2Vec2.Free(vs[3])}}}if(flags&amp;Box2D.Dynamics.b2DebugDraw.e_centerOfMassBit){for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){var b=bodyNode.body;Box2D.Dynamics.b2World.s_xf.R=b.m_xf.R;Box2D.Dynamics.b2World.s_xf.position=b.GetWorldCenter();this.m_debugDraw.DrawTransform(Box2D.Dynamics.b2World.s_xf)}}};Box2D.Dynamics.b2World.prototype.QueryAABB=function(callback,aabb){this.m_contactManager.m_broadPhase.Query(callback,aabb)};Box2D.Dynamics.b2World.prototype.QueryPoint=function(callback,p){var WorldQueryWrapper=function(fixture){if(fixture.TestPoint(p)){return callback(fixture)}else{return true}};var aabb=Box2D.Collision.b2AABB.Get();aabb.lowerBound.Set(p.x-Box2D.Common.b2Settings.b2_linearSlop,p.y-Box2D.Common.b2Settings.b2_linearSlop);aabb.upperBound.Set(p.x+Box2D.Common.b2Settings.b2_linearSlop,p.y+Box2D.Common.b2Settings.b2_linearSlop);this.m_contactManager.m_broadPhase.Query(WorldQueryWrapper,aabb);Box2D.Collision.b2AABB.Free(aabb)};Box2D.Dynamics.b2World.prototype.RayCast=function(callback,point1,point2){var broadPhase=this.m_contactManager.m_broadPhase;var output=new Box2D.Collision.b2RayCastOutput;var RayCastWrapper=function(input,fixture){var hit=fixture.RayCast(output,input);if(hit){var flipFrac=1-output.fraction;var point=Box2D.Common.Math.b2Vec2.Get(flipFrac*point1.x+output.fraction*point2.x,flipFrac*point1.y+output.fraction*point2.y);var retVal=callback(fixture,point,output.normal,output.fraction);Box2D.Common.Math.b2Vec2.Free(point);return retVal}else{return input.maxFraction}};var input=new Box2D.Collision.b2RayCastInput(point1,point2,1);broadPhase.RayCast(RayCastWrapper,input)};Box2D.Dynamics.b2World.prototype.RayCastOne=function(point1,point2){var result=null;var RayCastOneWrapper=function(fixture,point,normal,fraction){result=fixture;return fraction};this.RayCast(RayCastOneWrapper,point1,point2);return result};Box2D.Dynamics.b2World.prototype.RayCastAll=function(point1,point2){var result=Box2D.Array.Get();var RayCastAllWrapper=function(fixture,point,normal,fraction){result.push(fixture);return 1};this.RayCast(RayCastAllWrapper,point1,point2);return result};Box2D.Dynamics.b2World.prototype.GetBodyList=function(){return this.bodyList};Box2D.Dynamics.b2World.prototype.GetJointList=function(){return this.m_jointList};Box2D.Dynamics.b2World.prototype.GetContactList=function(){return this.contactList};Box2D.Dynamics.b2World.prototype.IsLocked=function(){return this.m_isLocked};Box2D.Dynamics.b2World.prototype.Solve=function(step){for(var controllerNode=this.controllerList.GetFirstNode();controllerNode;controllerNode=controllerNode.GetNextNode()){controllerNode.controller.Step(step)}var m_island=this.island;m_island.Reset(this.m_contactManager.m_contactListener,this.m_contactSolver);for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){bodyNode.body.m_islandFlag=false}for(var contactNode=this.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){contactNode.contact.m_islandFlag=false}for(var j=this.m_jointList;j;j=j.m_next){j.m_islandFlag=false}var stack=Box2D.Dynamics.b2World.s_solveStack;for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.nonStaticActiveAwakeBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){var seed=bodyNode.body;if(seed.m_islandFlag){continue}m_island.Clear();stack.length=0;stack.push(seed);seed.m_islandFlag=true;while(stack.length&gt;0){var b=stack.pop();m_island.AddBody(b);if(!b.IsAwake()){b.SetAwake(true)}if(b.GetType()===Box2D.Dynamics.b2BodyDef.b2_staticBody){continue}for(var contactNode=b.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.nonSensorEnabledTouchingContacts);contactNode;contactNode=contactNode.GetNextNode()){var contact=contactNode.contact;if(contact.m_islandFlag){continue}m_island.AddContact(contact);contact.m_islandFlag=true;var other=contact.GetOther(b);if(other.m_islandFlag){continue}stack.push(other);other.m_islandFlag=true}for(var jn=b.m_jointList;jn;jn=jn.next){if(jn.joint.m_islandFlag||!jn.other.IsActive()){continue}m_island.AddJoint(jn.joint);jn.joint.m_islandFlag=true;if(jn.other.m_islandFlag){continue}stack.push(jn.other);jn.other.m_islandFlag=true}}m_island.Solve(step,this.m_gravity,this.m_allowSleep)}for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.nonStaticActiveAwakeBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){bodyNode.body.SynchronizeFixtures()}this.m_contactManager.FindNewContacts()};Box2D.Dynamics.b2World.prototype.SolveTOI=function(step){var m_island=this.island;m_island.Reset(this.m_contactManager.m_contactListener,this.m_contactSolver);for(var bodyNode=this.bodyList.GetFirstNode(Box2D.Dynamics.b2BodyList.TYPES.allBodies);bodyNode;bodyNode=bodyNode.GetNextNode()){var b=bodyNode.body;b.m_islandFlag=false;b.m_sweep.t0=0}for(var contactNode=this.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){contactNode.contact.m_islandFlag=false;contactNode.contact.m_toi=null}for(var j=this.m_jointList;j;j=j.m_next){j.m_islandFlag=false}while(true){var toi2=this._SolveTOI2(step);var minContact=toi2.minContact;var minTOI=toi2.minTOI;if(minContact===null||Box2D.Dynamics.b2World.MAX_TOI&lt;minTOI){break}var fixtureABody=minContact.m_fixtureA.GetBody();var fixtureBBody=minContact.m_fixtureB.GetBody();Box2D.Dynamics.b2World.s_backupA.Set(fixtureABody.m_sweep);Box2D.Dynamics.b2World.s_backupB.Set(fixtureBBody.m_sweep);fixtureABody.Advance(minTOI);fixtureBBody.Advance(minTOI);minContact.Update(this.m_contactManager.m_contactListener);minContact.m_toi=null;if(minContact.IsSensor()||!minContact.IsEnabled()){fixtureABody.m_sweep.Set(Box2D.Dynamics.b2World.s_backupA);fixtureBBody.m_sweep.Set(Box2D.Dynamics.b2World.s_backupB);fixtureABody.SynchronizeTransform();fixtureBBody.SynchronizeTransform();continue}if(!minContact.IsTouching()){continue}var seed=fixtureABody;if(seed.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody){seed=fixtureBBody}m_island.Clear();var queue=Box2D.Dynamics.b2World.s_solveQueue;queue.length=0;queue.push(seed);seed.m_islandFlag=true;while(queue.length&gt;0){var b=queue.shift();m_island.AddBody(b);if(!b.IsAwake()){b.SetAwake(true)}if(b.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody){continue}for(var contactNode=b.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.nonSensorEnabledTouchingContacts);contactNode;contactNode=contactNode.GetNextNode()){if(m_island.m_contactCount==Box2D.Common.b2Settings.b2_maxTOIContactsPerIsland){break}var contact=contactNode.contact;if(contact.m_islandFlag){continue}m_island.AddContact(contact);contact.m_islandFlag=true;var other=contact.GetOther(b);if(other.m_islandFlag){continue}if(other.GetType()!=Box2D.Dynamics.b2BodyDef.b2_staticBody){other.Advance(minTOI);other.SetAwake(true);queue.push(other)}other.m_islandFlag=true}for(var jEdge=b.m_jointList;jEdge;jEdge=jEdge.next){if(m_island.m_jointCount==Box2D.Common.b2Settings.b2_maxTOIJointsPerIsland){continue}if(jEdge.joint.m_islandFlag||!jEdge.other.IsActive()){continue}m_island.AddJoint(jEdge.joint);jEdge.joint.m_islandFlag=true;if(jEdge.other.m_islandFlag){continue}if(jEdge.other.GetType()!=Box2D.Dynamics.b2BodyDef.b2_staticBody){jEdge.other.Advance(minTOI);jEdge.other.SetAwake(true);queue.push(jEdge.other)}jEdge.other.m_islandFlag=true}}this.islandTimeStep.Reset((1-minTOI)*step.dt,0,step.velocityIterations,step.positionIterations,false);m_island.SolveTOI(this.islandTimeStep);for(var i=0;i&lt;m_island.m_bodies.length;i++){m_island.m_bodies[i].m_islandFlag=false;if(!m_island.m_bodies[i].IsAwake()||m_island.m_bodies[i].GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody){continue}m_island.m_bodies[i].SynchronizeFixtures();for(var contactNode=m_island.m_bodies[i].contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.allContacts);contactNode;contactNode=contactNode.GetNextNode()){contactNode.contact.m_toi=null}}for(var i=0;i&lt;m_island.m_contactCount;i++){m_island.m_contacts[i].m_islandFlag=false;m_island.m_contacts[i].m_toi=null}for(var i=0;i&lt;m_island.m_jointCount;i++){m_island.m_joints[i].m_islandFlag=false}this.m_contactManager.FindNewContacts()}};Box2D.Dynamics.b2World.prototype._SolveTOI2=function(step){var minContact=null;var minTOI=1;for(var contactNode=this.contactList.GetFirstNode(Box2D.Dynamics.Contacts.b2ContactList.TYPES.nonSensorEnabledContinuousContacts);contactNode;contactNode=contactNode.GetNextNode()){var c=contactNode.contact;if(this._SolveTOI2SkipContact(step,c)){continue}var toi=1;if(c.m_toi!=null){toi=c.m_toi}else if(c.IsTouching()){toi=1;c.m_toi=toi}else{var fixtureABody=c.m_fixtureA.GetBody();var fixtureBBody=c.m_fixtureB.GetBody();var t0=fixtureABody.m_sweep.t0;if(fixtureABody.m_sweep.t0&lt;fixtureBBody.m_sweep.t0){t0=fixtureBBody.m_sweep.t0;fixtureABody.m_sweep.Advance(t0)}else if(fixtureBBody.m_sweep.t0&lt;fixtureABody.m_sweep.t0){t0=fixtureABody.m_sweep.t0;fixtureBBody.m_sweep.Advance(t0)}toi=c.ComputeTOI(fixtureABody.m_sweep,fixtureBBody.m_sweep);Box2D.Common.b2Settings.b2Assert(0&lt;=toi&amp;&amp;toi&lt;=1);if(toi&gt;0&amp;&amp;toi&lt;1){toi=(1-toi)*t0+toi}c.m_toi=toi}if(Number.MIN_VALUE&lt;toi&amp;&amp;toi&lt;minTOI){minContact=c;minTOI=toi}}var result=Box2D.Dynamics.b2World.s_solveTOI2Result;result.minContact=minContact;result.minTOI=minTOI;return result};Box2D.Dynamics.b2World.prototype._SolveTOI2SkipContact=function(step,c){var fixtureABody=c.m_fixtureA.GetBody();var fixtureBBody=c.m_fixtureB.GetBody();if((fixtureABody.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody||!fixtureABody.IsAwake())&amp;&amp;(fixtureBBody.GetType()!=Box2D.Dynamics.b2BodyDef.b2_dynamicBody||!fixtureBBody.IsAwake())){return true}return false};Box2D.Dynamics.b2World.prototype.DrawJoint=function(joint){if(joint instanceof Box2D.Dynamics.Joints.b2DistanceJoint||joint instanceof Box2D.Dynamics.Joints.b2MouseJoint){var anchorA=joint.GetAnchorA();var anchorB=joint.GetAnchorB();this.m_debugDraw.DrawSegment(anchorA,anchorB,Box2D.Dynamics.b2World.s_jointColor);Box2D.Common.Math.b2Vec2.Free(anchorA);Box2D.Common.Math.b2Vec2.Free(anchorB)}else if(joint instanceof Box2D.Dynamics.Joints.b2PulleyJoint){var anchorA=joint.GetAnchorA();var anchorB=joint.GetAnchorB();var groundA=joint.GetGroundAnchorA();var groundB=joint.GetGroundAnchorB();this.m_debugDraw.DrawSegment(groundA,anchorA,Box2D.Dynamics.b2World.s_jointColor);this.m_debugDraw.DrawSegment(groundB,anchorB,Box2D.Dynamics.b2World.s_jointColor);this.m_debugDraw.DrawSegment(groundA,groundB,Box2D.Dynamics.b2World.s_jointColor);Box2D.Common.Math.b2Vec2.Free(anchorA);Box2D.Common.Math.b2Vec2.Free(anchorB);Box2D.Common.Math.b2Vec2.Free(groundA);Box2D.Common.Math.b2Vec2.Free(groundB)}else{var anchorA=joint.GetAnchorA();var anchorB=joint.GetAnchorB();if(joint.GetBodyA()!=this.m_groundBody){this.m_debugDraw.DrawSegment(joint.GetBodyA().m_xf.position,anchorA,Box2D.Dynamics.b2World.s_jointColor)}this.m_debugDraw.DrawSegment(anchorA,anchorB,Box2D.Dynamics.b2World.s_jointColor);if(joint.GetBodyB()!=this.m_groundBody){this.m_debugDraw.DrawSegment(joint.GetBodyB().m_xf.position,anchorB,Box2D.Dynamics.b2World.s_jointColor)}Box2D.Common.Math.b2Vec2.Free(anchorA);Box2D.Common.Math.b2Vec2.Free(anchorB)}};Box2D.Dynamics.b2World.prototype.DrawShape=function(shape,xf,color){if(shape instanceof Box2D.Collision.Shapes.b2CircleShape){var circle=shape;var center=Box2D.Common.Math.b2Math.MulX(xf,circle.m_p);var radius=circle.m_radius;var axis=xf.R.col1;this.m_debugDraw.DrawSolidCircle(center,radius,axis,color);Box2D.Common.Math.b2Vec2.Free(center)}else if(shape instanceof Box2D.Collision.Shapes.b2PolygonShape){var i=0;var poly=shape;var vertexCount=poly.GetVertexCount();var localVertices=poly.GetVertices();var vertices=Box2D.Array.Get();for(i=0;i&lt;vertexCount;i++){vertices[i]=Box2D.Common.Math.b2Math.MulX(xf,localVertices[i])}this.m_debugDraw.DrawSolidPolygon(vertices,vertexCount,color);for(i=0;i&lt;vertexCount;i++){Box2D.Common.Math.b2Vec2.Free(vertices[i])}}else if(shape instanceof Box2D.Collision.Shapes.b2EdgeShape){var edge=shape;var v1=Box2D.Common.Math.b2Math.MulX(xf,edge.GetVertex1());var v2=Box2D.Common.Math.b2Math.MulX(xf,edge.GetVertex2());this.m_debugDraw.DrawSegment(v1,v2,color);Box2D.Common.Math.b2Vec2.Free(v1);Box2D.Common.Math.b2Vec2.Free(v2)}};Box2D.Dynamics.b2World._freeCache=[];Box2D.Dynamics.b2World.Get=function(gravity,doSleep){var cache=this._freeCache;var o;if(cache.length&gt;0){o=cache.pop();this.call(o,gravity,doSleep)}else{o=new this(gravity,doSleep)}return o};Box2D.Dynamics.b2World.Free=function(o){this._freeCache.push(o)};Box2D.Dynamics.b2World.s_xf=new Box2D.Common.Math.b2Transform;Box2D.Dynamics.b2World.s_backupA=new Box2D.Common.Math.b2Sweep;Box2D.Dynamics.b2World.s_backupB=new Box2D.Common.Math.b2Sweep;Box2D.Dynamics.b2World.s_jointColor=new Box2D.Common.b2Color(.5,.8,.8);Box2D.Dynamics.b2World.s_color_inactive=new Box2D.Common.b2Color(.5,.5,.3);Box2D.Dynamics.b2World.s_color_static=new Box2D.Common.b2Color(.5,.9,.5);Box2D.Dynamics.b2World.s_color_kinematic=new Box2D.Common.b2Color(.5,.5,.9);Box2D.Dynamics.b2World.s_color_dynamic_sleeping=new Box2D.Common.b2Color(.6,.6,.6);Box2D.Dynamics.b2World.s_color_dynamic_awake=new Box2D.Common.b2Color(.9,.7,.7);Box2D.Dynamics.b2World.s_pairColor=new Box2D.Common.b2Color(.3,.9,.9);Box2D.Dynamics.b2World.s_aabbColor=new Box2D.Common.b2Color(0,0,.8);Box2D.Dynamics.b2Body.prototype.SetUserData=function(userData){this.userData=userData};Box2D.Dynamics.b2Body.prototype.GetUserData=function(){return this.userData};Box2D.Dynamics.b2Fixture.prototype.SetUserData=function(userData){this.userData=userData};Box2D.Dynamics.b2Fixture.prototype.GetUserData=function(){return this.userData};Box2D.Dynamics.b2Fixture.prototype.ResizeShapeAsBox=function(hx,hy){this.m_shape.SetAsBox(hx,hy)};Box2D.Dynamics.b2Fixture.prototype.ResizeShapeAsCircle=function(radius){this.m_shape.SetRadius(radius)};Box2D.Dynamics.b2Body.prototype.ResizeFixtureShapesAsBox=function(hx,hy){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.ResizeShapeAsBox(hx,hy)}this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.ResizeFixtureShapesAsCircle=function(radius){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.ResizeShapeAsCircle(radius)}this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.ChangeFixtureDensities=function(value){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.SetDensity(value)}this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.ChangeFixtureFrictions=function(value){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.SetFriction(value)}this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.ChangeFixtureRestitutions=function(value){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.SetRestitution(value)}this.ResetMassData()};gs.html5={};gs.html5.text={};gs.LocalStorage={prefix:"",isAvailable:function(){try{return localStorage&amp;&amp;typeof localStorage!=="undefined"}catch(e){return false}},setPrefix:function(prefix){gs.LocalStorage.prefix=prefix},formatRealKey:function(virtualKey){return gs.LocalStorage.prefix+virtualKey},getString:function(virtualKey){var realKey=gs.LocalStorage.formatRealKey(virtualKey);var theString=null;if(gs.LocalStorage.isAvailable()){try{theString=localStorage.getItem(realKey)}catch(exception){gs.Log.error("LocalStorage read failed:",virtualKey)}}return theString},setString:function(virtualKey,value){try{var realKey=gs.LocalStorage.formatRealKey(virtualKey);localStorage.removeItem(realKey);if(value){localStorage.setItem(realKey,value)}}catch(exception){gs.Log.error("LocalStorage write failed:",virtualKey)}},getObject:function(virtualKey){var theString=gs.LocalStorage.getString(virtualKey);var theObject=null;if(theString!==null){try{theObject=JSON.parse(theString)}catch(exception){gs.Log.error("LocalStorage object parsing failed:",virtualKey)}}return theObject},setObject:function(virtualKey,value){try{var theString=JSON.stringify(value);gs.LocalStorage.setString(virtualKey,theString)}catch(exception){gs.Log.error("LocalStorage object serialization failed:",virtualKey)}},getAll:function(){var map={};var prefix=gs.LocalStorage.prefix;Object.keys(localStorage).forEach(function(key){if(key.substr(0,prefix.length)===prefix){map[key.substr(prefix.length)]=localStorage.getItem(key)}});return map}};gs.html5.Audio={createAudioElement:function(){return document.createElement("AUDIO")},isWebAudioExtensionSupported:function(){var testContext=gs.html5.Audio.createAudioContext();return testContext!==null},createAudioContext:function(){if(typeof AudioContext!=="undefined"){return new AudioContext}if(typeof webkitAudioContext!=="undefined"){var context=new webkitAudioContext;if(typeof context.createGain==="function"){return context}}return null},canPlayExtension:function(extension){if(!extension){return false}var audioFormat=null;var lowerExtension=extension.toLowerCase();switch(lowerExtension){case"m4a":audioFormat="mp4";break;default:audioFormat=lowerExtension;break}var mediaType="audio/"+audioFormat;return this.canPlayType(mediaType)},canPlayType:function(mediaType){if(!this.canPlayTypeCache){this.canPlayTypeCache={}}if(mediaType in this.canPlayTypeCache){return this.canPlayTypeCache[mediaType]}var canPlay=false;var testElement=this.createAudioElement();try{canPlay=!!(testElement.canPlayType&amp;&amp;testElement.canPlayType(mediaType).replace(/no/,""))}catch(exception){canPlay=false}this.canPlayTypeCache[mediaType]=canPlay;return canPlay}};gs.html5.GraphicsBuffer=function(width,height,acquireContext){this.canvas=null;this.context=null;this.width=width||0;this.height=height||0;this.canvas=gs.dom.createCanvas();this.canvas.width=this.width;this.canvas.height=this.height;this.canvas.style.backgroundColor="transparent";if(acquireContext!==false){this.context=this.canvas.getContext("2d")}};gs.html5.GraphicsBuffer.acquire=function(canvas){var buffer=new gs.html5.GraphicsBuffer(0,0,false);buffer.acquire(canvas);return buffer};gs.html5.GraphicsBuffer.prototype={acquire:function(canvas){this.releaseContext();this.canvas=canvas;this.width=canvas.width;this.height=canvas.height},resize:function(width,height){if(this.width!==width||this.height!==height){this.canvas.width=width;this.canvas.height=height;this.width=width;this.height=height}},releaseContext:function(){this.context=null},clear:function(color,op){var context=this.context;if(!color){color="transparent"}if(!op){op="copy"}var oldColor=this.context.fillStyle;var oldOp=context.globalCompositeOperation;context.fillStyle=color;context.globalCompositeOperation=op;context.fillRect(0,0,this.width,this.height);context.fillStype=oldColor;context.globalCompositeOperation=oldOp}};gs.html5.Canvas={createCanvasElement:function(width,height){var canvasElement=document.createElement("CANVAS");canvasElement.style.backgroundColor="transparent";if(width!==undefined&amp;&amp;height!==undefined){canvasElement.width=width;canvasElement.height=height}return canvasElement},createCanvasBuffer:function(width,height){return new gs.html5.GraphicsBuffer(width,height)},createTintedImage:function(image,r,g,b){var width=image.width;var height=image.height;var buffer=gs.html5.Canvas.createCanvasBuffer(width,height);buffer.context.drawImage(image,0,0,width,height);var imageData=buffer.context.getImageData(0,0,width,height);gs.html5.Canvas.tintImageData(imageData,width,height,r,g,b);buffer.context.putImageData(imageData,0,0);return buffer.canvas},tintImageData:function(imageData,width,height,r,g,b){var i,j;var mult=[];var multr=mult[r]=[];for(i=0,j=0;i&lt;256;++i){multr[i]=j|0;j+=r}var multg=mult[g]||[];if(!mult[g]){mult[g]=multg;j=0;for(i=0,j=0;i&lt;256;++i){multg[i]=j|0;j+=g}}var multb=mult[b]||[];if(!mult[b]){mult[b]=multb;j=0;for(i=0,j=0;i&lt;256;++i){multb[i]=j|0;j+=b}}var data=imageData.data;var end=width*height*4;for(var index=0;index!==end;index+=2){data[index]=multr[data[index]];index++;data[index]=multg[data[index]];index++;data[index]=multb[data[index]]}},createCroppedImage:function(image,width,height,anchorHorizontal,anchorVertical){var x=0;var y=0;switch(anchorHorizontal){case"left":break;case"center":x=Math.floor((image.width-width)/2);break;case"right":x=image.width-width;break}switch(anchorVertical){case"top":break;case"center":y=Math.floor((image.height-height)/2);break;case"bottom":y=image.height-height;break}var buffer=gs.html5.Canvas.createCanvasBuffer(width,height);buffer.context.drawImage(image,-x,-y);return buffer.canvas},createPaddedImage:function(image,width,height){var buffer=gs.html5.Canvas.createCanvasBuffer(width,height);if(width&gt;0&amp;&amp;height&gt;0&amp;&amp;image.width&gt;0&amp;&amp;image.height&gt;0){var x=Math.floor((width-image.width)/2);var y=Math.floor((height-image.height)/2);buffer.context.drawImage(image,x,y)}return buffer.canvas},createTiledImage:function(image,width,height,tileWidth,tileHeight,repeat){if(!repeat){repeat="repeat"}if(image.width===0||image.height===0){return gs.html5.createCanvasElement(width,height)}var tileCanvas=gs.html5.Canvas.createCanvasBuffer(tileWidth,tileHeight);tileCanvas.context.drawImage(image,0,0,tileWidth,tileHeight);if(width%tileWidth!==0){width=Math.ceil(width/tileWidth)*tileWidth}if(height%tileHeight!==0){height=Math.ceil(height/tileHeight)*tileHeight}var buffer=gs.html5.Canvas.createCanvasBuffer(width,height);buffer.context.fillStyle=buffer.context.createPattern(tileCanvas.canvas,repeat);buffer.context.fillRect(0,0,width,height);return buffer.canvas},createTiledImageHorizontal:function(image,width,tileWidth){return gs.html5.Canvas.createTiledImage(image,width,image.height,tileWidth,image.height,"repeat-x")},createTiledImageVertical:function(image,height,tileHeight){return gs.html5.Canvas.createTiledImage(image,image.width,height,image.width,tileHeight,"repeat-y")}};gs.AspectRatio={ASPECT_INVALID:0,ASPECT_1_1:100,ASPECT_4_3:133,ASPECT_3_2:150,ASPECT_16_10:160,ASPECT_15_9:167,ASPECT_16_9:178};gs.AspectRatio.approximate=function(width,height){if(width===0||height===0){return gs.ASPECT_INVALID}var ratio=width/height;if(ratio&lt;1){ratio=1/ratio}var rounded=Math.round(ratio*100);for(var key in gs.AspectRatio){var standard=gs.AspectRatio[key];if(Math.abs(standard-rounded)&lt;2){return standard}}return rounded};gs.ViewportFit={NONE:"NONE",CENTER:"CENTER",FILL:"FILL",LETTERBOX:"LETTERBOX",OVERSCAN:"OVERSCAN",STRETCH:"STRETCH"};gs.ViewportReference={GAME:"GAME",FRAME:"FRAME",WINDOW:"WINDOW",SCREEN:"SCREEN"};gs.ViewportScale={STRETCH:"STRETCH",RESIZE:"RESIZE",QUALITY:"QUALITY",PERFORMANCE:"PERFORMANCE",WHOLE_MULTIPLE_PERFORMANCE:"WHOLE_MULTIPLE_PERFORMANCE",WHOLE_MULTIPLE_QUALITY:"WHOLE_MULTIPLE_QUALITY"};gs.html5.Viewport=function(){this.frame=null;this.frameWidth=0;this.frameHeight=0;this.drawBuffer=new gs.html5.GraphicsBuffer(0,0,false);this.drawWidth=0;this.drawHeightCSS=0;this.drawWidthPixel=0;this.drawHeightPixel=0;this.input=gs.dom.create("DIV");this.inputWidth=0;this.inputHeight=0;this.designWidth=0;this.designHeight=0;this.overlay=gs.dom.create("DIV");this.overlayWidth=0;this.overlayHeight=0;this.overlayCount=0;this.overlayLayer=null;this.overlayParent=null;this.overlayRequestCount=gs.globalOptions.dynamicOverlayLayerInitiallyVisible?1:0;this.gameWidth=0;this.gameHeight=0;this.gameAspect=gs.AspectRatio.ASPECT_INVALID;this.gameIsPortrait=false;this.windowWidth=0;this.windowHeight=0;this.screenWidth=window.screen.width;this.screenHeight=window.screen.height;this.reportWidth=0;this.reportHeight=0;this.reportAspect=gs.AspectRatio.ASPECT_INVALID;this.reference=gs.ViewportReference.FRAME;this.scale=gs.ViewportScale.QUALITY;this.fit=gs.ViewportFit.LETTERBOX;this.factor=1;this.zoom=1;var devicePixelRatio=window.devicePixelRatio||1;this.cssFactor=Math.floor(devicePixelRatio);if(this.cssFactor&lt;1||gs.platform===gs.firefox||navigator&amp;&amp;navigator.userAgent.match(/(iPad)|(iPhone)/)){this.cssFactor=1}};gs.html5.Viewport.prototype={setFrame:function(frameElement){this.frame=frameElement;this.updateFrameSize()},setCanvas:function(canvasElement){this.drawBuffer.acquire(canvasElement);this.frame=canvasElement.parentNode;var style=gs.dom.getComputedStyle(this.frame);this.frameWidth=parseInt(style.width,10);this.frameHeight=parseInt(style.height,10)},shouldReportTrueSize:function(){return this.fit===gs.ViewportFit.OVERSCAN},setReportSize:function(width,height){this.reportWidth=width;this.reportHeight=height;this.reportAspect=gs.AspectRatio.approximate(width,height)},appendOverlay:function(element){this.overlay.appendChild(element);this.overlayCount++;if(this.frame){this.frame.appendChild(this.overlay)}},resizeFrame:function(width,height){if(gs.globalOptions.forceViewportOrientationMatch){var targetIsPortrait=height&gt;width;if(targetIsPortrait!==this.gameIsPortrait){var swap=width;width=height;height=swap}}gs.dom.resizeElement(this.frame,width,height);this.frameWidth=width;this.frameHeight=height},resizeInput:function(width,height){gs.dom.resizeElement(this.input,width,height);this.inputWidth=width;this.inputHeight=height},resizeOverlay:function(width,height){gs.dom.resizeElement(this.overlay,width,height);this.overlayWidth=width;this.overlayHeight=height},resizeBuffer:function(cssWidth,cssHeight){var pixelWidth=cssWidth*this.cssFactor;var pixelHeight=cssHeight*this.cssFactor;var scaleX=pixelWidth/this.gameWidth;var scaleY=pixelHeight/this.gameHeight;var scaleMin=Math.min(scaleX,scaleY);var scaleMax=Math.max(scaleX,scaleY);var scale;var scaleWhole;var bufferWidth;var bufferHeight;var stretchPixelCount=this.gameWidth*this.gameHeight;var resizePixelCount=pixelWidth*pixelHeight;switch(this.scale){case gs.ViewportScale.STRETCH:bufferWidth=this.gameWidth;bufferHeight=this.gameHeight;break;case gs.ViewportScale.RESIZE:bufferWidth=pixelWidth;bufferHeight=pixelHeight;break;case gs.ViewportScale.QUALITY:if(stretchPixelCount&gt;resizePixelCount){bufferWidth=this.gameWidth;bufferHeight=this.gameHeight}else{bufferWidth=pixelWidth;bufferHeight=pixelHeight}break;case gs.ViewportScale.PERFORMANCE:if(stretchPixelCount&lt;resizePixelCount){bufferWidth=this.gameWidth;bufferHeight=this.gameHeight}else{bufferWidth=pixelWidth;bufferHeight=pixelHeight}break;case gs.ViewportScale.WHOLE_MULTIPLE_PERFORMANCE:if(scaleMin&gt;=1){scale=scaleMin;scaleWhole=Math.floor(scale)}else if(scaleMax&lt;1){scale=scaleMax;scaleWhole=1/Math.floor(1/scale)}bufferWidth=this.gameWidth*scaleWhole;bufferHeight=this.gameHeight*scaleWhole;break;case gs.ViewportScale.WHOLE_MULTIPLE_QUALITY:if(scaleMin&gt;=1){scale=scaleMin;scaleWhole=Math.ceil(scale)}else if(scaleMax&lt;1){scale=scaleMax;scaleWhole=1/Math.floor(1/scale)}bufferWidth=this.gameWidth*scaleWhole;bufferHeight=this.gameHeight*scaleWhole;break;default:gs.Log.error("Unrecognized viewport scale:",this.scale)}var factor=1/Math.sqrt(this.factor);bufferWidth=Math.ceil(bufferWidth*factor);bufferHeight=Math.ceil(bufferHeight*factor);var cssScaleX=cssWidth/bufferWidth;var cssScaleY=cssHeight/bufferHeight;var transformOrigin="0 0";var transform="scale3d("+cssScaleX+","+cssScaleY+",1)";gs.dom.resizeElement(this.drawBuffer.canvas,bufferWidth,bufferHeight);this.drawBuffer.canvas.style.transformOrigin=transformOrigin;this.drawBuffer.canvas.style.transform=transform;this.drawBuffer.canvas.style.webkitTransformOrigin=transformOrigin;this.drawBuffer.canvas.style.webkitTransform=transform;this.drawBuffer.resize(bufferWidth,bufferHeight)},refitBuffer:function(width,height){if(gs.globalOptions.forceViewportOrientationMatch){var targetIsPortrait=height&gt;width;if(targetIsPortrait!==this.gameIsPortrait){var swap=width;width=height;height=swap}}var aspect=this.gameWidth/this.gameHeight;var scaleX=width/this.gameWidth;var scaleY=height/this.gameHeight;var scaleMin=Math.min(scaleX,scaleY);var scaleMax=Math.max(scaleX,scaleY);var drawWidth;var drawHeight;var left,top;switch(this.fit){case gs.ViewportFit.NONE:drawWidth=this.gameWidth;drawHeight=this.gameHeight;left=0;top=0;break;case gs.ViewportFit.CENTER:drawWidth=this.gameWidth;drawHeight=this.gameHeight;left=Math.floor(.5*(this.frameWidth-drawWidth));top=Math.floor(.5*(this.frameHeight-drawHeight));break;case gs.ViewportFit.FILL:case gs.ViewportFit.STRETCH:drawWidth=width;drawHeight=height;left=0;top=0;break;case gs.ViewportFit.LETTERBOX:if(scaleMin===scaleX){drawWidth=width;drawHeight=Math.floor(drawWidth/aspect);left=0;top=Math.floor(.5*(this.frameHeight-drawHeight))}else{drawHeight=height;drawWidth=Math.floor(drawHeight*aspect);left=Math.floor(.5*(this.frameWidth-drawWidth));top=0}break;case gs.ViewportFit.OVERSCAN:if(scaleMax===scaleX){drawWidth=width;drawHeight=Math.floor(width/aspect);left=0;top=Math.floor(.5*(this.frameHeight-drawHeight))}else{drawHeight=height;drawWidth=Math.floor(height*aspect);left=Math.floor(.5*(this.frameWidth-drawWidth));top=0}break;default:gs.Log.error("Unrecognized viewport fit:",this.fit);break}this.resizeBuffer(drawWidth,drawHeight);this.resizeInput(drawWidth,drawHeight);this.resizeOverlay(drawWidth,drawHeight);gs.dom.repositionElement(this.input,left,top);gs.dom.repositionElement(this.drawBuffer.canvas,0,0);gs.dom.repositionElement(this.overlay,0,0)},updateGameSize:function(width,height){this.gameWidth=width;this.gameHeight=height;this.gameIsPortrait=height&gt;width;this.gameAspect=gs.AspectRatio.approximate(width,height)},updateWindowSize:function(width,height){this.windowWidth=width;this.windowHeight=height},updateFrameSize:function(){if(this.frame){var style=gs.dom.getComputedStyle(this.frame);if(style){this.frameWidth=parseInt(style.width,10);this.frameHeight=parseInt(style.height,10)}else{this.frameWidth=this.gameWidth;this.frameHeight=this.gameHeight}}},relayout:function(){switch(this.reference){case gs.ViewportReference.GAME:this.resizeFrame(this.gameWidth,this.gameHeight);this.refitBuffer(this.gameWidth,this.gameHeight);this.setReportSize(this.gameWidth,this.gameHeight);break;case gs.ViewportReference.FRAME:this.updateFrameSize();this.refitBuffer(this.frameWidth,this.frameHeight);if(this.shouldReportTrueSize()){this.setReportSize(this.frameWidth,this.frameHeight)}else{this.setReportSize(this.gameWidth,this.gameHeight)}break;case gs.ViewportReference.WINDOW:this.resizeFrame(this.windowWidth,this.windowHeight);this.refitBuffer(this.windowWidth,this.windowHeight);if(this.shouldReportTrueSize()){this.setReportSize(this.windowWidth,this.windowHeight)}else{this.setReportSize(this.gameWidth,this.gameHeight)}break;case gs.ViewportReference.SCREEN:this.screenWidth=window.screen.width;this.screenHeight=window.screen.height;var cssWidth=this.screenWidth/this.cssFactor;var cssHeight=this.screenHeight/this.cssFactor;this.resizeFrame(cssWidth,cssHeight);this.refitBuffer(cssWidth,cssHeight);if(this.shouldReportTrueSize()){this.setReportSize(this.screenWidth,this.screenHeight)}else{this.setReportSize(this.gameWidth,this.gameHeight)}break;default:gs.Log.error("Unrecognized viewport reference:",this.reference);break}},show:function(){if(this.drawBuffer.parentNode!==this.frame){this.drawBuffer.canvas.style.position="absolute";if(!gs.globalOptions.forceInputEventsOnCanvas){this.drawBuffer.canvas.style.pointerEvents="none"}this.drawBuffer.canvas.mozOpaque=true;this.input.style.position="absolute";this.input.style.backgroundColor="transparent";if(this.frame.hasChildNodes()){this.frame.insertBefore(this.input,this.frame.firstChild)}else{this.frame.appendChild(this.input)}this.input.appendChild(this.drawBuffer.canvas);this.overlay.style.position="absolute";this.overlay.style.pointerEvents="none";if(this.overlayCount&gt;0){this.frame.appendChild(this.overlay)}}if(!this.overlayLayer){var gseOverlays=document.getElementsByClassName("gse-overlay");if(gseOverlays&amp;&amp;gseOverlays.length&gt;0){this.overlayLayer=gseOverlays[0];if(this.overlayLayer){this.overlayParent=this.overlayLayer.parentNode;if(this.overlayRequestCount===0&amp;&amp;this.overlayParent){if(gs.globalOptions.useDynamicOverlayLayer){try{this.overlayParent.removeChild(this.overlayLayer)}catch(exception){}}}}}}},setZoom:function(zoom){this.zoom=zoom;this.frame.style.zoom=zoom},showOverlayLayer:function(){if(!gs.globalOptions.useDynamicOverlayLayer)return;this.overlayRequestCount++;if(this.overlayRequestCount===1&amp;&amp;this.overlayLayer&amp;&amp;this.overlayParent){try{this.overlayParent.appendChild(this.overlayLayer)}catch(exception){}}},hideOverlayLayer:function(){if(!gs.globalOptions.useDynamicOverlayLayer)return;if(this.overlayRequestCount&gt;0){this.overlayRequestCount--}if(this.overlayRequestCount===0&amp;&amp;this.overlayLayer&amp;&amp;this.overlayParent){try{this.overlayParent.removeChild(this.overlayLayer)}catch(exception){}}}};gs.html5.text.Font=function(family,sizePx){this.family=family;this.sizePx=sizePx};gs.html5.text.Font.toCSS=function(family,sizePx){return sizePx.toString()+"px "+family};gs.html5.text.Font.prototype={toCSS:function(){return gs.html5.text.Font.toCSS(this.family,this.sizePx)}};gs.html5.text.FontPicker=function(){this.fontMap={};this.familyMap={};this.testBuffer=new gs.html5.GraphicsBuffer;this.testSizePx=20;this.testString="abcdefghijklmnopqrstuvwxyz 0123456789";this.fallbackFamily="sans-serif";var invalidFamily="sans-serif";this.invalidWidth=this.measureTestWidth(invalidFamily)};gs.html5.text.FontPicker.prototype={measureTestWidth:function(family){var context=this.testBuffer.context;context.font=gs.html5.text.Font.toCSS(family,this.testSizePx);var metrics=context.measureText(this.testString);return metrics.width},pickBestFont:function(family,sizePx){family+=", "+this.fallbackFamily;var key=gs.html5.text.Font.toCSS(family,sizePx);var bestFont=this.fontMap[key];if(bestFont){return bestFont}var bestName=this.familyMap[family];if(bestName){bestFont=new gs.html5.text.Font(bestName,sizePx);this.fontMap[key]=bestFont;return bestFont}var testWidth=this.measureTestWidth(family);if(!testWidth||isNaN(testWidth)||testWidth&lt;1||testWidth===this.invalidWidth){bestFont=new gs.html5.text.Font(this.fallbackFamily,sizePx)}else{bestFont=new gs.html5.text.Font(family,sizePx)}this.fontMap[key]=bestFont;this.familyMap[family]=bestFont.family;return bestFont}};gs.html5.Text={normalizeString:function(s){s=s.replace(/\\32/g," ");s=s.replace(/\\t/g,"\t");s=s.replace(/((\r|\\r)(\n|\\n))|((\n|\\n)(\r|\\r))/g,"\n");s=s.replace(/\\n|\r|\\r|\u2028|\u2029/g,"\n");return s}};gs.webgl={contextNames:["webgl","experimental-webgl"],contextOptions:{alpha:false,depth:false,stencil:false,antialias:false},supportedContextName:null,isSupported:function(){var testCanvas=gs.dom.createCanvas();var gl=gs.webgl.getContext(testCanvas);return gl!==null},getContext:function(canvasElement){if(gs.webgl.supportedContextName){return canvasElement.getContext(gs.webgl.supportedContextName)}var contextNames=gs.webgl.contextNames;for(var i=0;i&lt;contextNames.length;++i){try{var gl=canvasElement.getContext(contextNames[i],gs.webgl.contextOptions);if(gl){gs.webgl.supportedContextName=contextNames[i];return gl}}catch(exception){}}return null},createTextureFromImage:function(gl,image){var previousTexture=gl.getParameter(gl.ACTIVE_TEXTURE);gl.activeTexture(previousTexture+1);var texture=gl.createTexture();try{gl.bindTexture(gl.TEXTURE_2D,texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true);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);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);texture.previousWrapS=gl.CLAMP_TO_EDGE;texture.previousWrapT=gl.CLAMP_TO_EDGE}catch(exception){gs.Log.error(exception)}gl.activeTexture(previousTexture);var glError=gl.getError();if(glError){gs.Log.error("createTextureFromImage: glError",glError);gl.deleteTexture(texture);return null}return texture},createTextureFromImageSize:function(gl,imageElement,width,height){var buffer=new gs.html5.GraphicsBuffer(width,height);buffer.context.drawImage(imageElement,0,0,imageElement.width,imageElement.height,0,0,width,height);return this.createTextureFromImage(gl,buffer.canvas)}};gs.platform={};gs.platform.core={};(function(){var core=gs.platform.core;gs.platform=Object.create(core);gs.platform.core=core})();gs.platform.core.AccelerometerService=function(){this.game=null;this.gravity=9.80665;this.inverseGravity=1/this.gravity;this.orientation="portrait";this.rotateAxes=false;this.flipAxes=false;this.negateGravityXY=false;this.negateGravityZ=false;this.setNegateGravityZ(true)};gs.platform.core.AccelerometerService.onDeviceMotion=function(event){gs.platform.AccelerometerService.instance().onDeviceMotion(event)};gs.platform.core.AccelerometerService.prototype={init:function(game){this.game=game;window.addEventListener("devicemotion",gs.platform.core.AccelerometerService.onDeviceMotion)},setOrientation:function(orientation){this.orientation=orientation},setRotateAxes:function(rotateAxes){this.rotateAxes=rotateAxes},setFlipAxes:function(flipAxes){this.flipAxes=flipAxes},setNegateGravityXY:function(negateGravityXY){this.negateGravityXY=negateGravityXY},setNegateGravityZ:function(negateGravityZ){this.negateGravityZ=negateGravityZ},onDeviceMotion:function(event){this.setAccelerationV(event["accelerationIncludingGravity"])},setAccelerationV:function(a){var accelerometer=this.game.devices.accelerometer;var x=a.x*this.inverseGravity;var y=a.y*this.inverseGravity;var z=a.z*this.inverseGravity;if(this.rotateAxes){var temp=x;x=y;y=-temp}if(this.flipAxes){x=-x;y=-y}if(this.negateGravityXY){x=-x;y=-y}if(this.negateGravityZ){z=-z}accelerometer.x.setValue(x);accelerometer.y.setValue(y);accelerometer.z.setValue(z)}};gs.singleton(gs.platform.core.AccelerometerService);gs.platform.core.AnalyticsService=function(){var externalDelegate=gs.api.ExternalDelegate.instance();this.sessionManager=new gs.analytics.SessionManager(externalDelegate);this.currentSession=null};gs.platform.core.AnalyticsService.prototype={beginSession:function(){this.currentSession=this.sessionManager.openNewSession()},endSession:function(){this.currentSession.close()},trackSceneChange:function(previewSceneName,newSceneName){this.beginSceneChange(previewSceneName);this.endSceneChange(newSceneName)},beginSceneChange:function(previousSceneName){this.currentSession.beginSceneChange(previousSceneName)},endSceneChange:function(newSceneName){this.currentSession.endSceneChange(newSceneName)}};gs.singleton(gs.platform.core.AnalyticsService);gs.platform.core.BrowserService=function(){};gs.platform.core.BrowserService.prototype={isInternalBrowserAllowed:function(url){return true},platformHasBlocker:function(){return!/crosswalk/.test(navigator.userAgent.toLowerCase())},openBrowser:function(url,internal){if(gs.globalOptions.useBehaviorStubs){gs.EngineContext.current.delegate.onBrowserOpen(url,internal);return}var didInternal=false;if(internal){didInternal=this.openInternalBrowser(url)}if(!didInternal){this.openExternalBrowser(url)}},openInternalBrowser:function(url){try{gs.EngineContext.current.getRenderContext().viewport.showOverlayLayer();this.rootElement=gs.dom.getElement("gse-browser");this.browserFrame=gs.dom.getElement("gse-browser-frame");this.closeButton=gs.dom.getElement("gse-browser-close");var that=this;this.onCloseButtonClicked=function(){that.closeInternalBrowser()};this.closeButton.addEventListener("click",this.onCloseButtonClicked,false);gs.EngineContext.current.pause();this.browserFrame.src=url;gs.dom.setElementVisible(this.rootElement,true);return true}catch(exception){gs.Log.warn(exception);gs.Log.warn("Internal Browser dialog not available");return false}},closeInternalBrowser:function(){this.closeButton.removeEventListener("click",this.onCloseButtonClicked,false);gs.dom.setElementVisible(this.rootElement,false);gs.EngineContext.current.getRenderContext().viewport.hideOverlayLayer();gs.Game.current.clearTouchState();gs.EngineContext.current.unpause()},openExternalBrowser:function(url){function onPointerEvent(){window.removeEventListener("mouseup",onPointerEvent,false);window.removeEventListener("mousedown",onPointerEvent,false);window.removeEventListener("touchstart",onPointerEvent,false);window.removeEventListener("touchend",onPointerEvent,false);window.open(url)}if(this.platformHasBlocker()){window.addEventListener("mouseup",onPointerEvent,false);window.addEventListener("mousedown",onPointerEvent,false);window.addEventListener("touchstart",onPointerEvent,false);window.addEventListener("touchend",onPointerEvent,false)}else{window.open(url)}}};gs.singleton(gs.platform.core.BrowserService);gs.platform.core.DeviceAnalyticsService=function(){this.sessionManager=new gs.analytics.SessionManager;this.sessionManager.enableUploading();this.currentSession=null};gs.platform.core.DeviceAnalyticsService.prototype={beginSession:function(){this.sessionManager.flush();this.currentSession=this.sessionManager.openNewSession()},endSession:function(){this.currentSession.close()},trackSceneChange:function(previewSceneName,newSceneName){this.beginSceneChange(previewSceneName);this.endSceneChange(newSceneName)},beginSceneChange:function(previousSceneName){this.currentSession.beginSceneChange(previousSceneName)},endSceneChange:function(newSceneName){this.currentSession.endSceneChange(newSceneName)}};gs.singleton(gs.platform.core.DeviceAnalyticsService);gs.platform.core.HashService=function(){};gs.platform.core.HashService.prototype={init:function(gameData){},host:function(url){},hash:function(str){},id:function(hash,id){}};gs.singleton(gs.platform.core.HashService);gs.platform.core.JoystickService=function(){this.game=null;this.playerMap={};this.playerKeyMap={}};gs.platform.core.JoystickService.onDeviceConnect=function(evt){gs.platform.JoystickService.instance().onDeviceConnect(evt)};gs.platform.core.JoystickService.onDeviceDisconnect=function(evt){gs.platform.JoystickService.instance().onDeviceDisconnect(evt)};gs.platform.core.JoystickService.prototype={getGamepads:function(){var gamepads=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads:[];if(gamepads&amp;&amp;Array.isArray(gamepads)){return gamepads.filter(function(g){return g})}return[]},onDeviceConnect:function(e){var playerKey=null;var players=this.game.devices.players;if(this.game.attributes.playerType.getValue()==1){playerKey="player1"}else{playerKey=Object.keys(players).sort().find(function(playerKey){return!players[playerKey].joystick.connected.getValue()})}var player=players[playerKey];var joystick=player.joystick;joystick.connected.setValue(true);joystick.name.setValue(e.gamepad.id);joystick.productID.setValue(e.gamepad.index);this.playerMap[e.gamepad.index]=player;this.playerKeyMap[e.gamepad.index]=playerKey;console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.",e.gamepad.index,e.gamepad.id,e.gamepad.buttons.length,e.gamepad.axes.length)},onDeviceDisconnect:function(e){var player=this.playerMap[e.gamepad.index];var pluggedInCount=this.getGamepads().length;if(player){if(this.game.attributes.playerType.getValue()!=1||pluggedInCount==0){var joystick=player.joystick;joystick.connected.setValue(false);joystick.name.setValue("unknown");joystick.vendorID.setValue(-1);joystick.productID.setValue(-1);Object.keys(gs.Game.DEFAULT_JOYSTICK_INPUT_VALUES).forEach(function(btn){player[btn].setValue(gs.Game.DEFAULT_JOYSTICK_INPUT_VALUES[btn])})}}delete this.playerMap[e.gamepad.index];delete this.playerKeyMap[e.gamepad.index];console.log("Gamepad disconnected from index %d: %s",e.gamepad.index,e.gamepad.id)},init:function(game){this.game=game;window.addEventListener("gamepadconnected",gs.platform.core.JoystickService.onDeviceConnect);window.addEventListener("gamepaddisconnected",gs.platform.core.JoystickService.onDeviceDisconnect)},updateMappedKey:function(playerKey,button,pressed){var game=this.game;var keyValue=game.attributes[playerKey+" Keymap"][button].getValue();if(keyValue){if(pressed){game.eventCenter.postEvent("keyDown",null,keyValue)}else{game.eventCenter.postEvent("keyUp",null,keyValue)}}},update:function(){var activePlayers=Object.keys(this.playerMap);var gamepads=this.getGamepads();if(gamepads&amp;&amp;activePlayers.length&gt;0){for(var i=0;i&lt;activePlayers.length;i++){var gamepadIndex=activePlayers[i];var gamepad=gamepads[gamepadIndex];var player=this.playerMap[gamepadIndex];var playerKey=this.playerKeyMap[gamepadIndex];if(gamepad&amp;&amp;gamepad.axes){var axisCount=gamepad.axes.length;if(axisCount&gt;0){player.leftStickX.setValue(gamepad.axes[0])}if(axisCount&gt;1){player.leftStickY.setValue(gamepad.axes[1])}if(axisCount&gt;2){player.rightStickX.setValue(gamepad.axes[2])}if(axisCount&gt;3){player.rightStickY.setValue(gamepad.axes[3])}}if(gamepad&amp;&amp;gamepad.buttons){var _this=this;var buttonCount=gamepad.buttons.length;["buttonA","buttonB","buttonX","buttonY","leftShoulder1","rightShoulder1","leftShoulder2","rightShoulder2","select","start","leftStickClick","rightStickClick","dpadUp","dpadDown","dpadLeft","dpadRight"].forEach(function(btn,idx){if(buttonCount&gt;idx){var pressed=gamepad.buttons[idx].pressed;if(player[btn].getValue()!=pressed){player[btn].setValue(pressed);_this.updateMappedKey(playerKey,btn,pressed)}}})}}}}};gs.singleton(gs.platform.core.JoystickService);gs.platform.core.PurchaseService=function(){};gs.platform.core.PurchaseService.prototype={purchaseItem:function(itemId){gs.Log.debug("PurchaseService.purchaseItem("+itemId+")");gs.Game.current.eventCenter.postEvent("InAppFailure")},restoreItems:function(){gs.Log.debug("PurchaseService.restoreItems()");var emptyList=gs.array.provide();gs.Game.current.eventCenter.postEvent("InAppRestore",null,emptyList)}};gs.singleton(gs.platform.core.PurchaseService);gs.platform.core.KeyboardCaptureService=function(){};gs.platform.core.KeyboardCaptureService.prototype={activateTextPrompt:function(behavior,initText){try{var txtEntry=this.hiddenTextElement=document.createElement("input");txtEntry.type="text";txtEntry.tabIndex=0;txtEntry.style.width="1px";txtEntry.style.height="1px";txtEntry.style.position="fixed";txtEntry.style.top=0;txtEntry.style.left=0;txtEntry.value=initText;function refocusHandler(evt){console.log("refocusing");txtEntry.focus();return true}txtEntry.addEventListener("blur",refocusHandler);function keyupHandler(evt){console.log("Handling change...");behavior.keyboardInputEntered(txtEntry.value);return true}txtEntry.addEventListener("keyup",keyupHandler);txtEntry.addEventListener("keydown",function(evt){console.log(evt);if(evt.code==="Enter"){evt.preventDefault();console.log("Stoping behavior...");txtEntry.removeEventListener("blur",refocusHandler);txtEntry.removeEventListener("keyup",keyupHandler);behavior.keyboardInputEntered(txtEntry.value);document.body.removeChild(txtEntry);txtEntry=null;behavior.keyboardInputCancelled()}});console.log("Adding textEntry");document.body.appendChild(txtEntry);txtEntry.focus()}catch(e){behavior.stop(0)}}};gs.singleton(gs.platform.core.KeyboardCaptureService);gs.platform.core.TextService=function(){};gs.platform.core.TextService.prototype={openTextPrompt:function(prompt,initialText,callback){try{gs.EngineContext.current.getRenderContext().viewport.showOverlayLayer();this.rootElement=gs.dom.getElement("gse-text");this.textPrompt=gs.dom.getElement("gse-text-prompt");this.textInput=gs.dom.getElement("gse-text-input");this.doneButton=gs.dom.getElement("gse-text-done");this.cancelButton=gs.dom.getElement("gse-text-cancel");var that=this;this.onDoneButtonClicked=function(){that.closeTextPrompt();callback&amp;&amp;callback.call(null,that.textInput.value)};this.onCancelButtonClicked=function(){that.closeTextPrompt();callback&amp;&amp;callback.call(null,null)};this.doneButton.addEventListener("click",this.onDoneButtonClicked,false);this.cancelButton.addEventListener("click",this.onCancelButtonClicked,false);this.textPrompt.textContent=prompt;this.textInput.value=initialText;gs.dom.setElementVisible(this.rootElement,true);this.textInput.focus()}catch(exception){gs.Log.warn(exception);gs.Log.warn("Text Input dialog not available");callback&amp;&amp;callback.call(null,initialText)}},closeTextPrompt:function(){this.doneButton.removeEventListener("click",this.onDoneButtonClicked,false);this.cancelButton.removeEventListener("click",this.onCancelButtonClicked,false);gs.dom.setElementVisible(this.rootElement,false);gs.EngineContext.current.getRenderContext().viewport.hideOverlayLayer()}};gs.singleton(gs.platform.core.TextService);gs.globalOptions.supportsVibrate="vibrate"in navigator||"mozVibrate"in navigator;gs.GameLoop=function(targetRate){this.isRunning=false;this.isSpinning=false;this.callback=null;this.element=null;this.requestID=null;this.intervalID=null;this.intervalMS=targetRate!==0?Math.floor(1e3/targetRate):16;this.useRequestAnimationFrame=targetRate!==0?false:typeof window.requestAnimationFrame==="function";gs.GameLoop.instance=this};gs.GameLoop.instance=null;gs.GameLoop.tick=function(){gs.GameLoop.instance.tick()};gs.GameLoop.prototype={start:function(){this.isRunning=true;if(!this.isSpinning){if(this.useRequestAnimationFrame){this.requestID=window.requestAnimationFrame(gs.GameLoop.tick,this.element)}else{this.intervalID=window.setInterval(gs.GameLoop.tick,this.intervalMS)}this.isSpinning=true}},stop:function(){this.isRunning=false;this.isSpinning=false;if(this.requestID){window.cancelAnimationFrame(this.requestID);this.requestID=null}if(this.intervalID){window.clearInterval(this.intervalID)}},tick:function(){this.requestID=null;if(this.isSpinning&amp;&amp;this.useRequestAnimationFrame){this.requestID=window.requestAnimationFrame(gs.GameLoop.tick,this.element)}if(this.isRunning){try{this.callback&amp;&amp;this.callback.call(null)}catch(exception){gs.Log.error(exception);if(exception&amp;&amp;exception.stack){gs.Log.debug(exception.stack)}}}},setCallback:function(callback){this.callback=callback},setDOMElement:function(element){this.element=element}};gs.JXON={_type:"@",_text:"$",_children:"#",detect:function(jxonObject){if(jxonObject&amp;&amp;jxonObject["@"]){gs.JXON._type="@";gs.JXON._text="$";gs.JXON._children="#"}else{gs.JXON._type="_type";gs.JXON._text="_text";gs.JXON._children="_children"}},tag:function(jxonObject){return jxonObject[gs.JXON._type]},content:function(jxonObject){return jxonObject[gs.JXON._text]},id:function(jxonObject){return jxonObject["id"]},children:function(jxonObject){return jxonObject[gs.JXON._children]},childrenWithTag:function(jxonObject,tag){var result=[];var children=gs.JXON.children(jxonObject);if(children){children.forEach(function(child){if(gs.JXON.tag(child)===tag){result.push(child)}})}return result},childWithTag:function(jxonObject,tag){var children=gs.JXON.childrenWithTag(jxonObject,tag);return children.length&gt;0?children[0]:undefined},childWithID:function(jxonObject,id){var result=undefined;var children=gs.JXON.children(jxonObject);if(children){children.forEach(function(child){if(gs.JXON.id(child)===id){result=child}})}return result}};gs.PGF={attributes:function(nodeJXON){var attributesNode=gs.JXON.childWithTag(nodeJXON,"attributes");if(!attributesNode){return undefined}return gs.JXON.children(attributesNode)},attributesWithType:function(nodeJXON,type){var results=[];var attributes=gs.PGF.attributes(nodeJXON);if(attributes){attributes.forEach(function(attribute){if(gs.JXON.tag(attribute)===type){results.push(attribute)}})}return results},attributeWithID:function(nodeJXON,id){var result=null;var attributes=gs.PGF.attributes(nodeJXON);if(attributes){attributes.forEach(function(attribute){if(gs.JXON.id(attribute)===id){result=attribute}})}return result}};gs.XML={parse:function(xmlString){gs.JXON.detect(xmlString);var root=gs.XML.XMLStringToJXON(xmlString);return gs.Prototypical.convertJXONLite(root)},XMLStringToJXON:function(xmlString){var platformXML=gs.XML.XMLStringToPlatformXML(xmlString);return gs.XML.platformXMLToJXON(platformXML)},XMLStringToPlatformXML:function(xmlString){var parser=new DOMParser;var contentType="text/xml";var xmlDocument=parser.parseFromString(xmlString,contentType);var xmlRoot=xmlDocument.childNodes.item(0);return xmlRoot},platformXMLToJXON:function(xmlObject){var jxonObject={},i,key,child;jxonObject[gs.JXON._type]=xmlObject.nodeName;Array.prototype.forEach.call(xmlObject.attributes,function(attribute){var key=attribute.nodeName;jxonObject[key]=attribute.nodeValue},gs.XML);var childNodeCount=xmlObject.childNodes.length;if(childNodeCount===0){jxonObject[gs.JXON._text]="";jxonObject[gs.JXON._children]=[]}else{if(childNodeCount===1){var firstChild=xmlObject.firstChild;if(firstChild.nodeType===Node.TEXT_NODE){jxonObject[gs.JXON._text]=String(firstChild.nodeValue);return jxonObject}}jxonObject._children=[];var elementCount=0;for(i=0;i&lt;childNodeCount;i++){child=gs.XML.getChildNode(xmlObject,i);if(child.nodeType===Node.ELEMENT_NODE){elementCount++;key=child.nodeName;var jxonChild=gs.XML.platformXMLToJXON(child);jxonObject[gs.JXON._children].push(jxonChild)}}if(elementCount===0){delete jxonObject[gs.JXON._children]}}return jxonObject},getChildNode:function(xmlNode,index){return NodeList.prototype.item.call(xmlNode.childNodes,index)}};gs.Prototypical={convertJXONLite:function(node,parent,context){var tag=node["_type"];var nodes=node["_children"];var hasNodes=nodes&amp;&amp;nodes.length&gt;0;switch(tag){case"scenes":case"actors":case"prototypes":case"layers":case"images":case"sounds":case"behaviors":case"elseBehaviors":case"conditions":case"expression":case"tags":case"rows":case"columns":case"array":return gs.Prototypical.convertJXONLiteList(node,parent);case"aspects":case"graphics":case"motion":case"physics":return gs.Prototypical.convertJXONLiteMap(node,parent);case"info":case"game":case"scene":case"assets":return gs.Prototypical.convertJXONLiteEntity(node,parent,true);case"layer":case"actor":case"behavior":case"condition":case"file":case"reference":case"row":case"column":case"pair":return gs.Prototypical.convertJXONLiteEntity(node,parent,false);case"image":case"sound":case"music":if(hasNodes||context==="assets"||context=="images"||context==="sounds"){return gs.Prototypical.convertJXONLiteAsset(node,parent)}else{return gs.Prototypical.convertJXONLiteOther(node,parent)}case"string":return gs.Prototypical.convertJXONLiteString(node,parent);case"plugins":return node;case"attributes":if(node["id"]==="autorotate"){return gs.Prototypical.convertJXONLiteOther(node,parent)}else{return gs.Prototypical.convertJXONLiteMap(node,parent)}case"table":if(hasNodes){return gs.Prototypical.convertJXONLiteEntity(node,parent)}else{return gs.Prototypical.convertJXONLiteOther(node,parent)}case"predicate":case"subjectPredicate":return gs.Prototypical.convertJXONLitePredicate(node,parent);case"polygon":return gs.Prototypical.convertJXONLitePolygon(node,parent);default:return gs.Prototypical.convertJXONLiteOther(node,parent)}},convertJXONLitePolygon:function(node,parent){var tag=node["_type"];var content=node["_text"];if(!("polygons"in parent)){parent["polygons"]=[]}var stringPoints=content.split(",");var shapePoints=[];var point=[];for(var j=0;j&lt;stringPoints.length;j++){point[j%2]=new Number(stringPoints[j]);if(j%2==1){shapePoints.push(point);point=[]}}parent["polygons"].push(shapePoints)},convertJXONLiteList:function(node,parent){var tag=node["_type"];var id=node["id"];var nodes=node["_children"];if(nodes){if(tag==="array"){parent[id]=nodes}else{parent[tag]=nodes}for(var i=0;i&lt;nodes.length;i++){nodes[i]=gs.Prototypical.convertJXONLite(nodes[i],null,tag)}}else{parent[tag]=[]}return nodes},convertJXONLiteMap:function(node,parent){var tag=node["_type"];var nodes=node["_children"];var map={};parent[tag]=map;if(nodes&amp;&amp;nodes.length&gt;0){for(var i=0;i&lt;nodes.length;i++){gs.Prototypical.convertJXONLite(nodes[i],map,tag)}}return map},convertJXONLiteString:function(node,parent){return node["_text"]},convertJXONLiteEntity:function(node,parent,includeTag){var tag=node["_type"];delete node["_type"];if(includeTag){node["@"]=tag}if(tag==="column"){var cells=node["_text"];if(typeof cells==="string"){cells=gs.Prototypical.parseCSV(cells)}node["$"]=cells}delete node["_text"];var nodes=node["_children"];delete node["_children"];if(nodes){for(var i=0;i&lt;nodes.length;i++){gs.Prototypical.convertJXONLite(nodes[i],node,tag)}}return node},convertJXONLiteAsset:function(node,parent){var tag=node["_type"];var nodes=node["_children"];delete node["_type"];delete node["_children"];delete node["_text"];if(nodes){node["files"]=nodes;for(var i=0;i&lt;nodes.length;i++){nodes[i]=gs.Prototypical.convertJXONLite(nodes[i],node,tag)}}else{node["files"]=[]}return node},convertJXONLitePredicate:function(node,parent){var tag=node["_type"];var nodes=node["_children"];delete node["_type"];delete node["_children"];delete node["_text"];parent[tag]=node;if(nodes){for(var i=0;i&lt;nodes.length;i++){gs.Prototypical.convertJXONLite(nodes[i],node,tag)}}return node},convertJXONLiteOther:function(node,parent){var tag=node["_type"];var id=node["id"];var nodes=node["_children"];var hasNodes=nodes&amp;&amp;nodes.length&gt;0;var content=node["_text"];var hasContent=content!==undefined;var key=id||tag;delete node["_type"];delete node["id"];delete node["_children"];delete node["_text"];if(tag==="tablecolumnassignment"){for(var i=0;i&lt;nodes.length;i++){gs.Prototypical.convertJXONLite(nodes[i],node,tag)}return node}if(hasNodes){parent[key]=node;for(var i=0;i&lt;nodes.length;i++){gs.Prototypical.convertJXONLite(nodes[i],node,tag)}}else{var propertyCount=Object.keys(node).length;if(propertyCount===0){parent[key]=gs.Prototypical.formatContent(content)}else{if(id){parent[id]=node}node["@"]=tag;if(hasContent){node["$"]=gs.Prototypical.formatContent(content)}}}},formatContent:function(content){if(typeof content==="number"){if(isNaN(content)){return"nan"}if(content===Number.POSITIVE_INFINITY){return"inf"}if(content===Number.NEGATIVE_INFINITY){return"-inf"}}return content},parseCSV:function(csv){var newline=/\r\n|\r|\n/g;var separator=",";var commaLiteral="\\u002C";var commaPattern=/\\u002C/g;var a=csv.split(newline);for(var i in a){a[i]=a[i].replace(/\\,/g,commaLiteral);for(var f=a[i].split(separator),x=f.length-1,tl;x&gt;=0;x--){if(f[x].replace(/"\s+$/,'"').charAt(f[x].length-1)=='"'){if((tl=f[x].replace(/^\s+"/,'"')).length&gt;1&amp;&amp;tl.charAt(0)=='"'){f[x]=f[x].replace(/^\s*"|"\s*$/g,"").replace(/""/g,'"')}else if(x){f.splice(x-1,2,[f[x-1],f[x]].join(separator))}else f=f.shift().split(separator).concat(f)}else{f[x]=f[x].replace(/""/g,'"')}}for(var j=0;j&lt;f.length;j++){f[j]=f[j].replace(commaPattern,",")}a[i]=f}return a[0]}};gs.api.ExternalDelegate=function(){this.delegate=null};gs.api.ExternalDelegate.instance=function(){return gs.util.lazySingleton(this)};gs.api.ExternalDelegate.prototype={setDelegate:function(delegate){this.delegate=delegate},readExternalValueSync:function(key){if(!this.delegate){return null}return this.delegate["readExternalValueSync"](key)},registerOptions:function(tableKeypath,attributeKeypath){if(!this.delegate){return}this.delegate["registerOptions"](tableKeypath,attributeKeypath)}};gs.api.Delegate=function(){this.delegates=[]};gs.api.Delegate.prototype={appendDelegate:function(externalDelegate){this.delegates.push(externalDelegate)},onGameDimensionsKnown:function(width,height){return this.invoke("onGameDimensionsKnown",width,height)},onGameReady:function(){return this.invoke("onGameReady")},onSceneAboutToChange:function(sceneKey,sceneName,adType){return this.invoke("onSceneAboutToChange",sceneKey,sceneName,adType)},onCurrentSceneChanged:function(sceneKey,sceneName){return this.invoke("onCurrentSceneChanged",sceneKey,sceneName)},onLoadingBegin:function(){return this.invoke("onLoadingBegin")},onLoadingEnd:function(){return this.invoke("onLoadingEnd")},onTerminate:function(){return this.invoke("onTerminate")},onFrameRendered:function(){return this.invoke("onFrameRendered")},onProfilerFrame:function(frame,entities,gameLoad,sceneLoad){return this.invoke("onProfilerFrame",frame,entities,gameLoad,sceneLoad)},onExternalReadSync:function(key){return this.invoke("onExternalReadSync",key)},onBrowserOpen:function(url){return this.invoke("onBrowserOpen",url)},onShowBannerShow:function(position){return this.invoke("onShowBannerShow",position)},onShowBannerHide:function(){return this.invoke("onShowBannerHide")},onShowMoreGames:function(){return this.invoke("onShowMoreGames")},onLaunchService:function(pageIndex){return this.invoke("onLaunchService",pageIndex)},onGameCenterLogin:function(){return this.invoke("onGameCenterLogin")},onGameCenterPostScore:function(score,leaderboard){return this.invoke("onGameCenterPostScore",score,leaderboard)},onSaveTable:function(key,table,defaultFunction){if(this.invoke("onSaveTable",key,table)===undefined){defaultFunction(key,table)}},onSaveAttribute:function(key,value,defaultFunction){if(this.invoke("onSaveAttribute",key,value)===undefined){defaultFunction(key,value)}},onLoadAttribute:function(key,defaultFunction){var value=this.invoke("onLoadAttribute",key);if(value===undefined){return defaultFunction(key)}return value},onGameCenterShowLeaderboard:function(leaderboard){return this.invoke("onGameCenterShowLeaderboard",leaderboard)},onGameCenterShowAchievements:function(){return this.invoke("onGameCenterShowAchievements")},onGameCenterResetAchievements:function(){return this.invoke("onGameCenterResetAchievements")},onGameCenterUpdateAchievement:function(identifier,percentageComplete){return this.invoke("onGameCenterUpdateAchievement",identifier,percentageComplete)},onIAPBuyItem:function(itemInfo){return this.invoke("onIAPBuyItem",itemInfo)},onIAPRestoreItems:function(){return this.invoke("onIAPRestoreItems")},onIAPConsumeItem:function(itemInfo){return this.invoke("onIAPConsumeItem",itemInfo)},onIAPRequestPurchaseData:function(){return this.invoke("onIAPRequestPurchaseData")},onTweetSheet:function(message,img,editable){return this.invoke("onTweetSheet",message,img,editable)},onLogDebuggingStatement:function(text,entity){return this.invoke("onLogDebuggingStatement",text,entity)},onLogDebug:function(message){return this.invoke("onLogDebug",message)},onLogInfo:function(message){return this.invoke("onLogInfo",message)},onLogWarn:function(message){return this.invoke("onLogWarn",message)},onLogStrict:function(message){return this.invoke("onLogStrict",message)},onLogError:function(message){return this.invoke("onLogError",message)},onLogFatal:function(message){return this.invoke("onLogFatal",message)},onLogAll:function(message){return this.invoke("onLogAll",message)},onSpecial:function(data){return this.invoke("onSpecial",data)},invoke:function(method){var i=0,delegates=this.delegates,end=this.delegates.length,delegate=null;var lastReturnValue=undefined;var returnValue=undefined;var argumentCount=arguments.length-1;switch(argumentCount){case 0:for(;i&lt;end;++i){delegate=delegates[i];if(typeof delegate[method]==="function"){try{returnValue=delegate[method]()}catch(exception){}if(returnValue!==undefined){lastReturnValue=returnValue}}}break;case 1:var singleArgument=arguments[1];for(;i&lt;end;++i){delegate=delegates[i];if(typeof delegate[method]==="function"){try{returnValue=delegate[method](singleArgument)}catch(exception){}if(returnValue!==undefined){lastReturnValue=returnValue}}}break;case 2:var firstArgument=arguments[1];var secondArgument=arguments[2];for(;i&lt;end;++i){delegate=delegates[i];if(typeof delegate[method]==="function"){try{returnValue=delegate[method](firstArgument,secondArgument)}catch(exception){}if(returnValue!==undefined){lastReturnValue=returnValue}}}break;default:var manyArguments=[];for(;i&lt;argumentCount;i++){manyArguments.push(arguments[i+1])}for(i=0;i&lt;end;++i){delegate=delegates[i];if(typeof delegate[method]==="function"){try{returnValue=delegate[method].apply(delegate,manyArguments)}catch(exception){}if(returnValue!==undefined){lastReturnValue=returnValue}}}break}return lastReturnValue}};gs.LegacyDelegate={getListeners:function(area,action){if(!this.actionListeners){this.actionListeners={}}if(!this.actionListeners[area]){this.actionListeners[area]={}}if(!this.actionListeners[area][action]){this.actionListeners[area][action]=[]}return this.actionListeners[area][action]},addActionListener:function(area,action,listener){gs.Log.strict("registered legacy action listener:",area,action);this.getListeners(area,action).push(listener)},dispatchAction:function(area,action,args){var listeners=this.getListeners(area,action);for(var i=0,end=listeners.length;i&lt;end;i++){try{listeners[i].call(null,args)}catch(exception){gs.Log.error(exception)}}},onGameDimensionsKnown:function(width,height){this.dispatchAction("screen","size",{width:width,height:height})},onCurrentSceneChanged:function(sceneKey,sceneName){this.dispatchAction("scene","start",{id:sceneKey,name:sceneName})},onProfilerFrame:function(frame,entities,game,scene){this.dispatchAction("profiler","frame",frame);this.dispatchAction("profiler","entities",entities);this.dispatchAction("profiler","game",game);this.dispatchAction("profiler","scene",scene);var averageFrameMS=frame.frame||16;var fps=1e3/averageFrameMS;this.dispatchAction("debug","updateFPS",fps)},onBannerShow:function(position){this.dispatchAction("showBanner","show",{position:position})},onBannerHide:function(){this.dispatchAction("showBanner","hide",null)},onLaunchService:function(pageIndex){this.dispatchAction("launchService","launchService",{page:pageIndex})},onGameCenterLogin:function(){this.dispatchAction("GameCenter","login",null)},onGameCenterPostScore:function(){this.dispatchAction("GameCenter","postScore",null)},onGameCenterShowLeaderboard:function(){this.dispatchAction("GameCenter","showLeaderboard",null)},onGameCenterShowAchievements:function(){this.dispatchAction("GameCenter","showAchievements",null)},onGameCenterResetAchievements:function(){this.dispatchAction("GameCenter","resetAchievements",null)},onGameCenterUpdateAchievement:function(){this.dispatchAction("GameCenter","updateAchievement",null)},onTweetSheet:function(message){this.dispatchAction("Twitter","tweetSheet",null)}};gs.LogVisualizer=function(){this.root=null;this.createDOM()};gs.LogVisualizer.prototype={createDOM:function(){this.root=gs.dom.create("DIV");this.root.className="gse-debug gse-log"},append:function(line,color){var p=gs.dom.create("P");p.textContent=line;if(color){p.style.color=color}this.root.appendChild(p)},onLogAll:function(message){this.append(message)}};gs.PerformanceCounter=function(){this.count=0};gs.PerformanceCounter.prototype={getReading:function(){return this.count},reset:function(){this.count=0},set:function(value){this.count=value},add:function(delta){this.count+=delta},increment:function(){this.count++}};gs.PerformanceTimer=function(count,initialValue){if(initialValue===undefined){initialValue=0}this.timeProvider=window.performance&amp;&amp;window.performance.now?window.performance:Date;this.count=count;this.sum=initialValue*this.count;this.average=initialValue;this.index=0;this.enterTime=this.getTime();this.exitTime=this.getTime();this.buffer=[];for(var i=0;i&lt;this.count;i++){this.buffer[i]=initialValue}};gs.PerformanceTimer.prototype={getReading:function(){this.average=this.sum/this.count;return this.average},getTime:function(){return this.timeProvider.now()},enter:function(){this.enterTime=this.getTime()},exit:function(){this.exitTime=this.getTime();var delta=this.exitTime-this.enterTime;this.sum-=this.buffer[this.index];this.sum+=delta;this.buffer[this.index]=delta;this.index=(this.index+1)%this.count},tick:function(){this.exit();this.enter()}};gs.FrameProfiler=function(){var smoothingFactor=60;this.frame=new gs.PerformanceTimer(smoothingFactor,1e3/60);this.engine=new gs.PerformanceTimer(smoothingFactor,1e3/100);this.simulate=new gs.PerformanceTimer(smoothingFactor,1);this.physics=new gs.PerformanceTimer(smoothingFactor,1);this.render=new gs.PerformanceTimer(smoothingFactor,1);this.profile=new gs.PerformanceTimer(smoothingFactor,1);this.input=new gs.PerformanceTimer(smoothingFactor,1);this.reading={frame:0,engine:0,simulate:0,physics:0,render:0,profile:0,input:0};this.getReading()};gs.FrameProfiler.prototype={getReading:function(){this.reading["frame"]=this.frame.getReading();this.reading["engine"]=this.engine.getReading();this.reading["simulate"]=this.simulate.getReading();this.reading["physics"]=this.physics.getReading();this.reading["render"]=this.render.getReading();this.reading["profile"]=this.profile.getReading();this.reading["input"]=this.input.getReading();return this.reading}};gs.EntityCounter=function(){this.layers=new gs.PerformanceCounter;this.actors=new gs.PerformanceCounter;this.sprites=new gs.PerformanceCounter;this.particles=new gs.PerformanceCounter;this.textures=new gs.PerformanceCounter;this.awake=new gs.PerformanceCounter;this.contacts=new gs.PerformanceCounter;this.reading={layers:0,actors:0,sprites:0,particles:0,textures:0,awake:0,contacts:0};this.getReading()};gs.EntityCounter.prototype={reset:function(){this.layers.reset();this.actors.reset();this.sprites.reset();this.particles.reset();this.textures.reset();this.awake.reset();this.contacts.reset()},getReading:function(){this.reading["layers"]=this.layers.getReading();this.reading["actors"]=this.actors.getReading();this.reading["sprites"]=this.sprites.getReading();this.reading["particles"]=this.particles.getReading();this.reading["textures"]=this.textures.getReading();this.reading["awake"]=this.awake.getReading();this.reading["contacts"]=this.contacts.getReading();return this.reading}};gs.LoadProfiler=function(){this.time=new gs.PerformanceTimer(1);this.load=new gs.PerformanceTimer(1);this.parse=new gs.PerformanceTimer(1);this.assets=new gs.PerformanceTimer(1);this.images=new gs.PerformanceCounter;this.sounds=new gs.PerformanceCounter;this.reading={time:0,load:0,parse:0,assets:0,images:0,sounds:0};this.getReading()};gs.LoadProfiler.prototype={reset:function(){this.images.reset();this.sounds.reset()},getReading:function(){this.reading["time"]=this.time.getReading();this.reading["load"]=this.load.getReading();this.reading["parse"]=this.parse.getReading();this.reading["assets"]=this.assets.getReading();this.reading["images"]=this.images.getReading();this.reading["sounds"]=this.sounds.getReading();return this.reading}};gs.FrameRateVisualizer=function(){this.root=null;this.span=null;this.trueDeltaMS=1;this.deltaMS=1;this.hitchMS=0;this.hitchCounter=0;this.didDraw=false;this.createDOM()};gs.FrameRateVisualizer.prototype={createDOM:function(){this.root=gs.dom.create("DIV");this.root.className="gse-debug gse-profiler";this.span=gs.dom.create("SPAN");this.root.appendChild(this.span)},onProfilerFrame:function(frame,entities,gameLoad,sceneLoad){var s="";var average=frame.frame;if(this.hitchCounter&lt;=0&amp;&amp;average&lt;18){if(this.didDraw){this.span.textContent="";this.didDraw=false}this.hitchMS=0;return}if(this.hitchCounter&gt;0){this.hitchCounter--;s+="-"+this.hitchMS.toFixed(0)+"! "}else{this.hitchMS=0}s+=this.trueDeltaMS.toFixed(0)+" "+this.deltaMS.toFixed(0)+" "+average.toFixed(1);this.span.textContent=s;this.didDraw=true},hitch:function(hitchMS,windowMS){this.hitchMS+=hitchMS;this.hitchCounter=Math.floor(windowMS/1e3*60)}};gs.ProfilerVisualizer=function(){this.setEntityProfilerRowMax={};this.setProfilerCellCache={};this.frameCount=0;this.root=null;this.frame=null;this.counters=null;this.createDOM()};gs.ProfilerVisualizer.prototype={createDOM:function(){this.root=gs.dom.create("DIV");this.root.className="gse-debug gse-profiler";this.frame=this.createTable("frame","1/s","ms","%");this.addRow(this.frame,"frame");this.addRow(this.frame,"- engine");this.addRow(this.frame,"-- evaluate");this.addRow(this.frame,"-- physics");this.addRow(this.frame,"-- render");this.addRow(this.frame,"- profile");this.addRow(this.frame,"- idle");this.addRow(this.frame,"input");this.root.appendChild(this.frame);this.counters=this.createTable("counters","now","max");this.addRow(this.counters,"layers");this.addRow(this.counters,"actors");this.addRow(this.counters,"sprites");this.addRow(this.counters,"particles");this.addRow(this.counters,"textures");this.addRow(this.counters,"awake");this.addRow(this.counters,"contacts");this.root.appendChild(this.counters)},createTable:function(title){var table=gs.dom.create("TABLE");table.gseColumnCount=arguments.length;table.gseRows=[];var caption=gs.dom.create("CAPTION");caption.textContent=title;table.appendChild(caption);var tr=gs.dom.create("TR");tr.gseCells=[];var th=gs.dom.create("TH");th.textContent=" ";tr.appendChild(th);tr.gseCells.push(th);for(var i=1;i&lt;arguments.length;i++){th=gs.dom.create("TH");th.textContent=arguments[i];tr.appendChild(th);tr.gseCells.push(th)}table.appendChild(tr);table.gseRows.push(tr);return table},addRow:function(table,label){var tr=gs.dom.create("TR");tr.gseCells=[];var td=gs.dom.create("TD");td.textContent=label;tr.appendChild(td);tr.gseCells.push(td);for(var i=1;i&lt;table.gseColumnCount;i++){td=gs.dom.create("TD");tr.appendChild(td);tr.gseCells.push(td);if(arguments[i+1]){th.textContent=arguments[i+1]}}table.appendChild(tr);table.gseRows.push(tr)},setCell:function(table,r,c,v){var cell=table.gseRows[r].gseCells[c];cell.textContent=v},setProfilerCell:function(field,cell,text){var rowCache=this.setProfilerCellCache[field];if(!rowCache){rowCache=[];this.setProfilerCellCache[field]=rowCache}var cellCache=rowCache[cell];if(!cellCache){cellCache={previous:"",map:{},element:null};rowCache[cell]=cellCache}if(text===cellCache.previous){return}var textNode=cellCache.map[text];if(!textNode){textNode=document.createTextNode(text);cellCache.map[text]=textNode}cellCache.previous=text;if(!cellCache.element){var tr=null;$("#developer-profiler tr").each(function(){if(tr){return}if($(this).attr("data-field")===field){tr=$(this)[0]}});cellCache.element=$(tr).find("td")[cell]}var td=cellCache.element;if(td.firstChild){td.replaceChild(textNode,td.firstChild)}else{td.appendChild(textNode)}},setFrameProfilerRow:function(field,row,valueMS,frameMS){var perSecond=valueMS===0?0:1e3/valueMS;if(field==="frame"){this.setCell(this.frame,row,1,Math.ceil(perSecond).toString())}else if(field==="engine"){var engineRate=Math.ceil(perSecond).toString();if(perSecond&gt;99){engineRate="99"}this.setCell(this.frame,row,1,engineRate)}var fraction=frameMS===0?0:valueMS/frameMS;this.setCell(this.frame,row,2,valueMS.toFixed(1));this.setCell(this.frame,row,3,Math.ceil(100*fraction).toString())},setEntityProfilerRow:function(field,row,value){var max=this.setEntityProfilerRowMax[field];if(max===undefined||max&lt;value){max=value;this.setEntityProfilerRowMax[field]=max}this.setCell(this.counters,row,1,value);this.setCell(this.counters,row,2,max)},setSceneProfilerTimerRow:function(field,valueMS,totalMS){var fraction=totalMS===0?0:valueMS/totalMS;this.setProfilerCell(field,1,valueMS.toFixed(0));this.setProfilerCell(field,2,Math.ceil(100*fraction).toString())},setGameProfilerTimerRow:function(field,valueMS,totalMS){var fraction=totalMS===0?0:valueMS/totalMS;this.setProfilerCell(field,1,valueMS.toFixed(0));this.setProfilerCell(field,2,Math.ceil(100*fraction).toString())},setSceneProfilerCounterRow:function(field,value){this.setProfilerCell(field,1,value.toFixed(0))},onProfilerFrame:function(frame,entities,gameLoad,sceneLoad){var row=1;this.setEntityProfilerRow("layers",row++,entities.layers);this.setEntityProfilerRow("actors",row++,entities.actors);this.setEntityProfilerRow("sprites",row++,entities.sprites);this.setEntityProfilerRow("particles",row++,entities.particles);this.setEntityProfilerRow("textures",row++,entities.textures);this.setEntityProfilerRow("awake",row++,entities.awake);this.setEntityProfilerRow("contacts",row++,entities.contacts);if(this.frameCount++%5!==0){return}row=1;this.setFrameProfilerRow("frame",row++,frame.frame,frame.frame);this.setFrameProfilerRow("engine",row++,frame.engine,frame.frame);this.setFrameProfilerRow("evaluate",row++,frame.simulate,frame.frame);this.setFrameProfilerRow("physics",row++,frame.physics,frame.frame);this.setFrameProfilerRow("render",row++,frame.render,frame.frame);this.setFrameProfilerRow("profile",row++,frame.profile,frame.frame);var idle=frame.frame-frame.engine-frame.profile;this.setFrameProfilerRow("idle",row++,idle,frame.frame);this.setFrameProfilerRow("input",row++,frame.input,frame.frame)}};gs.analytics.DataType={HEADER:"h",ATTRIBUTES:"a",SESSION_OPEN:"s",SESSION_CLOSE:"c",EVENT:"e",UNKNOWN:"x"};gs.analytics.Attribute={DATA_TYPE:"dt",LIBRARY_VERSION:"lv",APP_UNIQUE_KEY:"au",APP_DISPLAY_NAME:"adn",APP_VERSION:"av",APP_DEVELOPER_ID:"devid",APP_UNIQUE_ID:"APP_UNIQUE_ID",APP_CREATOR_VERSION:"pcv",APP_RELEASE_ID:"ari",APP_LICENSE_TYPE:"alt",APP_INSTALL_ID:"iu",APP_DEVELOPER_USERNAME:"devun",DEVICE_UNIQUE_ID:"du",DEVICE_UNIQUE_ID_HASH:"udid",DEVICE_PLATFORM:"dp",DEVICE_OS_VERSION:"dov",DEVICE_COUNTRY:"dc",DEVICE_LOCALE_LANGUAGE:"dll",DEVICE_LOCALE_COUNTRY:"dlc",PREVIOUS_SCENE:"ps",NEXT_SCENE:"ns",UNKNOWN:""};gs.analytics.EventName={SCENE_CHANGE:"sceneChange"};gs.analytics.Blob=function(dataType){this["dt"]=dataType;this["u"]=gs.util.generateUUID();this["ct"]=gs.util.getSecondsSinceUnixEpoch()};gs.analytics.Blob.prototype={setAttribute:function(key,value){if(!this["attrs"]){this["attrs"]={dt:gs.analytics.DataType.ATTRIBUTES}}this["attrs"][key]=value}};gs.analytics.Header=function(uploadIndex,firstRunTime){gs.analytics.Blob.call(this,gs.analytics.DataType.HEADER);this["seq"]=uploadIndex;this["pa"]=firstRunTime;this.setAttribute(gs.analytics.Attribute.LIBRARY_VERSION,gs.analytics.Header.Constants.LIBRARY_VERSION)};gs.analytics.Header.Constants={LIBRARY_VERSION:"html5_1.0"};gs.analytics.Header.prototype=Object.create(gs.analytics.Blob.prototype,{});gs.analytics.SessionBlob=function(dataType,sessionID){gs.analytics.Blob.call(this,dataType);this["su"]=sessionID};gs.analytics.SessionBlob.prototype=Object.create(gs.analytics.Blob.prototype,{});gs.analytics.SessionOpen=function(sessionUUID,sessionIndex){gs.analytics.Blob.call(this,gs.analytics.DataType.SESSION_OPEN);this["u"]=sessionUUID;this["nth"]=sessionIndex};gs.analytics.SessionOpen.prototype=Object.create(gs.analytics.Blob.prototype,{});gs.analytics.SessionClose=function(sessionID,sessionDuration){gs.analytics.SessionBlob.call(this,gs.analytics.DataType.SESSION_CLOSE,sessionID);this["ctl"]=sessionDuration};gs.analytics.SessionClose.prototype=Object.create(gs.analytics.SessionBlob.prototype,{});gs.analytics.Event=function(sessionID,eventName){gs.analytics.SessionBlob.call(this,gs.analytics.DataType.EVENT,sessionID);this["n"]=eventName};gs.analytics.Event.prototype=Object.create(gs.analytics.SessionBlob.prototype,{});gs.analytics.Session=function(sessionIndex,sessionManager){this.sessionIndex=sessionIndex;this.sessionManager=sessionManager;this.blobs=[];this.sessionUUID=gs.util.generateUUID();this.isOpen=false;this.openTime=null;this.closeTime=null;this.unloadEventListener=null;this.previousScene=gs.analytics.Session.Constants.NO_SCENE};gs.analytics.Session.Constants={NO_SCENE:" "};gs.analytics.Session.prototype={open:function(){if(!this.isOpen){this.isOpen=true;this.openTime=gs.util.getSecondsSinceUnixEpoch();this.appendSessionOpen();var that=this;this.unloadEventListener=window.addEventListener("unload",function(event){that.close()},false)}},close:function(){if(this.isOpen){this.closeTime=gs.util.getSecondsSinceUnixEpoch();this.appendSessionClose();this.isOpen=false;window.removeEventListener("unload",this.unloadEventListener,false);this.unloadEventListener=null;this.sessionManager.appendSession(this)}},appendBlob:function(blob){this.blobs.push(blob)},appendSessionOpen:function(){var sessionOpenBlob=new gs.analytics.SessionOpen(this.sessionUUID,this.sessionIndex);this.appendBlob(sessionOpenBlob)},appendSessionClose:function(){var sessionDuration=this.closeTime-this.openTime;var sessionCloseBlob=new gs.analytics.SessionClose(this.sessionUUID,sessionDuration);this.appendBlob(sessionCloseBlob)},newEvent:function(eventName){var eventBlob=new gs.analytics.Event(this.sessionUUID,eventName);eventBlob[gs.analytics.Attribute.APP_UNIQUE_KEY]=this.sessionManager.getAppUniqueKey();return eventBlob},beginSceneChange:function(previousScene){if(previousScene!==null){this.previousScene=previousScene}else{this.previousScene=gs.analytics.Session.Constants.NO_SCENE}},endSceneChange:function(nextScene){var attr=gs.analytics.Attribute;var event=this.newEvent(gs.analytics.EventName.SCENE_CHANGE);event.setAttribute(attr.PREVIOUS_SCENE,this.previousScene);event.setAttribute(attr.NEXT_SCENE,nextScene);this.appendBlob(event);this.previousScene=gs.analytics.Session.Constants.NO_SCENE}};gs.analytics.SessionManager=function(externalDelegate){this.uploadingIsEnabled=false;this.storedSessionCount=null;this.blobs=null;this.sessionCount=null;this.uploadSequence=null;this.persistedAt=null;this.externalDelegate=externalDelegate};gs.analytics.SessionManager.prototype={keys:{sessionCount:"engine/gs.analytics.nth",uploadSequence:"engine/gs.analytics.seq",persistedAt:"engine/gs.analytics.pa",storedSessionCount:"engine/gs.analytics.storedSessionCount",storedSessionsPrefix:"engine/gs.analytics.storedSessions/",externalPrefix:"analytics/",uploadUrls:"UPLOAD_URLS"},enableUploading:function(){this.uploadingIsEnabled=true},flush:function(){this.readStateFromStorage();this.readBlobsFromStorage();if(this.uploadingIsEnabled){if(this.blobs.length&gt;0){this.uploadSequence++;var headerBlob=this.createHeader();var postBody=this.formatUploadContent(headerBlob,this.blobs);var uploadUrls=this.readExternalValue(this.keys.uploadUrls);if(uploadUrls){if(uploadUrls.forEach){var that=this;uploadUrls.forEach(function(uploadUrl){that.upload(uploadUrl,postBody)})}else{this.upload(uploadUrls,postBody)}}}}this.clearBlobsFromStorage();this.writeStateToStorage()},clearBlobsFromStorage:function(){for(var i=0;i&lt;this.storedSessionCount;i++){var storageKey=this.keys.storedSessionsPrefix+i;this.writeObjectToStorage(storageKey,null)}this.storedSessionCount=0},upload:function(uploadUrl,postBody){var request=new XMLHttpRequest;request.open("POST",uploadUrl,true);request.send(postBody);gs.Log.info("Posted analytics to:",uploadUrl)},createHeader:function(){var headerBlob=new gs.analytics.Header(this.uploadSequence,this.persistedAt);var attr=gs.analytics.Attribute;var attrReversed=gs.util.reverseMap(attr);var that=this;var readExternal=function(enumValue){var enumKey=attrReversed[enumValue];return that.readExternalValue(enumKey)};var queryHeaderAttribute=function(key){var value=readExternal(key);if(value!==null){headerBlob.setAttribute(key,value)}};var appUniqueKey=this.getAppUniqueKey();headerBlob.setAttribute(attr.APP_UNIQUE_KEY,appUniqueKey);queryHeaderAttribute(attr.APP_DISPLAY_NAME);queryHeaderAttribute(attr.APP_VERSION);queryHeaderAttribute(attr.APP_DEVELOPER_ID);queryHeaderAttribute(attr.APP_CREATOR_VERSION);queryHeaderAttribute(attr.APP_RELEASE_ID);queryHeaderAttribute(attr.APP_LICENSE_TYPE);queryHeaderAttribute(attr.APP_INSTALL_ID);queryHeaderAttribute(attr.APP_DEVELOPER_USERNAME);queryHeaderAttribute(attr.DEVICE_UNIQUE_ID);queryHeaderAttribute(attr.DEVICE_UNIQUE_ID_HASH);queryHeaderAttribute(attr.DEVICE_PLATFORM);queryHeaderAttribute(attr.DEVICE_OS_VERSION);queryHeaderAttribute(attr.DEVICE_COUNTRY);queryHeaderAttribute(attr.DEVICE_LOCALE_LANGUAGE);queryHeaderAttribute(attr.DEVICE_LOCALE_COUNTRY);return headerBlob},getAppUniqueKey:function(){var attr=gs.analytics.Attribute;var attrReversed=gs.util.reverseMap(attr);var developerID=this.readExternalValue(attrReversed[gs.analytics.Attribute.APP_DEVELOPER_ID]);var appID=this.readExternalValue(attrReversed[gs.analytics.Attribute.APP_UNIQUE_ID]);return developerID+"-"+appID},formatUploadContent:function(headerBlob,blobs){var root=[];root.push(headerBlob);blobs.forEach(function(blob){root.push(blob)});return JSON.stringify(root)},appendSession:function(session){this.readStateFromStorage();var storageKey=this.keys.storedSessionsPrefix+this.storedSessionCount;this.writeObjectToStorage(storageKey,session.blobs);this.storedSessionCount++;this.writeStateToStorage()},openNewSession:function(){this.readStateFromStorage();var sessionIndex=++this.sessionCount;this.writeStateToStorage();var session=new gs.analytics.Session(sessionIndex,this);session.open();return session},readStateFromStorage:function(){this.sessionCount=this.readObjectFromStorage(this.keys.sessionCount);if(this.sessionCount===null){this.sessionCount=0}this.uploadSequence=this.readObjectFromStorage(this.keys.uploadSequence);if(this.uploadSequence===null){this.uploadSequence=0}this.persistedAt=this.readObjectFromStorage(this.keys.persistedAt);if(this.persistedAt===null){this.persistedAt=gs.util.getSecondsSinceUnixEpoch()}this.storedSessionCount=this.readObjectFromStorage(this.keys.storedSessionCount);if(this.storedSessionCount===null){this.storedSessionCount=0}},readBlobsFromStorage:function(){var blobs=[];for(var i=0;i&lt;this.storedSessionCount;i++){var storageKey=this.keys.storedSessionsPrefix+i;var sessionBlobs=this.readObjectFromStorage(storageKey);if(sessionBlobs){sessionBlobs.forEach(function(blob){blobs.push(blob)})}}this.blobs=blobs},writeStateToStorage:function(){this.writeObjectToStorage(this.keys.sessionCount,this.sessionCount);this.writeObjectToStorage(this.keys.uploadSequence,this.uploadSequence);this.writeObjectToStorage(this.keys.persistedAt,this.persistedAt);this.writeObjectToStorage(this.keys.storedSessionCount,this.storedSessionCount)},readObjectFromStorage:function(key){return gs.LocalStorage.getObject(key)},writeObjectToStorage:function(key,value){return gs.LocalStorage.setObject(key,value)},readExternalValue:function(virtualKey){var realKey=this.keys.externalPrefix+virtualKey;if(this.externalDelegate){return this.externalDelegate.readExternalValueSync(realKey)}else{return gs.EngineContext.current.delegate.onExternalReadSync(realKey)}}};gs.file={getExtension:function(path){var pattern=/\.(\w+)$/;var match=pattern.exec(path);if(match){return match[1]}else{return null}},replaceExtension:function(path,newExtension){newExtension="."+newExtension;var pattern=/\.(\w+)$/;if(pattern.test(path)){return path.replace(pattern,newExtension)}else{return path+newExtension}},removeExtension:function(path){var pattern=/\.(\w+)$/;if(pattern.test(path)){return path.replace(pattern,"")}else{return path}},joinPath:function(before,after){var trimBack=/^(.*?)\/*$/;var matchBefore=trimBack.exec(String(before));before=matchBefore[1];var trimFront=/^\/*(.*)$/;var matchAfter=trimFront.exec(String(after));after=matchAfter[1];return before+"/"+after}};gs.file.Format={XML:"XML",JSON:"JSON",JSONP:"JSONP"};gs.file.Format.getFileExtension=function(format){switch(String(format).toUpperCase()){case gs.file.Format.XML:return"xml";case gs.file.Format.JSON:return"json";case gs.file.Format.JSONP:return"js";default:gs.Log.error("Unrecognized format:",format);return""}};gs.file.File=function(){this.cacheKey=null;this.text=null;this.data=null;this.format=null};gs.file.File.prototype={getText:function(){return this.text},setText:function(text){this.text=text},clearText:function(){this.setText(null)},getData:function(){gs.JXON.detect(this.data);return this.data},setData:function(data){this.data=data},hasData:function(){return this.data!==null},getFormat:function(){return this.format},setFormat:function(format){this.format=format}};gs.file.FileFetcher=function(){};gs.file.FileFetcher.onRequestLoad=function(event){var request=this;request.fetcher.onRequestLoad(request,event)};gs.file.FileFetcher.onRequestError=function(event){var request=this;request.fetcher.onRequestError(request,event)};gs.file.FileFetcher.onScriptLoad=function(event){var script=this;script.fetcher.onScriptLoad(script,event)};gs.file.FileFetcher.onScriptError=function(event){var script=this;script.fetcher.onScriptError(script,event)};gs.file.FileFetcher.prototype={extensions:{JSON:"JSON",XML:"XML",JS:"JS"},fetch:function(path){var extension=gs.file.getExtension(path).toUpperCase();switch(extension){case this.extensions.JSON:return this.fetchJSON(path);case this.extensions.XML:return this.fetchText(path);case this.extensions.JS:return this.fetchJSONP(path);default:var promise=new gs.Promise;promise.reject("Unexpected file extension: "+extension);return promise}},fetchText:function(path){var request=new XMLHttpRequest;request.fetcher=this;request.promise=new gs.Promise;request.path=path;request.addEventListener("load",gs.file.FileFetcher.onRequestLoad,false);request.addEventListener("error",gs.file.FileFetcher.onRequestError,false);try{request.open("GET",path,true);request.send(null)}catch(exception){gs.file.FileFetcher.onRequestError.call(request,exception)}return request.promise},fetchJSON:function(path){var request=new XMLHttpRequest;request.fetcher=this;request.promise=new gs.Promise;request.path=path;request.addEventListener("load",gs.file.FileFetcher.onRequestLoad,false);request.addEventListener("error",gs.file.FileFetcher.onRequestError,false);try{request.open("GET",path,true);request.send(null)}catch(exception){gs.file.FileFetcher.onRequestError.call(request,exception)}return request.promise},fetchJSONP:function(path){var script=document.createElement("SCRIPT");script.fetcher=this;script.promise=new gs.Promise;script.src=path;script.async=true;script.onload=gs.file.FileFetcher.onScriptLoad;script.onerror=gs.file.FileFetcher.onScriptError;var head=document.getElementsByTagName("HEAD")[0];head.appendChild(script);return script.promise},onRequestLoad:function(request,event){var ok=request.status===200||request.status===0&amp;&amp;request.response;if(!ok){return this.onRequestError(request,event)}var promise=request.promise;var path=request.path;var file=new gs.file.File;var response=request.response||request.responseText;var extension=gs.file.getExtension(path);if(extension===gs.file.Format.getFileExtension(gs.file.Format.XML)){file.setFormat(gs.file.Format.XML);file.setText(response)}else{file.setFormat(gs.file.Format.JSON);if(typeof response==="string"){file.setData(JSON.parse(response))}else{file.setData(response)}}this.deserialize(file);promise.resolve(file)},onRequestError:function(request,event){var promise=request.promise;promise.reject(event)},onScriptLoad:function(script,event){script.parentNode.removeChild(script);for(var key in script){delete script[key]}},onScriptError:function(script,event){script.parentNode.removeChild(script);var promise=script.promise;promise.reject(event);for(var key in script){delete script[key]}},deserializeJSON:function(file){var data;if(!file.hasData()){var text=file.getText();file.clearText();data=JSON.parse(text);file.setData(data)}data=file.getData();if(data&amp;&amp;data["_type"]){data=gs.Prototypical.convertJXONLite(data);file.setData(data)}},deserializeXML:function(file){if(!file.hasData()){var text=file.getText();file.clearText();var data=gs.XML.parse(text);file.setData(data)}},deserialize:function(file){if(file.getFormat()===gs.file.Format.XML){this.deserializeXML(file)}else{this.deserializeJSON(file)}}};gs.file.FileCache=function(){this.fileMap={};this.requestMap={};this.jsonpMap={};this.fetcher=new gs.file.FileFetcher;if(!pgf["jsonp"]){var that=this;pgf["jsonp"]=function(key,meta,data){if(data===undefined){data=meta}var tuple=that.jsonpMap[key];if(tuple){var file=new gs.file.File;file.setData(data);that.setFile(key,file);tuple.promise.resolve(file);delete that.jsonpMap[key];delete that.requestMap[tuple.path]}}}};gs.file.FileCache.prototype={fetch:function(path,key){if(gs.file.getExtension(path)===gs.file.Format.getFileExtension(gs.file.Format.JSONP)){var promise=new gs.Promise;this.jsonpMap[key]={path:path,promise:promise};this.fetchFile(path,key).otherwise(function failureFetchFile(failure){promise.reject(failure)});return promise}else{return this.fetchFile(path,key)}},fetchFile:function(path,key){var promise=new gs.Promise;var that=this;var file=this.getFile(path);if(file){promise.resolve(file);return promise}var request=this.requestMap[path];if(request){request.then(function successFetchFile(file){promise.resolve(file)},function failureFetchFile(failure){promise.reject(failure)})}else{var requestPromise=this.fetcher.fetch(path);this.requestMap[path]=requestPromise;requestPromise.then(function successFetchFile(file){that.setFile(key,file);delete that.requestMap[path];promise.resolve(file)},function failureFetchFile(failure){delete that.requestMap[path];promise.reject(failure)})}return promise},setFile:function(key,file){file.cacheKey=key;this.fileMap[key]=file},getFile:function(key){if(key in this.fileMap){return this.fileMap[key]}else{return null}},deleteFile:function(file){delete this.fileMap[file.cacheKey]},deleteFileKey:function(key){delete this.fileMap[key]}};gs.file.VirtualFileCache=function(){this.cache=new gs.file.FileCache;this.prefix=null;this.retainSceneByIndexMap={};this.setFormats([gs.file.Format.JSON]);gs.file.VirtualFileCache.instance=this;gs.file.VirtualFileCache.current=this};gs.file.VirtualFileCache.prototype={strings:{game:"game",object:"object",assets:"assets",actors:"actors",scenes:"scenes",tables:"tables",images:"images"},setPrefix:function(prefix){this.prefix=prefix},setFormats:function(formats){this.formats=formats;this.extensions=[];for(var i=0;i&lt;formats.length;i++){this.extensions[i]=gs.file.Format.getFileExtension(formats[i])}},setDefaultExtension:function(extension){var index=this.extensions.indexOf(extension);if(index&gt;0){var format=this.formats[index];this.extensions.splice(index,1);this.extensions.unshift(extension);this.formats.splice(index,1);this.formats.unshift(format)}},getRealPath:function(virtualPath){var realPath=gs.file.joinPath(this.prefix,virtualPath);var extension=gs.file.getExtension(virtualPath);if(extension===null){var defaultExtension=gs.file.Format.getFileExtension(this.formats[0]);realPath+="."+defaultExtension}return realPath},fetch:function(virtualPath){var promise=new gs.Promise;var that=this;var key=gs.file.removeExtension(virtualPath);var file=this.cache.getFile(key);if(file){promise.resolve(file);return promise}var realPath=this.getRealPath(virtualPath);this.cache.fetch(realPath,key).then(function successFetchVirtual(realFile){that.cache.deleteFile(realFile);that.cache.setFile(key,realFile);promise.resolve(realFile)},function failureFetchVirtual(failure){promise.reject(failure)});return promise},fetchData:function(virtualPath){var promise=new gs.Promise;var currentExtension=gs.file.getExtension(virtualPath);var currentIndex=this.extensions.indexOf(currentExtension);if(currentIndex===-1){currentIndex=0;currentExtension=this.extensions[currentIndex]}var that=this;this.fetch(virtualPath).then(function successFetchData(file){that.setDefaultExtension(currentExtension);promise.resolve(file)}).otherwise(function failureFetchData(failure){var nextIndex=currentIndex+1;if(nextIndex&lt;that.extensions.length){var nextPath=gs.file.replaceExtension(virtualPath,that.extensions[nextIndex]);that.fetchData(nextPath).then(function successFetchData(file){promise.resolve(file)}).otherwise(function failureFetchData(failure){promise.reject(failure)})}else{promise.reject(failure)}});return promise},deserializeJSON:function(file){var data;if(!file.hasData()){var text=file.getText();file.clearText();data=JSON.parse(text);file.setData(data)}data=file.getData();if(data["_type"]){data=gs.Prototypical.convertJXONLite(data);file.setData(data)}},deserializeXML:function(file){if(!file.hasData()){var text=file.getText();file.clearText();var data=gs.XML.parse(text);file.setData(data)}},deserialize:function(file){if(file.getFormat()===gs.file.Format.XML){this.deserializeXML(file)}else{this.deserializeJSON(file)}},fetchGame:function(){var promise=new gs.Promise;var that=this;var file=this.cache.getFile(this.strings.game);if(file){promise.resolve(file)}else{this.fetchData(that.strings.object).then(function successFetchGame(file){that.cache.setFile(that.strings.game,file);promise.resolve(file)},function failureFetchGame(failure){promise.reject(failure)})}return promise},loadGame:function(){var promise=new gs.Promise;var that=this;this.fetchGame().then(function successLoadGame(file){that.deserialize(file);promise.resolve(file)},function failureLoadGame(failure){promise.reject(failure)});return promise},deleteGame:function(){this.cache.deleteFileKey(this.strings.object);this.cache.deleteFileKey(this.strings.game)},fetchSceneByIndex:function(index){var path=gs.file.joinPath(this.strings.scenes,index);return this.fetchData(path)},loadSceneByIndex:function(index){var promise=new gs.Promise;var that=this;this.fetchSceneByIndex(index).then(function successLoadScene(file){that.deserialize(file);if(!that.retainSceneByIndexMap[index]){that.cache.deleteFile(file)}promise.resolve(file)},function failureLoadScene(failure){promise.reject(failure)});return promise},retainSceneByIndex:function(index){this.retainSceneByIndexMap[index]=true},isSceneRetainedByIndex:function(index){return this.retainSceneByIndexMap[index]},fetchActorPrototypeByIndex:function(index){var path=gs.file.joinPath(this.strings.actors,index);return this.fetchData(path)},loadActorPrototypeByIndex:function(index){var promise=new gs.Promise;var that=this;this.fetchActorPrototypeByIndex(index).then(function successLoadActorPrototype(file){that.deserialize(file);that.cache.deleteFile(file);promise.resolve(file)},function failureLoadActorPrototype(failure){promise.reject(failure)});return promise},fetchAllActorPrototypes:function(){var promise=new gs.Promise;var that=this;this.loadGame().then(function(gameFile){var actors=null;var promises=[];var game=gameFile.getData();actors=game["prototypes"];if(actors){if(!Array.isArray(actors)){actors=[actors]}for(var index=1;index&lt;=actors.length;index++){var actor=actors[index-1];var actorPath=gs.file.joinPath(that.strings.actors,index.toString());if(actor["attributes"]){var actorFile=new gs.file.File;actorFile.setData(actor);that.cache.setFile(actorPath,actorFile)}else{promises.push(that.fetchData(actorPath))}}}if(promises.length&gt;0){gs.Promise.all(promises,function(){promise.resolve()},function(failure){promise.reject(failure)})}else{promise.resolve()}});return promise},fetchAssetsManifest:function(){return this.fetchData(this.strings.assets)},loadAssetsManifest:function(){var promise=new gs.Promise;var that=this;this.fetchAssetsManifest().then(function successLoadAssetManifest(file){that.deserialize(file);that.cache.deleteFile(file);promise.resolve(file)},function failureLoadAssetManifest(failure){promise.reject(failure)});return promise},fetchTableById:function(id){var path=gs.file.joinPath(this.strings.tables,id);return this.fetchData(path)},loadTableById:function(id){var promise=new gs.Promise;var that=this;this.fetchTableById(id).then(function successLoadTable(file){that.deserialize(file);that.cache.deleteFile(file);promise.resolve(file)},function failureLoadTable(failure){promise.reject(failure)});return promise}};gs.tables={getKeypath:function(key){if(!/^game\.attributes\./.test(key)){key="game.attributes."+key}return key},saveToPersistence:function(table,key){var persistenceObject=table.serialize();gs.LocalStorage.setObject(key,persistenceObject)},loadFromPersistence:function(table,key){var persistenceObject=gs.LocalStorage.getObject(key);if(persistenceObject===null){return false}table.parseFromJXON(persistenceObject);return true}};gs.tables.Table=function(){this.id="";this.name="";this.rowCount=0;this.columnCount=0;this.rowNames=[];this.rowNamesLower=[];this.columnNames=[];this.columnNamesLower=[];this.columnTypes=[];this.data=[];this.tempCell={row:0,column:0}};gs.tables.Table.prototype={setId:function(id){this.id=id},clear:function(){this.rowCount=0;this.columnCount=0;this.rowNames.length=0;this.rowNamesLower.length=0;this.columnNames.length=0;this.columnNamesLower.length=0;this.columnTypes.length=0;this.data.length=0},appendColumn:function(name,type){this.columnNames.push(name);this.columnNamesLower.push(name.toLowerCase());this.columnTypes.push(type);var defaultValue=this.defaultValueForType(type);for(var rowi=0;rowi&lt;this.rowCount;rowi++){var row=this.data[rowi];row.push(defaultValue)}this.columnCount++},insertRow:function(row,name){if(name===undefined){name=""}row=this.lookupRow(row);var rowi=row-1;gs.array.insert(this.rowNames,rowi,name);gs.array.insert(this.rowNamesLower,rowi,name.toLowerCase());gs.array.insert(this.data,rowi,gs.array.provide());for(var columni=0;columni&lt;this.columnCount;columni++){var columnType=this.columnTypes[columni];var defaultValue=this.defaultValueForType(columnType);this.data[rowi][columni]=defaultValue}this.rowCount++},insertRowAtEnd:function(name){this.insertRow(this.rowCount+1,name)},insertRowAtBegin:function(name){this.insertRow(1,name)},setRowName:function(row,name){var rowi=row-1;this.rowNames[rowi]=name;this.rowNamesLower[rowi]=name.toLowerCase()},getColumnType:function(column){column=this.lookupColumn(column);return this.columnTypes[column-1]},getCellType:function(row,column){return this.getColumnType(column)},removeRow:function(row){var rowBase1=this.lookupRow(row);if(rowBase1===-1){rowBase1=this.rowCount}else if(rowBase1&lt;=0||this.rowCount&lt;rowBase1){gs.Log.debug("Bad removeRow",row,this.rowCount);return}var rowBase0=rowBase1-1;gs.array.remove(this.rowNames,rowBase0);gs.array.remove(this.rowNamesLower,rowBase0);gs.array.remove(this.data,rowBase0);this.rowCount--},removeRowAtEnd:function(){if(this.rowCount&gt;0){this.removeRow(this.rowCount)}},getCell:function(row,column){var cell=this.lookupCell(row,column);return this.getCellByIndex(cell.row,cell.column)},getCellByIndex:function(row,column){if(this.isInBounds(row,column)){return this.data[row-1][column-1]}else{if(row===this.rowCount&amp;&amp;this.rowCount===0){}else{gs.Log.warn("gs.Table.getCellByIndex out-of-bounds",this.id,this.name,this.rowCount,this.columnCount,row,column);return undefined}return""}},setCell:function(row,column,value){var cell=this.lookupCell(row,column);this.setCellByIndex(cell.row,cell.column,value)},setCellByIndex:function(row,column,value){if(this.isInBounds(row,column)){var lastValue=this.data[row-1][column-1];this.data[row-1][column-1]=value;return lastValue}else{gs.Log.warn("gs.Table.setCellByIndex out-of-bounds",this.id,this.name,this.rowCount,this.columnCount,row,column,value);return value}},emptyValue:function(v){var t=typeof v;return t==="undefined"||(t==="object"?v===null||Object.keys(v).length===0:[false,0,"","0"].indexOf(v)&gt;=0)},isInBounds:function(row,column){var goodRow=1&lt;=row&amp;&amp;row&lt;=this.rowCount;var goodColumn=1&lt;=column&amp;&amp;column&lt;=this.columnCount;return goodRow&amp;&amp;goodColumn},lookupRow:function(row){if(typeof row==="number"){return row}if(typeof row==="string"){var rowLower=row.toLowerCase();var index=this.rowNamesLower.indexOf(rowLower);if(index!==-1){return index+1}var rowParsed=gs.parseInteger(row);if(!isNaN(rowParsed)){return rowParsed}}gs.Log.error("bad row",row);return 0},lookupColumn:function(column){if(typeof column==="number"){return column}if(typeof column==="string"){var columnLower=column.toLowerCase();var index=this.columnNamesLower.indexOf(columnLower);if(index!==-1){return index+1}var columnParsed=gs.parseInteger(column);if(!isNaN(columnParsed)){return columnParsed}}gs.Log.error("bad column",column);return 0},lookupCell:function(row,column){this.tempCell.row=this.lookupRow(row);this.tempCell.column=this.lookupColumn(column);return this.tempCell},getTypeByEnum:function(typeEnum){switch(typeEnum){case 0:case 1:return"text";case 2:return"integer";case 3:return"real";case 4:return"boolean";case 5:return"angle";case 6:return"image";case 7:return"sound";default:gs.Log.error("bad type enum",typeEnum);return null}},getEnumByType:function(typeString){switch(typeString){case"text":return 1;case"integer":return 2;case"real":return 3;case"boolean":return 4;case"angle":return 5;case"image":return 6;case"sound":return 7;default:gs.Log.error("bad type string",typeString);return 0}},defaultValueForType:function(type){switch(type){case"boolean":return false;case"text":case"image":case"sound":return"";default:return 0}},coerceType:function(value,type){var valueType=typeof value;switch(type){case"boolean":return valueType==="boolean"?value:gs.parseBoolean(value);case"text":case"image":case"sound":return valueType==="string"?value:String(value);case"real":return valueType==="number"?value:parseFloat(value);default:return valueType==="number"?value:gs.parseInteger(value)}},parseFromLite:function(tableJXON){this.name=tableJXON["name"];var rowi,columni;var rowJXON,columnJXON;var rowCount=gs.parseInteger(tableJXON["numRows"]);var columnCount=gs.parseInteger(tableJXON["numCols"]);var columns=tableJXON["columns"];if(!Array.isArray(columns)){columns=[columns]}for(columni=0;columni&lt;columnCount;columni++){columnJXON=columns[columni];var typeEnum=gs.parseInteger(columnJXON["type"]);this.appendColumn(columnJXON["name"],this.getTypeByEnum(typeEnum))}var rows=tableJXON["rows"];if(!Array.isArray(rows)){rows=[rows]}for(rowi=0;rowi&lt;rowCount;rowi++){rowJXON=rows[rowi];this.insertRowAtEnd(rowJXON["name"])}for(columni=0;columni&lt;columnCount;columni++){columnJXON=columns[columni];var columnData=columnJXON["$"];if(columnData){if(!Array.isArray(columnData)){columnData=gs.Prototypical.parseCSV(columnData)}var columnType=this.columnTypes[columni];for(rowi=0;rowi&lt;rowCount;rowi++){this.data[rowi][columni]=this.coerceType(columnData[rowi],columnType)}}}},parseFromJXON:function(tableJXON){gs.JXON.detect(tableJXON);this.name=tableJXON["name"];var rowi,columni;var rowJXON,columnJXON;var rowCount=gs.parseInteger(tableJXON["numRows"]);var columnCount=gs.parseInteger(tableJXON["numCols"]);var columnsTag=gs.JXON.childWithTag(tableJXON,"columns");var columns=gs.JXON.childrenWithTag(columnsTag,"column");for(columni=0;columni&lt;columnCount;columni++){columnJXON=columns[columni];var typeEnum=gs.parseInteger(columnJXON["type"]);this.appendColumn(columnJXON["name"],this.getTypeByEnum(typeEnum))}var rowsTag=gs.JXON.childWithTag(tableJXON,"rows");var rows=gs.JXON.childrenWithTag(rowsTag,"row");for(rowi=0;rowi&lt;rowCount;rowi++){rowJXON=rows[rowi];this.insertRowAtEnd(rowJXON["name"])}for(columni=0;columni&lt;columnCount;columni++){columnJXON=columns[columni];var columnData=columnJXON[gs.JXON._text];if(columnData){var columnType=this.columnTypes[columni];for(rowi=0;rowi&lt;rowCount;rowi++){this.data[rowi][columni]=this.coerceType(columnData[rowi],columnType)}}}},copyFromOtherTable:function(otherTable){this.clear();var rowi,columni;var rowCount=otherTable.rowCount;var columnCount=otherTable.columnCount;for(columni=0;columni&lt;columnCount;columni++){this.appendColumn(otherTable.columnNames[columni],otherTable.columnTypes[columni])}for(rowi=0;rowi&lt;rowCount;rowi++){this.insertRowAtEnd(otherTable.rowNames[rowi])}for(rowi=0;rowi&lt;rowCount;rowi++){for(columni=0;columni&lt;columnCount;columni++){this.data[rowi][columni]=otherTable.data[rowi][columni]}}},serialize:function(){var root={serializationFormat:"file",serializationVersion:"1",_type:"table",name:this.name,numRows:this.rowCount,numCols:this.columnCount,_children:[]};var rows={_type:"rows",_children:[]};for(var row=0;row&lt;this.rowCount;row++){rows["_children"].push({_type:"row",id:row,name:this.rowNames[row]})}root["_children"].push(rows);var columns={_type:"columns",_children:[]};for(var column=0;column&lt;this.columnCount;column++){columns["_children"].push({_type:"column",id:column,name:this.columnNames[column],type:this.getEnumByType(this.columnTypes[column]),_text:this.serializeColumn(column+1)})}root["_children"].push(columns);return root},serializeColumn:function(column){var result=[];for(var row=1;row&lt;=this.rowCount;row++){var value=this.getCell(row,column);result.push(String(value))}return result}};gs.lua={mod:function(x,y){return x-Math.floor(x/y)*y}};gs.NOOP_FUNCTION=function(){};gs.GameSaladObject=function(){var GSObject={};GSObject.__class=GSObject;GSObject.__superclass=null;GSObject.__classname="GameSaladObject";GSObject.__classSet={GameSaladObject:true};GSObject.__tostring=function(){return this.__classname};GSObject.superclass=function(){return this.__superclass};GSObject.getClass=function(){return this.__class};GSObject.classname=function(){return this.__classname};GSObject.isAClass=function(){return this===this.__class};GSObject.subclass=function(className,properties){var subclass=Object.create(this);subclass.__superclass=this;subclass.__class=subclass;subclass.__classname=className;var tempSet={};tempSet[className]=true;subclass.__classSet=gs.set.unionSet(this.__classSet,tempSet);if(properties){for(var key in properties){subclass[key]=properties[key]}}return subclass};GSObject.create=function(){var instance=Object.create(this);instance._parent=null;instance._objectKey=null;instance._children=gs.array.provide();return instance};GSObject.createNoChildren=function(){var instance=Object.create(this);instance._parent=null;instance._objectKey=null;return instance};GSObject.provide=function(){return this.__class.create()};GSObject.init=function(){return this};GSObject.initPrime=function(){return this};GSObject.clone=function(){return this.__class.provide()};GSObject.recycleArrays=function(){if(this._children){gs.array.recycle(this._children)}};GSObject.addAccessor=function(aProperty,aGetFunction){Object.defineProperty(this,aProperty,{configurable:true,get:function(){return this[aGetFunction]()}})};GSObject.addAccessors=function(propertyList,getFunctionList){var count=propertyList.length;for(var i=0;i&lt;count;++i){var property=propertyList[i];var getFunction=getFunctionList[i];this.addAccessor(property,getFunction)}};GSObject.addMutator=function(aProperty,aSetFunction){Object.defineProperty(this,aProperty,{configurable:true,set:function(newValue){return this[aSetFunction](newValue)}})};GSObject.addMutators=function(propertyList,setFunctionList){var count=propertyList.length;for(var i=0;i&lt;count;++i){var property=propertyList[i];var setFunction=setFunctionList[i];this.addMutator(property,setFunction)}};GSObject.valueForKey=function(key){return this[key]};GSObject.setValueForKey=function(value,key){this[key]=value;this.notifyObserversOfChange(key,value)};GSObject.valueForKeypath=function(keypath){var components=keypath.split(".");return this.valueForKeypathArray(components)};GSObject.valueForKeypathArray=function(components){var node=this;var obfuscationLookupTable=gs.CompoundAttribute.obfuscationLookupTable;for(var i=0,iend=components.length;node&amp;&amp;i&lt;iend;++i){var key=components[i];key=obfuscationLookupTable[key]||key;node=node[key]}return node};GSObject.addObserver=function(observer){if(!this._observers){this._observers=gs.array.provide()}var observers=this._observers;var n=observers.length;observers.push(observer);if(n===0){this.setObservable(true)}};GSObject.notifyObserversOfChange=function(){};GSObject.hasObserver=function(observer){var observers=this._observers;var observersCount=observers.length;for(var i=0;i&lt;observersCount;++i){if(observers[i]===observer){return true}}return false};GSObject.removeObserver=function(observer){if(this._observers){var observers=this._observers;var index=observers.indexOf(observer);if(index===-1){return}if(observers.length===1){this.setObservable(false);gs.array.recycle(this._observers);this._observers=null}else{observers.splice(index,1)}}};GSObject.observeChange=function(subject,key,value){};GSObject.observeValueChange=function(subject,key,value){};GSObject.generateRandomObjectKey=function(){var key;do{key="rid"+Math.floor(Math.random()*1e6)}while(this[key]);return key};GSObject.generateUniqueObjectKey=function(){return gs.ObjectBase.generateUniqueObjectKey()};GSObject.getParent=function(){return this._parent};GSObject.setParent=function(parent){this._parent=parent};GSObject.getObjectKey=function(){return this._objectKey};GSObject.setObjectKey=function(objectKey){this._objectKey=objectKey};GSObject.setObjectForKey=function(object,key){var children=this._children;if(key&amp;&amp;this.hasOwnProperty(key)){this.removeObjectForKey(key)}if(!object){return}object._objectKey=key;object._parent=this;this[key]=object;if(children.indexOf(object)===-1){children.push(object)}};GSObject.removeObjectForKey=function(key){var removedObject=null;if(key&amp;&amp;this.hasOwnProperty(key)){removedObject=this[key];if(removedObject){var kidIndex=this._children.indexOf(removedObject);this._children.splice(kidIndex,1);delete this[key];if(removedObject&amp;&amp;removedObject._parent===this){removedObject.setParent(null)}}}return removedObject};GSObject.addAccessors(["objectKey","parent"],["getObjectKey","getParent"]);GSObject.addMutators(["objectKey","parent"],["setObjectKey","setParent"]);return GSObject}();gs.instanceOfClassType=function(object,classtype){return object.__classSet&amp;&amp;object.__classSet[classtype]};gs.isInstanceOf=function(object,sometype){var jsType=typeof object;if(jsType===sometype){return true}else if(jsType==="object"&amp;&amp;object&amp;&amp;object.__class){if(gs.instanceOfClassType(object,sometype)){return true}}return false};gs.makeEqualityPredicate=function(object){return function(testObject){return testObject==object}};gs.getTypeName=function(o){var t=gs.getTypeHelper(o);return t?t.name:null};gs.getTypeHelper=function(o){if(o===undefined||o===null){return o}if(!gs.classPrototypes){gs.classPrototypes=[];gs.classDescriptions=[]}var nodePrototype=Object.getPrototypeOf(o);var index=gs.classPrototypes.indexOf(nodePrototype);if(index!==-1){return gs.classDescriptions[index]}for(var name in gs){var declaration=gs[name];if(typeof declaration==="function"){if(nodePrototype===declaration.prototype){var description={name:name,constructor:declaration};gs.classPrototypes.push(nodePrototype);gs.classDescriptions.push(description);return description}}}return null};gs.ObjectBase=function(){};gs.ObjectBase.nextUniqueObjectKey=1;gs.ObjectBase.generateUniqueObjectKey=function(){return"uid"+this.nextUniqueObjectKey++};gs.ObjectBase.prototype={clone:function(){return this.__class.provide()}};gs.inherits(gs.ObjectBase,Object);gs.ObjectWithImmutableAttributes=function(){if(!this.attributes){this.attributes=new gs.ImmutableAttributeCollection}this.attributes._parent=this};gs.ObjectWithImmutableAttributes.prototype={init:function(){this.declareAttributes(this.attributes);return this},declareAttributes:function(attributes){},clone:function(){var other=this.__class.provide();other.attributes=this.attributes.clone();other.attributes._parent=other;return other},loadFromLite:function(node,initialState){var attributes=node["attributes"];if(attributes){this.attributes.loadFromLite(attributes,initialState)}}};gs.inherits(gs.ObjectWithImmutableAttributes,gs.ObjectBase);gs.ObjectList=function(){};gs.ObjectList.prototype={clear:function(){this.length=0},loadFromLite:function(parseFunc,node,initialState){var element;if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){element=parseFunc(node[i],initialState);this[i]=element}}else{element=parseFunc(node,initialState);this[0]=element}},makeChildrenPerformFunction:function(func,arg){for(var i=0;i&lt;this.length;i++){func.call(this[i],arg)}}};gs.inherits(gs.ObjectList,gs.ObjectBase);gs.ObjectListWithKeys=function(){};gs.ObjectListWithKeys.prototype={clear:function(){this.length=0;for(var key in this){delete this[key]}},loadFromLite:function(parseFunc,node,initialState){var element;if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){element=parseFunc(node[i],initialState);this[i]=element;element._objectKey=element._objectKey||gs.ObjectBase.generateUniqueObjectKey();this[element._objectKey]=element}}else{element=parseFunc(node,initialState);this[0]=element;element._objectKey=element._objectKey||gs.ObjectBase.generateUniqueObjectKey();this[element._objectKey]=element}},makeChildrenPerformFunction:function(func,arg){for(var i=0;i&lt;this.length;i++){func.call(this[i],arg)}}};gs.inherits(gs.ObjectListWithKeys,gs.ObjectList);gs.Timebase=function(){this.base=0;this.paused=false;if(!this.currentTimeStamp){this.currentTimeStamp={}}this.currentTimeStamp.time=0;this.currentTimeStamp.dt=0;this.currentTimeStamp.base=this.base};gs.Pool.init(gs.Timebase);gs.Timebase.prototype={init:function(){var base=gs.EngineContext.current.getSimulationTimeS();return this.initWithBase(base)},initWithBase:function(base){this.base=base;this.paused=false;this.currentTimeStamp.time=0;this.currentTimeStamp.dt=0;this.currentTimeStamp.base=this.base;return this},initWithTime:function(basetimestamp){return this.initWithBase(basetimestamp.time)},pause:function(){if(!this.paused){this.paused=true;this.pausedAtTime=gs.EngineContext.current.getSimulationTimeS()-this.base}},resume:function(){if(this.paused){this.base=gs.EngineContext.current.getSimulationTimeS()-this.pausedAtTime;this.finishTimebaseResume()}},pauseRelativeToTimestamp:function(timestamp){if(!this.paused){this.paused=true;this.pausedAtTime=timestamp.time-this.base}},resumeRelativeToTimestamp:function(timestamp){if(this.paused){this.base=timestamp.time-this.pausedAtTime;this.finishTimebaseResume()}},finishTimebaseResume:function(){this.currentTimeStamp.base=this.base;this.pausedAtTime=null;this.paused=false},nextTimestamp:function(dt){this.currentTimeStamp.time+=dt;this.currentTimeStamp.dt=dt;return this.currentTimeStamp},convertTimeStamp:function(timestamp){this.currentTimeStamp.time=Math.max(0,timestamp.time-this.base);this.currentTimeStamp.dt=timestamp.dt},getTimeStamp:function(){return this.currentTimeStamp}};gs.Network=function(){};gs.Network.prototype={ERROR_STRING_NETWORK_ERROR:"network error",errorMap:{"network error":-1},createRequest:function(method,url){var request=new XMLHttpRequest;request.open(method,url,true);request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");return request},send:function(method,url,body){var promise=new gs.Promise;var request=this.createRequest(method,url);request.onreadystatechange=function(){if(request.readyState===4){if(request.status===200){promise.resolve(request.responseText)}else{promise.reject()}}};request.onerror=function(){promise.reject()};if(method.toUpperCase()==="POST"){request.send(body)}else{request.send()}return promise},sendJSON:function(method,url,bodyJSON){var promise=new gs.Promise;var bodyString=null;if(method.toUpperCase()==="POST"){bodyString=JSON.stringify(bodyJSON);bodyString="params="+encodeURIComponent(bodyString)}this.send(method,url,bodyString).then(function onSuccess(responseText){try{var responseJSON=JSON.parse(responseText);promise.resolve(responseJSON);return}catch(exception){gs.Log.debug(exception)}promise.reject()}).otherwise(function onFailure(){promise.reject()});return promise},getJSON:function(url){return this.sendJSON("GET",url,null)},postJSON:function(url,bodyJSON){return this.sendJSON("POST",url,bodyJSON)},setLastError:function(errorString,disconnect){if(disconnect!==false){disconnect=true}var game=gs.Game.instance;if(game){var errorCode=this.errorMap[errorString]||-1;game.attributes.networking.lastError.setValue(errorCode);if(disconnect){game.attributes.networking.connected.setValue(false)}}},tableToNetworkJSON:function(tableAttribute){var tableData=tableAttribute._tableData;var tableJSON={Properties:[],Name:tableData.name,Children:[{Children:[],Name:tableData.id+"_headers",Properties:[{Name:"rowCount",Value:tableData.rowCount},{Name:"columnCount",Value:tableData.columnCount}]},{Children:[],Name:tableData.id}]};for(var column=0;column&lt;tableData.columnCount;column++){tableJSON["Children"][0]["Properties"].push({Name:["0",column+1,"name"].join("-"),Value:tableData.columnNames[column]});tableJSON["Children"][0]["Properties"].push({Name:["0",column+1,"type"].join("-"),Value:tableData.getEnumByType(tableData.columnTypes[column])})}var rowsJSON=[];for(var row=0;row&lt;tableData.rowCount;row++){var newRow=tableData.rowNames[row];if(!newRow){newRow=""}newRow=newRow+"|";for(var c=0;c&lt;tableData.columnCount;c++){var cellValue=tableData.getCell(row+1,c+1);var columnType=tableData.getCellType(row+1,c+1);if(columnType==="boolean"){newRow+=cellValue?"True":"False"}else if(columnType!="text"){newRow+=tableData.emptyValue(cellValue)?0:cellValue}else if(cellValue!=null){newRow+=cellValue.toString().replace("\\","\\\\").replace("|","\\|")}newRow+="|"}rowsJSON.push({Name:(row+1).toString(),Value:newRow})}tableJSON["Children"][1]["Properties"]=rowsJSON;return tableJSON},propertyToTable:function(objectJSON,tableAttribute){var _this=this;var objectData=objectJSON["Children"][1];var tableData=tableAttribute._tableData;if(objectData["Name"]===tableData.id){var newTable=new gs.tables.Table;newTable.id=objectData["Name"];newTable.name=objectJSON["Name"];var columnNameCheck=/\-name$/;var columnTypeCheck=/\-type$/;var expectedRowCount=0;objectJSON["Children"][0]["Properties"].forEach(function(property,idx){if(property["Name"]==="rowCount"){expectedRowCount=property["Value"];return}if(property["Name"]==="columnCount"){newTable.columnCount=property["Value"];return}if(columnNameCheck.test(property["Name"])){newTable.columnNames.push(property["Value"]);newTable.columnNamesLower.push(property["Value"].toLowerCase());return}if(columnTypeCheck.test(property["Name"])){newTable.columnTypes.push(newTable.getTypeByEnum(property["Value"]));return}});objectData["Properties"].forEach(function(rowInfo,ridx){var parsedRow=_this.parseTableRow(rowInfo["Value"]);parsedRow.forEach(function(columnData,cidx){var data=columnData;var colType=newTable.getColumnType(cidx);if(colType==="boolean"){data=!!data.match(/true/i)}if(cidx==0){newTable.insertRowAtEnd(parsedRow[0])}else{newTable.setCell(ridx+1,cidx,data)}})});tableData.copyFromOtherTable(newTable);newTable.clear()}else{throw new Exception("Expecting "+tableData.id+" but received table "+objectJSON["Children"][1]["Name"])}},parseTableRow:function(rowString){var currentColumn="";var row=[];for(var i=0;i&lt;rowString.length;i++){if(rowString[i]=="|"){row.push(currentColumn);currentColumn="";i++}else if(rowString[i]=="\\"){i++}if(rowString[i]=="|"){row.push("")}else{currentColumn+=rowString[i]}}return row}};gs.singleton(gs.Network);gs.PrototypicalDictionary=gs.GameSaladObject.subclass("PrototypicalDictionary");gs.PrototypicalDictionary.clone=function(){var other=this.__class.provide();var thisNodes=this._children;var otherNodes=other._children;for(var i=0,iend=thisNodes.length;i&lt;iend;i++){var value=thisNodes[i];var key=value._objectKey;var newValue=value.clone();newValue._objectKey=key;newValue._parent=other;other[key]=newValue;otherNodes[i]=newValue}return other};gs.PrototypicalDictionary.releaseExpressionInputs=function(){var items=this._children;for(var i=0,iend=items.length;i&lt;iend;i++){var item=items[i];if(item.releaseExpressionInputs){item.releaseExpressionInputs()}}};gs.PrototypicalObject=gs.PrototypicalDictionary.subclass("PrototypicalObject");gs.PrototypicalObject.addAccessors(["displayName"],["getDisplayName"]);gs.PrototypicalObject.addMutators(["displayName"],["setDisplayName"]);gs.PrototypicalObject.init=function(){gs.PrototypicalDictionary.init.call(this);this.setObjectForKey(gs.CompoundAttribute.provide().init(),"attributes");return this};gs.PrototypicalObject.initPrime=function(){this.attributes=null;return this};gs.PrototypicalObject.getDisplayName=function(){if(this.attributes.name){return this.attributes.name.getValue()}else{return""}};gs.PrototypicalObject.setDisplayName=function(name){};gs.PrototypicalObject.releaseExpressionInputs=function(){this.attributes.releaseExpressionInputs()};gs.PrototypicalObject.loadFromLite=function(node,initialState){var id=node["id"];var attributes=node["attributes"];if(id){this._objectKey=id}if(attributes){this.attributes.loadFromLite(attributes)}};gs.PrototypicalObject.loadFromTable=function(t,initialState){var key=t["id"];if(key){this._objectKey=key}var table=t[gs.JXON._children];if(!table){return}var itemCount=table.length;for(var i=0;i&lt;itemCount;++i){var node=table[i];var nodetype=gs.Project.nodeTypeNameMap[node[gs.JXON._type]];if(nodetype==="attributes"){if(node[gs.JXON._children]){this.attributes.loadFromTable(node[gs.JXON._children],initialState)}break}}};gs.PrototypicalImmutableObject=gs.PrototypicalDictionary.subclass("PrototypicalImmutableObject",{init:function(){gs.PrototypicalDictionary.init.call(this);this.setObjectForKey(new gs.ImmutableAttributeCollection,"attributes");return this},initPrime:function(){this.attributes=null;return this},releaseExpressionInputs:function(){this.attributes.releaseExpressionInputs()},loadFromLite:function(node,initialState){var id=node["id"];var attributes=node["attributes"];if(id){this._objectKey=id}if(attributes){this.attributes.loadFromLite(attributes,initialState)}},loadFromTable:function(t,initialState){var gs_JXON=gs.JXON;var gs_JXON__children=gs_JXON._children;var gs_Project_nodeTypeNameMap=gs.Project.nodeTypeNameMap;var key=t["id"];if(key){this._objectKey=key}var children=t[gs_JXON__children];if(children){for(var i=0,iend=children.length;i&lt;iend;i++){var child=children[i];var tag=gs_Project_nodeTypeNameMap[child[gs_JXON._type]];if(tag==="attributes"){var grandchildren=child[gs_JXON__children];if(grandchildren&amp;&amp;grandchildren.length&gt;0){this.attributes.loadFromTable(grandchildren,initialState)}break}}}}});gs.PrototypicalKeylessArray=gs.PrototypicalDictionary.subclass("PrototypicalKeylessArray");gs.PrototypicalKeylessArray.create=function(){var instance=gs.PrototypicalDictionary.create.call(this);instance.array=instance._children;return instance};gs.PrototypicalKeylessArray.init=function(entityType){gs.PrototypicalDictionary.init.call(this);this.entityType=entityType;return this};gs.PrototypicalKeylessArray.initPrime=function(){this.array=this._children;return this};gs.PrototypicalKeylessArray.length=function(){return this.array.length};gs.PrototypicalKeylessArray.clone=function(){var other=this.__class.provide();var thisNodes=this._children;var otherNodes=other._children;for(var i=0,iend=thisNodes.length;i&lt;iend;i++){var value=thisNodes[i];var key=value._objectKey;var newValue=value.clone();newValue._objectKey=key;newValue._parent=other;otherNodes[i]=newValue}return other};gs.PrototypicalKeylessArray.setObjectForKey=function(object,key){if(!object){return}object.setObjectKey(key);object.setParent(this);this.array.push(object)};gs.PrototypicalKeylessArray.addObjectAtIndex=function(object,index,key){if(this.array[index]){this.removeObjectAtIndex(index)}if(index===null||index===undefined){index=this.array.length}this.array.splice(index,0,object);key=key||this.generateUniqueObjectKey();object.setObjectKey(key);object.setParent(this)};gs.PrototypicalKeylessArray.addObjectAtEnd=function(object,key){if(this.hasOwnProperty(key)){this.removeObjectForKey(key)}object._objectKey=key;object._parent=this;this.array.push(object)};gs.PrototypicalKeylessArray.removeObjectAtIndex=function(index){var removedObject=this.array[index];this.array.splice(index,1);removedObject.setParent(null)};gs.PrototypicalKeylessArray.makeChildrenPerformFunction=function(func,arg){for(var i=0;i&lt;this.array.length;i++){func.call(this.array[i],arg)}};gs.PrototypicalKeylessArray.loadFromLite=function(node,initialState){var parseFunction;switch(this.entityType){case"condition":parseFunction=gs.Parser.parseCondition}if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){var element=parseFunction(node[i],initialState);element._objectKey=node[i].id;element._parent=this;this.array[i]=element}}else{var element=parseFunction(node,initialState);element._objectKey=node.id;element._parent=this;this.array[0]=element}};gs.PrototypicalKeylessArray.loadFromTable=function(t,initialState){var i,end;var elements=this.array;for(i=0,end=elements.length;i&lt;end;++i){elements[i].setParent(null)}elements.length=0;if(t){for(i=0,end=t.length;i&lt;end;++i){var node=t[i];var element=gs.Parser.parse(node,initialState);element._objectKey=node.id;element._parent=this;this.array.push(element)}}};gs.PrototypicalArray=gs.PrototypicalDictionary.subclass("PrototypicalArray");gs.PrototypicalArray.create=function(){var instance=gs.PrototypicalDictionary.create.call(this);instance.array=instance._children;return instance};gs.PrototypicalArray.init=function(){gs.PrototypicalDictionary.init.call(this);return this};gs.PrototypicalArray.initPrime=function(){this.array=this._children;return this};gs.PrototypicalArray.releaseExpressionInputs=function(){var items=this.array;for(var i=0,iend=items.length;i&lt;iend;i++){var item=items[i];if(item.releaseExpressionInputs){item.releaseExpressionInputs()}}};gs.PrototypicalArray.setObjectForKey=function(object,key){if(!object){return}object._objectKey=key;object._parent=this;this[key]=object};gs.PrototypicalArray.addObjectAtIndex=function(object,index,key){if(key&amp;&amp;this.hasOwnProperty(key)){this.removeObjectForKey(key)}key=key||this.generateUniqueObjectKey();var thisArray=this.array;if(index===thisArray.length){thisArray.push(object)}else if(index===null||index===undefined){thisArray.push(object)}else{thisArray.splice(index,0,object)}this.setObjectForKey(object,key)};gs.PrototypicalArray.addObjectAtEnd=function(object,key){if(this.hasOwnProperty(key)){this.removeObjectForKey(key)}object._objectKey=key;object._parent=this;this[key]=object;this.array.push(object)};gs.PrototypicalArray.removeObjectAtIndex=function(index){var removedObjectKey=this.array[index]._objectKey;this.removeObjectForKey(removedObjectKey)};gs.PrototypicalArray.removeObject=function(object){this.removeObjectForKey(object._objectKey)};gs.PrototypicalArray.indexOfObjectWithKey=function(key){var object=this[key];return this.array.indexOf(object)};gs.PrototypicalArray.makeChildrenPerformFunction=function(func,arg){for(var i=0;i&lt;this.array.length;++i){func.call(this.array[i],arg)}};gs.PrototypicalArray.loadFromLite=function(node,initialState){if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){var element=gs.Parser.parse(node[i],initialState);this.addObjectAtIndex(element,i,node[i].id)}}else{var element=gs.Parser.parse(node,initialState);this.addObjectAtIndex(element,0,node.id)}};gs.PrototypicalArray.loadFromTable=function(t,initialState){var count=this.array.length;for(var i=count-1;i&gt;=0;--i){this.removeObjectAtIndex(i)}var len=0;if(t){len=t.length}for(var i=0;i&lt;len;++i){var node=t[i];var id=node.id;var element=gs.Parser.parse(node,initialState);this.addObjectAtIndex(element,i,id)}};gs.TextConstraint=gs.GameSaladObject.subclass("TextConstraint");gs.TextConstraint.returnVec=[0,0];gs.TextConstraint.init=function(){gs.GameSaladObject.init.call(this);this.minCharacters=0;return this};gs.TextConstraint.defaultValue=function(){var retval="";while(retval.length&lt;this._minCharacters){retval+=" "}return retval};gs.TextConstraint.initWithParameters=function(minCharacters,maxCharacters){gs.GameSaladObject.init.call(this);this._minCharacters=minCharacters;this._maxCharacters=maxCharacters;return this};gs.TextConstraint.constrainValue=function(value){var validMutation=false;var newValue="";if(value!==undefined){validMutation=true;value=gs.Attribute.convertValueToString(value);var length=value.length;var minCharacters=this._minCharacters!=null?this._minCharacters:0;if(length&gt;=minCharacters){if(this._maxCharacters){length=Math.min(length,this._maxCharacters)}validMutation=true;newValue=value.substr(0,length)}}var returnVec=gs.TextConstraint.returnVec;returnVec[0]=validMutation;returnVec[1]=newValue;return returnVec};gs.TextConstraint.Default=gs.TextConstraint.provide().init();gs.NumberConstraint=gs.GameSaladObject.subclass("NumberConstraint");gs.NumberConstraint.returnVec=[0,0];gs.NumberConstraint.init=function(){gs.GameSaladObject.init.call(this);this._minValue=null;this._maxValue=null;this._step=null;this._circular=null;return this};gs.NumberConstraint.initWithParameters=function(minValue,maxValue,step,circular){gs.GameSaladObject.init.call(this);this._minValue=minValue;this._maxValue=maxValue;this._step=step;this._circular=circular;return this};gs.NumberConstraint.defaultValue=function(){return this._minValue!=null?this._minValue:0};gs.NumberConstraint.constrainValue=function(value){var validMutation=false;var newValue=null;var numberValue=Number(value);validMutation=numberValue!=null;var refined=numberValue;var minValue=this._minValue;var maxValue=this._maxValue;var step=this._step;if(this._circular&amp;&amp;minValue!==null&amp;&amp;maxValue!==null){var rangeValue=maxValue-minValue;while(refined&lt;minValue){refined+=rangeValue}while(refined&gt;maxValue){refined-=rangeValue}}if(step){refined=refined-refined%step+Math.floor(refined%step/step+.5)*step}if(minValue!==null&amp;&amp;refined&lt;minValue){refined=minValue}if(maxValue!==null&amp;&amp;refined&gt;maxValue){refined=maxValue}if(refined===Infinity){refined=0}newValue=refined;var returnVec=gs.NumberConstraint.returnVec;returnVec[0]=validMutation;returnVec[1]=newValue;return returnVec};gs.NumberConstraint.Real=gs.NumberConstraint.provide().init();gs.NumberConstraint.Integer=gs.NumberConstraint.provide().initWithParameters(null,null,1);gs.NumberConstraint.Index=gs.NumberConstraint.provide().initWithParameters(0,null,1);gs.NumberConstraint.Angle=gs.NumberConstraint.provide().initWithParameters(0,360,null,true);gs.NumberConstraint.PositiveReal=gs.NumberConstraint.provide().initWithParameters(0);gs.NumberConstraint.PositiveInteger=gs.NumberConstraint.provide().initWithParameters(0,null,1);gs.NumberConstraint.ZeroToOneInclusiveRange=gs.NumberConstraint.provide().initWithParameters(0,1);gs.NumberConstraint.Real.constrainValue=function(value){var returnVec=gs.NumberConstraint.returnVec;var valid=true;if(typeof value!=="number"){value=Number(value);valid=!isNaN(value);if(!valid){valid=true;value=1}}returnVec[0]=valid;returnVec[1]=value;return returnVec};gs.BooleanConstraint=gs.GameSaladObject.subclass("BooleanConstraint");gs.BooleanConstraint.returnVec=[0,0];gs.BooleanConstraint.defaultValue=function(){return false};gs.BooleanConstraint.constrainValue=function(value){var newValue=null;switch(value){case"true":case"1":newValue=true;break;case"false":case"0":newValue=false;break;default:newValue=Boolean(value);break}var validMutation=newValue!=null;var returnVec=gs.BooleanConstraint.returnVec;returnVec[0]=validMutation;returnVec[1]=newValue;return returnVec};gs.BooleanConstraint.Default=gs.BooleanConstraint.provide().init();gs.KeycodeConstraint=gs.TextConstraint.subclass("KeycodeConstraint");gs.KeycodeConstraint.constrainValue=function(value){var constrainedArray=gs.TextConstraint.constrainValue.call(this,value);var validMutation=constrainedArray[0];var newValue=constrainedArray[1];if(value===" "){constrainedArray[0]=true;constrainedArray[1]="space"}return constrainedArray};gs.KeycodeConstraint.Default=gs.KeycodeConstraint.provide().init();gs.Attribute=gs.PrototypicalDictionary.subclass("Attribute");gs.Attribute.addAccessors(["displayName","value","type"],["getDisplayName","getValue","getType"]);gs.Attribute.addMutators(["displayName","value"],["setDisplayName","setValue"]);gs.Attribute.create=function(){return this.createNoChildren()};gs.Attribute.init=function(){gs.PrototypicalDictionary.init.call(this);this._observed=false;this._initialValue=null;return this};gs.Attribute.initPrime=function(){this._value=null;this._type=null;this._constraint=null;this._initialValue=null;this._node=null;this._observers=null;this._observed=false;return this};gs.Attribute.clone=function(){var other=this.__class.provide();other._value=this._initialValue;other._initialValue=this._initialValue;other._type=this._type;other._constraint=this._constraint;other._isRotationAttribute=true;return other};gs.Attribute.initWithTypeAndValue=function(type,value){this.init();this.setType(type);if(value==null&amp;&amp;this._constraint){this.setValue(this._constraint.defaultValue())}else{this.setValue(value)}this._initialValue=this._value;return this};gs.Attribute.getDisplayName=function(){var displayName=this._displayName;if(!displayName){displayName=this.getObjectKey()}return displayName};gs.Attribute.setDisplayName=function(displayName){};gs.Attribute.setReserved=gs.NOOP_FUNCTION;gs.Attribute.getValue=function(){return this._value};gs.Attribute.booleanValue=function(){var value=this.getValue();return value};gs.Attribute.stringValue=function(){var v=this.getValue();return gs.Attribute.convertValueToString(v)};gs.Attribute.numberValue=function(){var v=this.getValue();if(isNaN(v)){return 0}return v};gs.Attribute.intValue=function(){return this.numberValue()|0};gs.Attribute.setValue=function(value){if(this._value!==value){var constraint=this._constraint;if(constraint){var constrained=constraint.constrainValue(value);var validMutation=constrained[0];var newValue=constrained[1];if(validMutation){this._value=newValue;this.notifyObserversOfValueChange(newValue)}}else{this._value=value;this.notifyObserversOfValueChange(value)}}};gs.Attribute.fastSetValue=function(value){if(this._value!==value){this._value=value;this.notifyObserversOfValueChange(value)}};gs.Attribute.getType=function(){if(this._type){return this._type}else{var testType=typeof this._value;switch(testType){case"number":return"real";case"string":return"text";default:return testType}}};gs.Attribute.setType=function(type){this._type=type;this.setConstraint(gs.DefaultConstraints[type])};gs.Attribute.setConstraint=function(constraint){this._constraint=constraint};gs.Attribute.getNode=function(){var node=this._node;if(!node){var node=gs.SGAttributeNode.provide();node.setValue(this.getValue());this._node=node;this._observed=true}return node};gs.Attribute.connectToSprite=function(sprite,valueKey,dirtyKey){this.sprite=sprite;this.spriteValueKey=valueKey;this.spriteDirtyKey=dirtyKey;sprite[valueKey]=this.getValue();sprite[dirtyKey]=true;this._observed=true};gs.Attribute.disconnectFromSprite=function(){this.sprite=null};gs.Attribute.notifyNodeOfValueChangeMethod=function(newValue){var node=this._node;if(node){node.setValue(newValue)}var sprite=this.sprite;if(sprite){sprite[this.spriteValueKey]=newValue;sprite[this.spriteDirtyKey]=true}};gs.Attribute.notifyObserversOfValueChange=gs.Attribute.notifyNodeOfValueChangeMethod;gs.Attribute.notifyObserversOfValueChangeMethod=function(newValue){this.notifyNodeOfValueChangeMethod(newValue);var observers=this._observers;if(observers){for(var i=0,iend=observers.length;i&lt;iend;i++){var observer=observers[i];observer.observeValueChange(this,newValue)}}};gs.Attribute.setObservable=function(observable){this._observed=observable;if(observable){this.notifyObserversOfValueChange=gs.Attribute.notifyObserversOfValueChangeMethod}else{this.notifyObserversOfValueChange=gs.Attribute.notifyNodeOfValueChangeMethod}};gs.Attribute.releaseExpressionInputs=function(){this._node=null;this._observed=false};gs.Attribute.loadFromLite=function(node,initialState){if(!this._type&amp;&amp;node["@"]){this.setType(node["@"])}var content=typeof node==="object"?node["$"]:node;this.setValue(content);if(initialState){this._initialValue=this._value}};gs.Attribute.loadFromTable=function(t,initialState){if(!this._type){var attributeType=t[gs.JXON._type];this.setType(attributeType)}var attributeContent=t[gs.JXON._text];this.setValue(attributeContent);if(initialState){this._initialValue=this._value}};gs.Attribute.restoreInitialState=function(){this._value=this._initialValue};gs.Attribute.loadFromTableStatic=function(t,initialState){var attribute=null;var attributeType=gs.JXON.tag(t);var children=gs.JXON.children(t);var expressionTag="expression";if(children&amp;&amp;children.length===1&amp;&amp;gs.JXON.tag(children[0])===expressionTag){attribute=gs.ExpressionAttribute.provide().init();attribute.loadFromTable(t,initialState)}else{var compoundAttributeClassMap=gs.Parser.compoundAttributeClassMap;var obfuscationLookupTable=gs.CompoundAttribute.obfuscationLookupTable;var compoundAttributeType=compoundAttributeClassMap[obfuscationLookupTable[attributeType]];if(compoundAttributeType){attribute=compoundAttributeType.provide().init();if(children){attribute.loadFromTable(children,initialState)}}else{attribute=gs.Attribute.provide().init();attribute.loadFromTable(t,initialState)}}return attribute};gs.Attribute.convertValueToString=function(v){if(v===undefined||v===null){return v}var s=String(v);if(typeof v==="number"){var magicDesiredDigits=6;var decimalIndex=s.indexOf(".");if(decimalIndex!==-1){if(s===v.toExponential()){if(/e-\d/.test(s)){return"0"}return s}var integerCount=decimalIndex;if(integerCount&gt;=magicDesiredDigits){return Math.floor(v).toString()}var fractionCount=s.length-decimalIndex-1;if(integerCount+fractionCount&gt;magicDesiredDigits){s=v.toPrecision(magicDesiredDigits);return Number(s).toString()}}}return s};gs.CompoundAttribute=gs.PrototypicalArray.subclass("CompoundAttribute");gs.CompoundAttribute.addAccessors(["displayName","type"],["getDisplayName","getType"]);gs.CompoundAttribute.initWithValues=function(valuesTable,allowExpressions){this.init();return this};gs.CompoundAttribute.addReservedCompoundAttribute=function(key,typeName,valuesTable,allowExpressions){var compoundAttributeClass=gs.CompoundAttribute;if(typeName){compoundAttributeClass=gs.Parser.compoundAttributeClassMap[typeName]}var compoundAttribute=compoundAttributeClass.provide();compoundAttribute.initWithValues(valuesTable,allowExpressions);this.addObjectAtEnd(compoundAttribute,key);return compoundAttribute};gs.CompoundAttribute.addReservedAttribute=function(key,initialValue,typeName,optionalConstraint){var attribute=gs.Attribute.provide().initWithTypeAndValue(typeName,initialValue);if(optionalConstraint){attribute.setConstraint(optionalConstraint)}this.addObjectAtEnd(attribute,key);return attribute};gs.CompoundAttribute.addExpressionAttribute=function(key,initialValue,typeName,optionalConstraint){var attribute=gs.ExpressionAttribute.provide().initWithTypeAndValue(typeName,initialValue);if(optionalConstraint){attribute.setConstraint(optionalConstraint)}this.addObjectAtEnd(attribute,key);return attribute};gs.CompoundAttribute.addBooleanImmutableAttribute=function(key,value){var attribute=new gs.BooleanImmutableAttribute(key,value);this[key]=attribute;this.array.push(attribute)};gs.CompoundAttribute.addIntegerImmutableAttribute=function(key,value){var attribute=new gs.IntegerImmutableAttribute(key,value);this[key]=attribute;this.array.push(attribute)};gs.CompoundAttribute.addRealImmutableAttribute=function(key,value){var attribute=new gs.RealImmutableAttribute(key,value);this[key]=attribute;this.array.push(attribute)};gs.CompoundAttribute.addStringImmutableAttribute=function(key,value){var attribute=new gs.StringImmutableAttribute(key,value);this[key]=attribute;this.array.push(attribute)};gs.CompoundAttribute.addIntegerMutableAttribute=function(key,value){var attribute=new gs.IntegerMutableAttribute(value);this.addObjectAtEnd(attribute,key)};gs.CompoundAttribute.addStringMutableAttribute=function(key,value){var attribute=new gs.StringMutableAttribute(value);this.addObjectAtEnd(attribute,key)};gs.CompoundAttribute.addPointMutableAttribute=function(key,x,y){var attribute=new gs.PointMutableAttribute;attribute.x.setValue(x);attribute.y.setValue(y);this.addObjectAtEnd(attribute,key)};gs.CompoundAttribute.getType=function(){return"attributes"};gs.CompoundAttribute.restoreInitialState=function(){var attributes=this.array;for(var i=0,iend=attributes.length;i&lt;iend;i++){attributes[i].restoreInitialState()}};gs.CompoundAttribute.obfuscationLookupTable=gs.util.createObfuscationLookup({acceleration:"acceleration",accelerometer:"accelerometer",actors:"actors",actorTag:"actorTag",actorTags:"actorTags",affectedByGravity:"affectedByGravity",alignment:"alignment",alpha:"alpha",angle:"angle",angularDrag:"angularDrag",angularVelocity:"angularVelocity",applyMaxSpeed:"applyMaxSpeed",array:"array",assignments:"assignments",aspects:"aspects",at:"at",at_index:"at_index",audio:"audio",autorotate:"autorotate",blendingMode:"blendingMode",blue:"blue",bundleName:"bundleName",button:"button",camera:"camera",collisionShape:"collisionShape",color:"color",colorChange:"colorChange",colorTarget:"colorTarget",colorTransitionTime:"colorTransitionTime",column:"column",command:"command",compound:"compound",compoundConditionKind:"compoundConditionKind",conditionType:"conditionType",continuousMovement:"continuousMovement",copies:"copies",count:"count",density:"density",destinationTableID:"destinationTableID",deviceOrientation:"deviceOrientation",deviceRotation:"deviceRotation",devices:"devices",direction:"direction",directionRelativity:"directionRelativity",directionSpace:"directionSpace",displaySize:"displaySize",dopplerShift:"dopplerShift",drag:"drag",duration:"duration",easing:"easing",emitterOffsetX:"emitterOffsetX",emitterOffsetY:"emitterOffsetY",enableAdvertisement:"enableAdvertisement",endCell:"endCell",endCellExpression:"endCellExpression",event:"event",finalValue:"finalValue",fixedRotation:"fixedRotation",font:"font",friction:"friction",functionName:"functionName",game:"game",gravity:"gravity",graphics:"graphics",green:"green",growthRate:"growthRate",haltWhenBehaviorStops:"haltWhenBehaviorStops",height:"height",horizontalAnchor:"horizontalAnchor",horizontalWrap:"horizontalWrap",image:"image",images:"images",index:"index",input1:"input1",input2:"input2",input3:"input3",input4:"input4",input5:"input5",input6:"input6",input7:"input7",input8:"input8",input9:"input9",input10:"input10",interfaceOrientation:"interfaceOrientation",interval:"interval",item:"item",key:"key",keyboardPrompt:"keyboardPrompt",keyString:"keyString",landscapeLeft:"landscapeLeft",landscapeRight:"landscapeRight",layerOrder:"layerOrder",lifetime:"lifetime",linearVelocity:"linearVelocity",location:"location",loop:"loop",loopAttribute:"loopAttribute",loopType:"loopType",maxSpeed:"maxSpeed",mode:"mode",motion:"motion",mouse:"mouse",movable:"movable",moveType:"moveType",musicName:"musicName",musicVolume:"musicVolume",name:"name",numParticles:"numParticles",numberOfInputs:"numberOfInputs",note:"note",notes:"notes",offsetAngle:"offsetAngle",offsetx:"offsetx",offsety:"offsety",operator:"operator",origin:"origin",page:"page",pair:"pair",pitch:"pitch",physics:"physics",portrait:"portrait",portraitUpsideDown:"portraitUpsideDown",position:"position",positional:"positional",positionSpace:"positionSpace",preloadArt:"preloadArt",preserveCurrentScene:"preserveCurrentScene",protocol:"protocol",prototypeKey:"prototypeKey",purchase:"purchase",purchases:"purchases",red:"red",restitution:"restitution",restoreActorImage:"restoreActorImage",returnAttribute:"returnAttribute",RHS:"RHS",rotation:"rotation",row:"row",rowNumber:"rowNumber",runToCompletion:"runToCompletion",scene:"scene",sceneKey:"sceneKey",screen:"screen",scrollable:"scrollable",services:"services",size:"size",sizeChange:"sizeChange",sizeTarget:"sizeTarget",sizeTransitionTime:"sizeTransitionTime",soundName:"soundName",soundVolume:"soundVolume",space:"space",spacing:"spacing",speed:"speed",startCell:"startCell",startCellExpression:"startCellExpression",startupTime:"startupTime",status:"status",subjectAttribute:"subjectAttribute",table:"table",tablecolumnassignment:"tablecolumnassignment",tableID:"tableID",tags:"tags",targetAttribute:"targetAttribute",text:"text",tileHeight:"tileHeight",tileWidth:"tileWidth",time:"time",timerType:"timerType",touch1:"touch1",touch10:"touch10",touch11:"touch11",touch2:"touch2",touch3:"touch3",touch4:"touch4",touch5:"touch5",touch6:"touch6",touch7:"touch7",touch8:"touch8",touch9:"touch9",touches:"touches",trackingArea:"trackingArea",useExternalBrowser:"useExternalBrowser",usePositionalSound:"usePositionalSound",URL:"URL",verticalAnchor:"verticalAnchor",verticalWrap:"verticalWrap",visible:"visible",volume:"volume",width:"width",wrap:"wrap",wrapX:"wrapX",wrapY:"wrapY",x:"x",y:"y",z:"z",flipHorizontally:"flipHorizontally",flipVertically:"flipVertically",attributes:"attributes",point:"point",rect:"rect",collision:"collision",mousePosition:"mousePosition",touch:"touch",auto:"auto-rotation",number:"number",string:"string",enumeration:"enumeration",clock:"clock",year:"year",month:"month",day:"day",boolean:"boolean"});gs.CompoundAttribute.loadFromLite=function(node,initialState){var obfuscationLookupTable=gs.CompoundAttribute.obfuscationLookupTable;for(var rawKey in node){var child=node[rawKey];var key=obfuscationLookupTable[rawKey]||rawKey;if(!key){key=child["id"]}var attribute=this[key];if(!attribute){attribute=gs.Attribute.provide().init();this.addObjectAtEnd(attribute,key)}attribute.loadFromLite(child,initialState)}};gs.CompoundAttribute.loadFromTable=function(t,initialState){var compoundAttributeClassMap=gs.Parser.compoundAttributeClassMap;var obfuscationLookupTable=gs.CompoundAttribute.obfuscationLookupTable;for(var index=0,len=t.length;index&lt;len;++index){var node=t[index];var tag=node[gs.JXON._type];var key=obfuscationLookupTable[node.id];if(!key){key=node.id;if(!node.name&amp;&amp;tag!=="compound"&amp;&amp;tag!=="array"){}}var compoundAttributeType=compoundAttributeClassMap[obfuscationLookupTable[tag]];if(!compoundAttributeType){var attribute=this[key];if(!attribute){attribute=gs.Attribute.provide().init();this.addObjectAtEnd(attribute,key)}attribute.loadFromTable(node,initialState)}else{var compoundAttr=this[key];if(typeof compoundAttr!="object"){compoundAttr=compoundAttributeType.provide().init();this.addObjectAtEnd(compoundAttr,key);if(node[gs.JXON._children]){compoundAttr.loadFromTable(node[gs.JXON._children],initialState)}else{compoundAttr.loadFromTable(node,initialState)}}else if(node[gs.JXON._children]){compoundAttr.loadFromTable(node[gs.JXON._children],initialState)}}}};gs.ColorAttribute=gs.CompoundAttribute.subclass("ColorAttribute");gs.ColorAttribute.defaultColor={red:1,green:1,blue:1,alpha:1};gs.ColorAttribute.init=function(){gs.CompoundAttribute.init.call(this);return this};gs.ColorAttribute.initWithValues=function(valuesTable){valuesTable=valuesTable||gs.ColorAttribute.defaultColor;var red=valuesTable.red;var green=valuesTable.green;var blue=valuesTable.blue;var alpha=valuesTable.alpha;this.addReservedAttribute("red",red,"real",gs.NumberConstraint.ZeroToOneInclusiveRange);this.addReservedAttribute("green",green,"real",gs.NumberConstraint.ZeroToOneInclusiveRange);this.addReservedAttribute("blue",blue,"real",gs.NumberConstraint.ZeroToOneInclusiveRange);this.addReservedAttribute("alpha",alpha,"real",gs.NumberConstraint.ZeroToOneInclusiveRange);return this};gs.ColorAttribute.getType=function(){return"color"};gs.ColorAttribute.getValue=function(){return{red:this.red._value,green:this.green._value,blue:this.blue._value,alpha:this.alpha._value}};gs.ColorAttribute.setValue=function(color){this.red.setValue(color.red);this.green.setValue(color.green);this.blue.setValue(color.blue);this.alpha.setValue(color.alpha)};gs.ColorAttribute.fastSetValue=function(color){this.red.fastSetValue(color.red);this.green.fastSetValue(color.green);this.blue.fastSetValue(color.blue);this.alpha.fastSetValue(color.alpha)};gs.ColorAttribute.setComponentValue=function(r,g,b,a){this.red.setValueForKey(r,"value");this.green.setValueForKey(g,"value");this.blue.setValueForKey(b,"value");this.alpha.setValueForKey(a,"value")};gs.ExpressionAttribute=gs.Attribute.subclass("ExpressionAttribute");gs.ExpressionAttribute.create=gs.PrototypicalDictionary.create;gs.ExpressionAttribute.init=function(){gs.Attribute.init.call(this);this._expression=null;this._hasExpression=false;return this};gs.ExpressionAttribute.initPrime=function(){gs.Attribute.initPrime.call(this);this._expression=null;this._hasExpression=false;return this};gs.ExpressionAttribute.clone=function(){var other=gs.PrototypicalDictionary.clone.call(this);other._value=this._initialValue;other._type=this._type;other._constraint=this._constraint;other._initialValue=this._initialValue;other._hasExpression=this._hasExpression;return other};gs.ExpressionAttribute.expression=function(){return this._expression};gs.ExpressionAttribute.setExpression=function(expression){this.setObjectForKey(expression,"_expression");this.setHasExpression(!!expression)};gs.ExpressionAttribute.setHasExpression=function(hasExpression){this._hasExpression=hasExpression;this.notifyObserversOfChange("hasExpression",hasExpression)};gs.ExpressionAttribute.hasExpression=function(){return this._hasExpression};gs.ExpressionAttribute.clearExpression=function(){this.removeObjectForKey("_expression");this.setHasExpression(false)};gs.ExpressionAttribute.getValue=function(){if(this._hasExpression){var expression=this._expression;if(expression.delegate!==this){expression.delegate=this;var node=this._parent;while(!node._entity){node=node._parent}this._entity=node._entity}if(expression.needsUpdate){var value=expression.evaluateForEntity(this._entity);if(this._value!==value){this._value=value;this.notifyObserversOfValueChange(value)}}}return this._value};gs.ExpressionAttribute.expressionInputsChanged=function(){if(this._observed){var value=this._expression.evaluateForEntity(this._entity);this.fastSetValue(value)}};gs.ExpressionAttribute.releaseExpressionInputs=function(){if(this._hasExpression){var expression=this._expression;expression.releaseInputs();expression.delegate=null;this._entity=null}this._node=null;this._observed=false};gs.ExpressionAttribute.loadFromLite=function(node,initialState){if(typeof node==="object"){var expression=gs.Parser.parseExpression(node["expression"]);if(expression.expressionTree.useConstant){this.setValue(expression.expressionTree.evaluateRoot())}else{this.setExpression(expression)}}else{this.setValue(node)}if(initialState){this._initialValue=this._value}};gs.ExpressionAttribute.loadFromTable=function(t,initialState){var attributeType=t[gs.JXON._type];if(attributeType!=="attribute"&amp;&amp;!this._type){this.setType(attributeType)}var attributeContent=t[gs.JXON._text];var contentType=typeof attributeContent;if(contentType==="undefined"){var expressionNode=t[gs.JXON._children][0];var expression=gs.Parser.parseExpression(expressionNode);this.setExpression(expression)}else{this.setValue(attributeContent)}if(initialState){this._initialValue=this._value}};gs.ExpressionAttribute.restoreInitialState=function(){this._value=this._initialValue;if(this._expression){this._expression.needsUpdate=true}};gs.PointAttribute=gs.CompoundAttribute.subclass("PointAttribute");gs.PointAttribute.defaultPoint={x:0,y:0};gs.PointAttribute.init=function(){gs.CompoundAttribute.init.call(this);return this};gs.PointAttribute.returnVec=[0,0];gs.PointAttribute.initWithValues=function(valuesTable,allowExpressions){valuesTable=valuesTable||gs.PointAttribute.defaultPoint;var x=valuesTable.x;var y=valuesTable.y;if(allowExpressions){this.addExpressionAttribute("x",x,"real");this.addExpressionAttribute("y",y,"real")}else{this.addReservedAttribute("x",x,"real");this.addReservedAttribute("y",y,"real")}return this};gs.PointAttribute.getType=function(){return"point"};gs.PointAttribute.getValue=function(){var returnVec=gs.PointAttribute.returnVec;returnVec[0]=this.x.getValue();returnVec[1]=this.y.getValue();return returnVec};gs.PointAttribute.setValue=function(point){this.x.setValue(point[0]);this.y.setValue(point[1])};gs.PointAttribute.fastSetValue=function(point){this.x.fastSetValue(point[0]);this.y.fastSetValue(point[1])};gs.RectAttribute=gs.CompoundAttribute.subclass("RectAttribute");gs.RectAttribute.defaultOrigin={x:0,y:0};gs.RectAttribute.defaultSize={width:1,height:1};gs.RectAttribute.init=function(){gs.CompoundAttribute.init.call(this);return this};gs.RectAttribute.initWithValues=function(valuesTable){var originTable=valuesTable||gs.RectAttribute.defaultOrigin;var sizeTable=valuesTable||gs.RectAttribute.defaultSize;this.addReservedCompoundAttribute("origin","point",originTable);this.addReservedCompoundAttribute("size","size",sizeTable);return this};gs.RectAttribute.getType=function(){return"rect"};gs.RectAttribute.getValue=function(tuple){tuple.x=this.origin.x.getValue();tuple.y=this.origin.y.getValue();tuple.width=this.size.width.getValue();tuple.height=this.size.height.getValue()};gs.RectAttribute.setValue=function(rect){this.origin.x.setValue(rect.x);this.origin.y.setValue(rect.y);this.size.width.setValue(rect.width);this.size.height.setValue(rect.height)};gs.RectAttribute.fastSetValue=function(rect){this.origin.x.fastSetValue(rect.x);this.origin.y.fastSetValue(rect.y);this.size.width.fastSetValue(rect.width);this.size.height.fastSetValue(rect.height)};gs.SizeAttribute=gs.CompoundAttribute.subclass("SizeAttribute");gs.SizeAttribute.defaultSize={width:1,height:1};gs.SizeAttribute.init=function(){gs.CompoundAttribute.init.call(this);return this};gs.SizeAttribute.initWithValues=function(valuesTable){valuesTable=valuesTable||gs.SizeAttribute;var width=valuesTable.width;var height=valuesTable.height;this.addReservedAttribute("width",width,"real",gs.NumberConstraint.PositiveReal);this.addReservedAttribute("height",height,"real",gs.NumberConstraint.PositiveReal);this.returnVec=[width,height];return this};gs.SizeAttribute.getType=function(){return"size"};gs.SizeAttribute.getValue=function(){var returnVec=this.returnVec;returnVec[0]=this.width.getValue();returnVec[1]=this.height.getValue();return returnVec};gs.SizeAttribute.setValue=function(size){this.width.setValue(size[0]);this.height.setValue(size[1])};gs.SizeAttribute.fastSetValue=function(size){this.width.fastSetValue(size[0]);this.height.fastSetValue(size[1])};gs.TableAttribute=gs.Attribute.subclass("TableAttribute",{init:function(id){gs.Attribute.init.call(this);this.setType("table");this.id=id;this._tableData=new gs.tables.Table;this.rowOffsetLookup=gs.Map.provide();this.columnOffsetLookup=gs.Map.provide();return this},getValue:function(){return this},getType:function(){return"table"},hasCell:function(row,column){var rowString=String(row);var columnString=String(column);return this._tableData.hasCell(rowString,columnString)},getCellSafe:function(row,column){var rowOffset=this.lookupRow(row);var columnOffset=this.lookupColumn(column);return this._tableData.getCellByIndex(rowOffset,columnOffset)},getRowCount:function(){return this._tableData.rowCount},getColumnCount:function(){return this._tableData.columnCount},lookupRow:function(row){var lookup=this.rowOffsetLookup;var offset=lookup[row];if(offset===undefined){offset=this._tableData.lookupRow(row);lookup[row]=offset}return offset},lookupColumn:function(column){var lookup=this.columnOffsetLookup;var offset=lookup[column];if(offset===undefined){offset=this._tableData.lookupColumn(column);lookup[column]=offset}return offset},getName:function(){return this._tableData.name},setCell:function(row,column,value){var lastValue=this._tableData.setCellByIndex(row,column,value);if(value!==lastValue){this.notifyObserversOfValueChange(this)}},setCellSafe:function(row,column,value){var rowOffset=this.lookupRow(row);var columnOffset=this.lookupColumn(column);var lastValue=this._tableData.setCellByIndex(rowOffset,columnOffset,value);if(value!==lastValue){this.notifyObserversOfValueChange(this)}},addRow:function(index){if(index===-1){this._tableData.insertRowAtEnd()}else{this._tableData.insertRow(index)}this.notifyObserversOfValueChange(this)},removeRow:function(index){if(index===-1){this._tableData.removeRowAtEnd()}else{this._tableData.removeRow(index)}this.notifyObserversOfValueChange(this)},getTableData:function(){return this._tableData},copyTable:function(tableToCopy){this._tableData.copyFromOtherTable(tableToCopy.getTableData());this.notifyObserversOfValueChange(this)},sumColumn:function(column,first,last){first=this.lookupColumn(first);last=this.lookupColumn(last);var sum=0;var cellNumber=0;switch(this._tableData.getColumnType(column).toLowerCase()){case"integer":case"real":case"index":case"angle":{for(var i=first;i&lt;=last;i++){cellNumber=Number(this.getCellSafe(i,column));sum+=cellNumber!=Number.NaN?cellNumber:0}}break}return sum},mergeRowValues:function(row,begin,end,separator){begin=this.lookupColumn(begin);end=this.lookupColumn(end);var direction=begin&gt;end?-1:1;end+=direction;var s="";var append=false;for(var i=begin;i!==end;i+=direction){if(append){s+=separator}s+=this.getCellSafe(row,i);append=true}return s},mergeColumnValues:function(column,begin,end,separator){begin=this.lookupRow(begin);end=this.lookupRow(end);var direction=begin&gt;end?-1:1;end+=direction;var s="";var append=false;for(var i=begin;i!==end;i+=direction){if(append){s+=separator}s+=this.getCellSafe(i,column);append=true}return s},searchRow:function(key,row,begin,end,predicate){key=this.ensureString(key);begin=this.lookupColumn(begin);end=this.lookupColumn(end);var direction=begin&gt;end?-1:1;end+=direction;for(var i=begin;i!==end;i+=direction){var value=this.getCellSafe(row,i);value=this.ensureString(value);if(this.matchPredicate(key,value,predicate)){return i}}return 0},searchColumn:function(key,column,begin,end,predicate){key=this.ensureString(key);begin=this.lookupRow(begin);end=this.lookupRow(end);var direction=begin&gt;end?-1:1;end+=direction;for(var i=begin;i!==end;i+=direction){var value=this.getCellSafe(i,column);value=this.ensureString(value);if(this.matchPredicate(key,value,predicate)){return i}}return 0},ensureString:function(s){if(typeof s!=="string"){return String(s)}return s},matchPredicate:function(key,value,predicate){switch(predicate){case"exact":return value===key;case"not exact":return value!==key;case"beginsWith":return gs.string.beginsWith(value,key);case"not beginsWith":return!gs.string.beginsWith(value,key);case"endsWith":return gs.string.endsWith(value,key);case"not endsWith":return!gs.string.endsWith(value,key);case"contains":return gs.string.contains(value,key);case"not contains":return!gs.string.contains(value,key)}},loadFromLite:function(node,initialState){var id=node["id"];if(id){this.id=id}this._tableData.setId(this.id)},loadFromTable:function(t){this.id=gs.JXON.id(t);this._tableData.setId(this.id)},loadTableData:function(virtualFileCache){var tableData=this._tableData;var persistenceKey=this.id;var loadedFromPersistence=gs.tables.loadFromPersistence(tableData,persistenceKey);if(!loadedFromPersistence){virtualFileCache.loadTableById(this.id).then(function(file){var data=file.getData();if(data){tableData.parseFromLite(data)}})}}});gs.PairAttribute=gs.CompoundAttribute.subclass("PairAttribute",{init:function(){gs.CompoundAttribute.init.call(this);this.addExpressionAttribute("first","");this.addExpressionAttribute("second","");return this},getType:function(){return"pair"},loadFromLite:function(node,initialState){this.addExpressionAttribute("first","");this.addExpressionAttribute("second","");this.first.loadFromLite(node["column"]);this.second.loadFromLite(node["rhsvalue"])},loadFromTable:function(t,initialState){var first=gs.Attribute.loadFromTableStatic(t[0],initialState);this.addObjectAtIndex(first,null,"first");var second=gs.Attribute.loadFromTableStatic(t[1],initialState);this.addObjectAtIndex(second,null,"second")}});gs.ArrayAttribute=gs.CompoundAttribute.subclass("ArrayAttribute",{init:function(){gs.CompoundAttribute.init.call(this);return this},getType:function(){return"array"},size:function(){return this.array.length},at:function(index){return this.array[index-1]},loadFromLite:function(node,initialState){if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){var child=node[i];var key=child.id||this.generateUniqueObjectKey();var childAttribute=new gs.PairExpressionAttribute;childAttribute.loadFromLite(child,initialState);this.addObjectAtEnd(childAttribute,key)}}else{var key=node.id||this.generateUniqueObjectKey();var childAttribute=new gs.PairExpressionAttribute;childAttribute.loadFromLite(node,initialState);this.addObjectAtEnd(childAttribute,key)}},loadFromTable:function(t,initialState){for(var i=0;i&lt;t.length;i++){var childJXON=t[i];var key=childJXON.id||this.generateUniqueObjectKey();var childAttribute=gs.Attribute.loadFromTableStatic(childJXON,initialState);this.addObjectAtEnd(childAttribute,key)}}});gs.AttributeBase=function(){};gs.AttributeBase.prototype={};gs.AttributeCollectionBase=function(){this._isConstant=false;this._objectKey=null;this._parent=null};gs.AttributeCollectionBase.ignoreAttributeKey={name:true,bundleName:true,note:true,conditionType:true};gs.AttributeCollectionBase.prototype=gs.subclass(Object,{addReservedCompoundAttribute:function(key,typeName,valuesTable,allowExpressions){this._isConstant=false;var compoundAttributeClass=gs.CompoundAttribute;if(typeName){compoundAttributeClass=gs.Parser.compoundAttributeClassMap[typeName]}var compoundAttribute=compoundAttributeClass.provide();compoundAttribute.initWithValues(valuesTable,allowExpressions);this.addAttribute(key,compoundAttribute);compoundAttribute._parent=this;return compoundAttribute},addReservedAttribute:function(key,initialValue,typeName,optionalConstraint){this._isConstant=false;var attribute=gs.Attribute.provide().initWithTypeAndValue(typeName,initialValue);if(optionalConstraint){attribute.setConstraint(optionalConstraint)}this.addAttribute(key,attribute);return attribute},addExpressionAttribute:function(key,initialValue,typeName,optionalConstraint){this._isConstant=false;var attribute=gs.ExpressionAttribute.provide().initWithTypeAndValue(typeName,initialValue);if(optionalConstraint){attribute.setConstraint(optionalConstraint)}this.addAttribute(key,attribute);attribute._parent=this;return attribute},addTableAttribute:function(key){this._isConstant=false;var attribute=gs.TableAttribute.provide().init(key);this.addAttribute(key,attribute);attribute._parent=this},addImmutableAttributeCollection:function(key){this._isConstant=false;var collection=new gs.ImmutableAttributeCollection;this.addAttribute(key,collection)},addBooleanImmutableAttribute:function(key,value){var attribute=new gs.BooleanImmutableAttribute(value);this.addAttribute(key,attribute)},addIntegerImmutableAttribute:function(key,value){var attribute=new gs.IntegerImmutableAttribute(value);this.addAttribute(key,attribute)},addRealImmutableAttribute:function(key,value){var attribute=new gs.RealImmutableAttribute(value);this.addAttribute(key,attribute)},addReferenceImmutableAttribute:function(key){var attribute=new gs.ReferenceImmutableAttribute;this.addAttribute(key,attribute)},addStringImmutableAttribute:function(key,value){var attribute=new gs.StringImmutableAttribute(value);this.addAttribute(key,attribute)},addColorImmutableAttribute:function(key,r,g,b,a){this._isConstant=false;var attribute=new gs.ColorImmutableAttribute;attribute.red.changeDefaultValue(r);attribute.green.changeDefaultValue(g);attribute.blue.changeDefaultValue(b);attribute.alpha.changeDefaultValue(a);this.addAttribute(key,attribute);attribute._parent=this},addBooleanMutableAttribute:function(key,value){this._isConstant=false;var attribute=new gs.BooleanMutableAttribute(value);this.addAttribute(key,attribute)},addIntegerMutableAttribute:function(key,value){this._isConstant=false;var attribute=new gs.IntegerMutableAttribute(value);this.addAttribute(key,attribute)},addIntegerPositiveMutableAttribute:function(key,value){this._isConstant=false;var attribute=new gs.IntegerPositiveMutableAttribute(value);this.addAttribute(key,attribute)},addRealMutableAttribute:function(key,value){this._isConstant=false;var attribute=new gs.RealMutableAttribute(value);this.addAttribute(key,attribute)},addRealAngleMutableAttribute:function(key,value){this._isConstant=false;var attribute=new gs.RealAngleMutableAttribute(value);this.addAttribute(key,attribute)},addRealPositiveMutableAttribute:function(key,value){this._isConstant=false;var attribute=new gs.RealPositiveMutableAttribute(value);this.addAttribute(key,attribute)},addRealNormalizedMutableAttribute:function(key,value){this._isConstant=false;var attribute=new gs.RealNormalizedMutableAttribute(value);this.addAttribute(key,attribute)},addRealConstrainedMutableAttribute:function(key,value,min,max){this._isConstant=false;var attribute=new gs.RealConstrainedMutableAttribute(value,min,max);this.addAttribute(key,attribute)},addStringMutableAttribute:function(key,value){this._isConstant=false;var attribute=new gs.StringMutableAttribute(value);this.addAttribute(key,attribute)},addPointMutableAttribute:function(key,x,y){this._isConstant=false;var attribute=new gs.PointMutableAttribute;attribute.x.setValue(x);attribute.y.setValue(y);this.addAttribute(key,attribute)},addSizeMutableAttribute:function(key,width,height){this._isConstant=false;var attribute=new gs.SizeMutableAttribute;attribute.width.setValue(width);attribute.height.setValue(height);this.addAttribute(key,attribute);attribute._parent=this},addColorMutableAttribute:function(key,r,g,b,a){this._isConstant=false;var attribute=new gs.ColorMutableAttribute;attribute.red.setValue(r);attribute.green.setValue(g);attribute.blue.setValue(b);attribute.alpha.setValue(a);this.addAttribute(key,attribute);attribute._parent=this},addIntegerExpressionAttribute:function(key,value){this._isConstant=false;var attribute=new gs.IntegerExpressionAttribute(value);this.addAttribute(key,attribute);attribute._parent=this},addRealExpressionAttribute:function(key,value){this._isConstant=false;var attribute=new gs.RealExpressionAttribute(value);this.addAttribute(key,attribute);attribute._parent=this},addStringExpressionAttribute:function(key,value){this._isConstant=false;var attribute=new gs.StringExpressionAttribute(value);this.addAttribute(key,attribute);attribute._parent=this},addVariantExpressionAttribute:function(key,value){this._isConstant=false;var attribute=new gs.VariantExpressionAttribute(value);this.addAttribute(key,attribute);attribute._parent=this},addPointExpressionAttribute:function(key,x,y){this._isConstant=false;var attribute=new gs.PointExpressionAttribute;attribute.x.setValue(x);attribute.y.setValue(y);this.addAttribute(key,attribute);attribute._parent=this},addAttribute:function(key,attribute){this[key]=attribute},clone:function(){if(this._isConstant){return this}var other=new gs.ImmutableAttributeCollection;other._isConstant=this._isConstant;for(var key in this){if(this.hasOwnProperty(key)){var attribute=this[key];if(attribute&amp;&amp;typeof attribute==="object"&amp;&amp;attribute!==this._parent){var otherAttribute=attribute.clone();if(attribute._parent===this){otherAttribute._parent=other}other[key]=otherAttribute}}}return other},restoreInitialState:function(){for(var key in this){if(this.hasOwnProperty(key)){var attribute=this[key];if(attribute&amp;&amp;typeof attribute==="object"&amp;&amp;attribute!==this._parent){attribute.restoreInitialState()}}}},releaseExpressionInputs:function(){for(var key in this){if(this.hasOwnProperty(key)){var attribute=this[key];if(attribute&amp;&amp;typeof attribute==="object"&amp;&amp;attribute!==this._parent){if(attribute.releaseExpressionInputs){attribute.releaseExpressionInputs()}}}}},valueForKeypathArray:function(components){var node=this;var obfuscationLookupTable=gs.CompoundAttribute.obfuscationLookupTable;for(var i=0,iend=components.length;node&amp;&amp;i&lt;iend;i++){var key=components[i];key=obfuscationLookupTable[key]||key;node=node[key]}return node},loadFromLite:function(node,initialState){for(var key in node){var attribute=this[key];if(attribute){if(typeof node[key]==="object"&amp;&amp;node[key].hasOwnProperty("$")){node[key]=node[key]["$"]}attribute.loadFromLite(node[key],initialState)}else if(!gs.AttributeCollectionBase.ignoreAttributeKey[key]){gs.Log.debug("Unrecognized attribute:",key)}}},loadFromTable:function(t,initialState){var compoundAttributeClassMap=gs.Parser.compoundAttributeClassMap;var obfuscationLookupTable=gs.CompoundAttribute.obfuscationLookupTable;var gs_JXON=gs.JXON;var gs_JXON__type=gs_JXON._type;var gs_JXON__children=gs_JXON._children;for(var i=0,iend=t.length;i&lt;iend;i++){var node=t[i];var tag=node[gs_JXON__type];var key=obfuscationLookupTable[node.id];if(!key){key=node.id}var attribute=this[key];if(!attribute){}else{var compoundAttributeType=compoundAttributeClassMap[obfuscationLookupTable[tag]];if(!compoundAttributeType){attribute.loadFromTable(node,initialState)}else{if(node[gs_JXON__children]){attribute.loadFromTable(node[gs_JXON__children],initialState)}}}}}});gs.ImmutableAttributeCollection=function(){gs.AttributeCollectionBase.call(this);this._isConstant=true};gs.ImmutableAttributeCollection.prototype=gs.subclass(gs.AttributeCollectionBase,{clone:function(){if(this._isConstant){return this}var other=new gs.ImmutableAttributeCollection;other._isConstant=this._isConstant;for(var key in this){if(this.hasOwnProperty(key)){var attribute=this[key];if(attribute&amp;&amp;typeof attribute==="object"&amp;&amp;attribute!==this._parent){var otherAttribute=attribute.clone();if(attribute._parent===this){otherAttribute._parent=other}other[key]=otherAttribute}}}return other},loadFromLite:function(node,initialState){var obfuscationLookupTable=gs.CompoundAttribute.obfuscationLookupTable;for(var rawKey in node){var child=node[rawKey];var key=obfuscationLookupTable[rawKey]||rawKey;var attribute=this[key];if(attribute){if(typeof child==="object"&amp;&amp;child.hasOwnProperty("$")){child=child["$"]}attribute.loadFromLite(child,initialState)}else if(!gs.AttributeCollectionBase.ignoreAttributeKey[rawKey]){gs.Log.debug("Unrecognized attribute:",rawKey)}}}});gs.MutableAttributeCollection=function(){gs.AttributeCollectionBase.call(this)};gs.MutableAttributeCollection.prototype=gs.subclass(gs.AttributeCollectionBase,{clone:function(){var other=new gs.MutableAttributeCollection;for(var key in this){if(this.hasOwnProperty(key)){var attribute=this[key];if(attribute&amp;&amp;typeof attribute==="object"&amp;&amp;attribute!==this._parent){var otherAttribute=attribute.clone();if(attribute._parent===this){otherAttribute._parent=other}other[key]=otherAttribute}}}return other},loadFromLite:function(node,initialState){var obfuscationLookupTable=gs.CompoundAttribute.obfuscationLookupTable;for(var rawKey in node){var child=node[rawKey];var key=obfuscationLookupTable[rawKey]||rawKey;var attribute=this[key];if(!attribute){var type=child["@"];key=rawKey;switch(type){case"boolean":this.addBooleanMutableAttribute(key,false);break;case"integer":this.addIntegerMutableAttribute(key,0);break;case"index":this.addIntegerPositiveMutableAttribute(key,0);break;case"real":this.addRealMutableAttribute(key,0);break;case"angle":this.addRealAngleMutableAttribute(key,0);break;case"table":this.addTableAttribute(key);break;default:this.addStringMutableAttribute(key,"")}attribute=this[key]}if(child!==null&amp;&amp;typeof child==="object"&amp;&amp;child.hasOwnProperty("$")&amp;&amp;type!=="table"){child=child["$"]}attribute.loadFromLite(child,initialState)}}});gs.ImmutableAttribute=function(){};gs.ImmutableAttribute.prototype={getValue:function(){return this._value},getValueForEntity:function(entity){return this._value},getValueForEntityStateless:function(entity){return this._value},loadFromLite:function(node,initialState){debugger},loadFromTable:function(jxon){},clone:function(){return this},changeDefaultValue:function(value){this._value=value},connectToSprite:function(sprite,valueKey,dirtyKey){sprite[valueKey]=this._value;sprite[dirtyKey]=true},disconnectFromSprite:function(){},hasExpression:function(){return false},addObserver:function(observer){},removeObserver:function(observer){},releaseExpressionInputs:function(){}};gs.inherits(gs.ImmutableAttribute,gs.AttributeBase);gs.BooleanImmutableAttribute=function(value){this._value=value};gs.BooleanImmutableAttribute.prototype=gs.subclass(gs.ImmutableAttribute,{getValue:function(){return this._value},loadFromLite:function(node,initialState){switch(node){case"true":case"1":this._value=true;break;case"false":case"0":this._value=false;break;default:this._value=Boolean(node);break}},loadFromTable:function(jxon){var rawValue=jxon[gs.JXON._text];switch(rawValue){case"true":case"1":this._value=true;break;case"false":case"0":this._value=false;break;default:this._value=Boolean(rawValue);break}}});gs.IntegerImmutableAttribute=function(value){this._value=value};gs.IntegerImmutableAttribute.prototype=gs.subclass(gs.ImmutableAttribute,{getValue:function(){return this._value},loadFromLite:function(node,initialState){this._value=Math.round(Number(node))},loadFromTable:function(jxon){this._value=Math.round(Number(jxon[gs.JXON._text]))}});gs.RealImmutableAttribute=function(value){this._value=value};gs.RealImmutableAttribute.prototype=gs.subclass(gs.ImmutableAttribute,{getValue:function(){return this._value},loadFromLite:function(node,initialState){this._value=Number(node)},loadFromTable:function(jxon){this._value=Number(jxon[gs.JXON._text])}});gs.ReferenceImmutableAttribute=function(){this._value=null};gs.ReferenceImmutableAttribute.prototype=gs.subclass(gs.ImmutableAttribute,{getValue:function(){return this._value},loadFromLite:function(node,initialState){var keypath=typeof node==="object"?node["$"]:node;if(keypath){this._value=gs.Reference.lookup(keypath)}else{this._value=null}},loadFromTable:function(jxon){var keypath=jxon[gs.JXON._text];if(keypath){this._value=gs.Reference.lookup(keypath)}else{this._value=null}}});gs.StringImmutableAttribute=function(value){this._value=value};gs.StringImmutableAttribute.prototype=gs.subclass(gs.ImmutableAttribute,{getValue:function(){return this._value},loadFromLite:function(node,initialState){this._value=String(node)},loadFromTable:function(jxon){this._value=String(jxon[gs.JXON._text])}});gs.ColorImmutableAttribute=function(){gs.ImmutableAttributeCollection.call(this);this.addRealImmutableAttribute("red",0);this.addRealImmutableAttribute("green",0);this.addRealImmutableAttribute("blue",0);this.addRealImmutableAttribute("alpha",0)};gs.ColorImmutableAttribute.prototype=gs.subclass(gs.ImmutableAttributeCollection,{clone:function(){return this}});gs.MutableAttribute=function(){this._observed=false;this._observer=null;this._observers=null;this.sprite=null;this.spriteValueKey=null;this.spriteDirtyKey=null};gs.MutableAttribute.prototype={constrainValue:function(value){return value},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},notifyObserversOfValueChange:function(value){if(this.sprite){this.sprite[this.spriteValueKey]=value;this.sprite[this.spriteDirtyKey]=true}var observers=this._observers;if(observers){for(var i=0;i&lt;observers.length;i++){observers[i].observeValueChange(this,value)}}else if(this._observer){this._observer.observeValueChange(this,value)}},loadFromLite:function(node,initialState){this.setValue(typeof node==="object"?node["$"]:node);if(initialState){this._initialValue=this._value}},loadFromTable:function(jxon,initialState){var content=jxon[gs.JXON._text];this.setValue(content);if(initialState){this._initialValue=this._value}},restoreInitialState:function(){this._value=this._initialValue},clone:function(){return new gs.MutableAttribute},addObserver:function(observer){this._observed=true;var observers=this._observers;if(observers){observers.push(observer)}else if(this._observer){observers=gs.array.provide();observers.push(this._observer);this._observer=null;observers.push(observer);this._observers=observers}else{this._observer=observer}},removeObserver:function(observer){var observers=this._observers;if(observers){var index=observers.indexOf(observer);if(index!==-1){observers.splice(index,1)}this._observed=this.sprite||observers.length&gt;0||this._node;if(observers.length===0){gs.array.recycle(observers);this._observers=null}}else if(observer===this._observer){this._observer=null;this._observed=this.sprite||this._node}},connectToSprite:function(sprite,valueKey,dirtyKey){this.sprite=sprite;this.spriteValueKey=valueKey;this.spriteDirtyKey=dirtyKey;sprite[valueKey]=this.getValue();sprite[dirtyKey]=true;this._observed=true},disconnectFromSprite:function(){this.sprite=null;this.spriteValueKey=null;this.spriteDirtyKey=null;this._observed=this._observer||this._observers&amp;&amp;this._observers.length&gt;0||this._node}};gs.inherits(gs.MutableAttribute,gs.AttributeBase);gs.BooleanMutableAttribute=function(value){gs.MutableAttribute.call(this);this._value=value;this._initialValue=value};gs.BooleanMutableAttribute.prototype=gs.subclass(gs.MutableAttribute,{constrainValue:function(value){switch(value){case"true":case"1":return true;case"false":case"0":return false;default:return Boolean(value)}},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},clone:function(){return new gs.BooleanMutableAttribute(this._initialValue)}});gs.IntegerMutableAttribute=function(value){gs.MutableAttribute.call(this);this._value=value;this._initialValue=value};gs.IntegerMutableAttribute.prototype=gs.subclass(gs.MutableAttribute,{constrainValue:function(value){if(typeof value==="number"){return Math.round(value)}var numberValue=Number(value);if(!isNaN(numberValue)){return Math.round(numberValue)}if(typeof value==="string"&amp;&amp;value==="true"){return 1}return 0},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},clone:function(){return new gs.IntegerMutableAttribute(this._initialValue)}});gs.IntegerPositiveMutableAttribute=function(value){gs.IntegerMutableAttribute.call(this,value)};gs.IntegerPositiveMutableAttribute.prototype=gs.subclass(gs.IntegerMutableAttribute,{constrainValue:function(value){var integerValue=gs.IntegerMutableAttribute.prototype.constrainValue.call(this,value);return integerValue&lt;0?0:integerValue},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},clone:function(){return new gs.IntegerPositiveMutableAttribute(this._initialValue)}});gs.RealMutableAttribute=function(value){gs.MutableAttribute.call(this);this._value=value;this._initialValue=value;this._node=null};gs.RealMutableAttribute.prototype=gs.subclass(gs.MutableAttribute,{constrainValue:function(value){if(typeof value==="number"){return value}var numberValue=Number(value);if(!isNaN(numberValue)){return numberValue}if(typeof value==="string"&amp;&amp;value==="true"){return 1}return 0},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},clone:function(){return new gs.RealMutableAttribute(this._initialValue)},getNode:function(){var node=this._node;if(!node){var node=gs.SGAttributeNode.provide();this._node=node;this._observed=true}node.setValue(this.getValue());return node},notifyObserversOfValueChange:function(value){var node=this._node;if(node){node.setValue(value)}gs.MutableAttribute.prototype.notifyObserversOfValueChange.call(this,value)}});gs.RealAngleMutableAttribute=function(value){gs.RealMutableAttribute.call(this,value)};gs.RealAngleMutableAttribute.prototype=gs.subclass(gs.RealMutableAttribute,{constrainValue:function(value){var realValue=gs.RealMutableAttribute.prototype.constrainValue.call(this,value);if(realValue&lt;0){realValue=realValue%360+360}return realValue%360},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},clone:function(){return new gs.RealAngleMutableAttribute(this._initialValue)}});gs.RealPositiveMutableAttribute=function(value){gs.RealMutableAttribute.call(this,value)};gs.RealPositiveMutableAttribute.prototype=gs.subclass(gs.RealMutableAttribute,{constrainValue:function(value){var realValue=gs.RealMutableAttribute.prototype.constrainValue.call(this,value);return realValue&lt;0?0:realValue},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},clone:function(){return new gs.RealPositiveMutableAttribute(this._initialValue)}});gs.RealNormalizedMutableAttribute=function(value){gs.RealMutableAttribute.call(this,value)};gs.RealNormalizedMutableAttribute.prototype=gs.subclass(gs.RealMutableAttribute,{constrainValue:function(value){var realValue=gs.RealMutableAttribute.prototype.constrainValue.call(this,value);return realValue&lt;0?0:realValue&gt;1?1:realValue},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},clone:function(){return new gs.RealNormalizedMutableAttribute(this._initialValue)}});gs.RealConstrainedMutableAttribute=function(value,min,max){gs.RealMutableAttribute.call(this,value);this.min=min;this.max=max};gs.RealConstrainedMutableAttribute.prototype=gs.subclass(gs.RealMutableAttribute,{constrainValue:function(value){var realValue=gs.RealMutableAttribute.prototype.constrainValue.call(this,value);return realValue&gt;this.max?this.max:realValue&lt;this.min?this.min:realValue},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},clone:function(){return new gs.RealConstrainedMutableAttribute(this._initialValue,this.min,this.max)}});gs.StringMutableAttribute=function(value){gs.MutableAttribute.call(this);this._value=value;this._initialValue=value};gs.StringMutableAttribute.prototype=gs.subclass(gs.MutableAttribute,{constrainValue:function(value){return gs.Attribute.convertValueToString(value)},getValue:function(){return this._value},setValue:function(value){if(this._value!==value){value=this.constrainValue(value);this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},fastSetValue:function(value){if(this._value!==value){this._value=value;if(this._observed){this.notifyObserversOfValueChange(value)}}},clone:function(){return new gs.StringMutableAttribute(this._initialValue)}});gs.PointMutableAttribute=function(){gs.ImmutableAttributeCollection.call(this);this.addRealMutableAttribute("x",0);this.addRealMutableAttribute("y",0)};gs.PointMutableAttribute.prototype=gs.subclass(gs.ImmutableAttributeCollection,{clone:function(){var other=new gs.PointMutableAttribute;other._objectKey=this._objectKey;other._isConstant=this._isConstant;other.addAttribute("x",this.x.clone());other.addAttribute("y",this.y.clone());return other}});gs.SizeMutableAttribute=function(){gs.ImmutableAttributeCollection.call(this);this.addRealMutableAttribute("width",0);this.addRealMutableAttribute("height",0)};gs.SizeMutableAttribute.prototype=gs.subclass(gs.ImmutableAttributeCollection,{clone:function(){var other=new gs.SizeMutableAttribute;other._objectKey=this._objectKey;other._isConstant=this._isConstant;other.addAttribute("width",this.width.clone());other.addAttribute("height",this.height.clone());return other}});gs.ColorMutableAttribute=function(){gs.ImmutableAttributeCollection.call(this);this.addRealNormalizedMutableAttribute("red",0);this.addRealNormalizedMutableAttribute("green",0);this.addRealNormalizedMutableAttribute("blue",0);this.addRealNormalizedMutableAttribute("alpha",0)};gs.ColorMutableAttribute.prototype=gs.subclass(gs.ImmutableAttributeCollection,{clone:function(){var other=new gs.ColorMutableAttribute;other._objectKey=this._objectKey;other._isConstant=this._isConstant;other.addAttribute("red",this.red.clone());other.addAttribute("green",this.green.clone());other.addAttribute("blue",this.blue.clone());other.addAttribute("alpha",this.alpha.clone());return other}});gs.ExpressionAttributeBase=function(){gs.MutableAttribute.call(this);this._parent=null;this._entity=null;this.expression=null};gs.ExpressionAttributeBase.prototype=gs.subclass(gs.MutableAttribute,{setValue:function(value){this._value=value},setExpression:function(expression){this.expression=expression;expression._parent=this;expression.delegate=this},getValue:function(){var expression=this.expression;if(expression&amp;&amp;expression.needsUpdate){this.update()}return this._value},getValueForEntity:function(entity){var expression=this.expression;if(expression&amp;&amp;expression.needsUpdate){this.update(entity)}return this._value},getValueForEntityStateless:function(entity){var expression=this.expression;if(expression){return expression.evaluateForEntityStateless(entity)}return this._value},update:function(entity){if(!this._entity||this._entity!==entity){if(entity){this._entity=entity}else{var node=this._parent;while(!node._entity){node=node._parent}this._entity=node._entity}}var value=this.expression.evaluateForEntity(this._entity);if(this._value!==value){this._value=value;this.notifyObserversOfValueChange(value)}},loadFromLite:function(node,initialState){if(typeof node==="object"){if(node["expression"]){var expression=gs.Parser.parseExpression(node["expression"]);if(expression.expressionTree.useConstant){this._value=expression.expressionTree.evaluateRoot()}else{this.setExpression(expression)}}else if(node["$"]!==undefined){this._value=node["$"]}}else{this._value=node}},loadFromTable:function(jxon){var content=jxon[gs.JXON._text];if(typeof content==="undefined"){var expressionJXON=jxon[gs.JXON._children][0];var expression=gs.Parser.parseExpression(expressionJXON);if(expression.expressionTree.useConstant){this._value=expression.expressionTree.evaluateRoot()}else{this.setExpression(expression)}}else{this._value=Number(content)}},expressionInputsChanged:function(){if(this._observed){var value=this.expression.evaluateForEntity(this._entity);if(this._value!==value){this._value=value;this.notifyObserversOfValueChange(value)}}},releaseExpressionInputs:function(){var expression=this.expression;if(expression){expression.releaseInputs()}},hasExpression:function(){return this.expression!==null},clone:function(){if(!this.expression){return new gs.RealImmutableAttribute(this._value)}else{var other=new gs.RealExpressionAttribute(this._value);if(this.expression){other.setExpression(this.expression.clone())}return other}}});gs.IntegerExpressionAttribute=function(value){gs.ExpressionAttributeBase.call(this);this._value=value};gs.IntegerExpressionAttribute.prototype=gs.subclass(gs.ExpressionAttributeBase,{setValue:function(value){this._value=value},getValue:function(){var expression=this.expression;if(expression&amp;&amp;expression.needsUpdate){this.update()}return this._value},getValueForEntity:function(entity){var expression=this.expression;if(expression&amp;&amp;expression.needsUpdate){this.update(entity)}return this._value},getValueForEntityStateless:function(entity){var expression=this.expression;if(expression){return expression.evaluateForEntityStateless(entity)}return this._value},loadFromLite:function(node,initialState){if(typeof node==="object"){var expression=gs.Parser.parseExpression(node["expression"]);if(expression.expressionTree.useConstant){this._value=Math.round(Number(expression.expressionTree.evaluateRoot()))}else{this.setExpression(expression)}}else{this._value=Math.round(Number(node))}},loadFromTable:function(jxon){var content=jxon[gs.JXON._text];if(typeof content==="undefined"){var expressionJXON=jxon[gs.JXON._children][0];var expression=gs.Parser.parseExpression(expressionJXON);if(expression.expressionTree.useConstant){this._value=expression.expressionTree.evaluateRoot()}else{this.setExpression(expression)}}else{this._value=Math.round(Number(content))}},clone:function(){if(!this.expression){return new gs.IntegerImmutableAttribute(this._value)}else{var other=new gs.IntegerExpressionAttribute(this._value);other.setExpression(this.expression.clone());return other}}});gs.RealExpressionAttribute=function(value){gs.ExpressionAttributeBase.call(this);this._value=value};gs.RealExpressionAttribute.prototype=gs.subclass(gs.ExpressionAttributeBase,{setValue:function(value){this._value=value},getValue:function(){var expression=this.expression;if(expression&amp;&amp;expression.needsUpdate){this.update()}return this._value},getValueForEntity:function(entity){var expression=this.expression;if(expression&amp;&amp;expression.needsUpdate){this.update(entity)}return this._value},getValueForEntityStateless:function(entity){var expression=this.expression;if(expression){return expression.evaluateForEntityStateless(entity)}return this._value},loadFromLite:function(node,initialState){if(typeof node==="object"){var expression=gs.Parser.parseExpression(node["expression"]);if(expression.expressionTree.useConstant){this._value=Number(expression.expressionTree.evaluateRoot())}else{this.setExpression(expression)}}else{this._value=Number(node)}},loadFromTable:function(jxon){var content=jxon[gs.JXON._text];if(typeof content==="undefined"){var expressionJXON=jxon[gs.JXON._children][0];var expression=gs.Parser.parseExpression(expressionJXON);if(expression.expressionTree.useConstant){this._value=expression.expressionTree.evaluateRoot()}else{this.setExpression(expression)}}else{this._value=Number(content)}},clone:function(){if(!this.expression){return new gs.RealImmutableAttribute(this._value)}else{var other=new gs.RealExpressionAttribute(this._value);other.setExpression(this.expression.clone());return other}}});gs.StringExpressionAttribute=function(value){gs.ExpressionAttributeBase.call(this);this._value=value};gs.StringExpressionAttribute.prototype=gs.subclass(gs.ExpressionAttributeBase,{setValue:function(value){this._value=value},getValue:function(){var expression=this.expression;if(expression&amp;&amp;expression.needsUpdate){this.update()}return this._value},getValueForEntity:function(entity){var expression=this.expression;if(expression&amp;&amp;expression.needsUpdate){this.update(entity)}return this._value},getValueForEntityStateless:function(entity){var expression=this.expression;if(expression){return expression.evaluateForEntityStateless(entity)}return this._value},loadFromLite:function(node,initialState){if(typeof node==="object"){if(node["expression"]){var expression=gs.Parser.parseExpression(node["expression"]);if(expression.expressionTree.useConstant){this._value=String(expression.expressionTree.evaluateRoot())}else{this.setExpression(expression)}}else{this.value=""}}else{this._value=String(node)}},loadFromTable:function(jxon){var content=jxon[gs.JXON._text];if(typeof content==="undefined"){var expressionJXON=jxon[gs.JXON._children][0];var expression=gs.Parser.parseExpression(expressionJXON);if(expression.expressionTree.useConstant){this._value=expression.expressionTree.evaluateRoot()}else{this.setExpression(expression)}}else{this._value=String(content)}},clone:function(){if(!this.expression){return new gs.StringImmutableAttribute(this._value)}else{var other=new gs.StringExpressionAttribute(this._value);other.setExpression(this.expression.clone());return other}}});gs.VariantExpressionAttribute=function(value){gs.ExpressionAttributeBase.call(this);this._value=value};gs.VariantExpressionAttribute.prototype=gs.subclass(gs.ExpressionAttributeBase,{});gs.PointExpressionAttribute=function(){gs.ImmutableAttributeCollection.call(this);this.addRealExpressionAttribute("x",0);this.addRealExpressionAttribute("y",0)};gs.PointExpressionAttribute.prototype=gs.subclass(gs.ImmutableAttributeCollection,{clone:function(){var other=new gs.PointExpressionAttribute;other._objectKey=this._objectKey;other._isConstant=this._isConstant;other.addAttribute("x",this.x.clone());other.addAttribute("y",this.y.clone());other.x._parent=other;other.y._parent=other;return other}});gs.PairExpressionAttribute=function(){gs.ImmutableAttributeCollection.call(this);this.addVariantExpressionAttribute("first","");this.addVariantExpressionAttribute("second","")};gs.PairExpressionAttribute.prototype=gs.subclass(gs.ImmutableAttributeCollection,{clone:function(){var other=new gs.PairExpressionAttribute;other._objectKey=this._objectKey;other._isConstant=this._isConstant;other.addAttribute("first",this.first.clone());other.addAttribute("second",this.second.clone());other.first._parent=other;other.second._parent=other;return other},loadFromLite:function(node,initialState){delete node["id;"];var keys=Object.keys(node);this.first.loadFromLite(node[keys[0]]);this.second.loadFromLite(node[keys[1]]);gs.array.recycle(keys)}});gs.Aspect=gs.PrototypicalImmutableObject.subclass("Aspect");gs.Aspect.actor=function(){var parentObject=this._parent._parent;return parentObject};gs.Aspect.start=function(actor,timestamp){};gs.Aspect.stop=function(actor,timestamp){};gs.Aspect.evaluate=function(actor,timestamp){};gs.Aspect.restoreInitialState=function(){this.attributes.restoreInitialState()};gs.GraphicsAspect=gs.Aspect.subclass("GraphicsAspect",{start:function(actor,timestamp){actor.aspects.graphics.attributes.visible.addObserver(this)},observeValueChange:function(attribute,value){var actorSpace=this.actor().getSpace();if(actorSpace){actorSpace.visible=value}}});gs.GraphicsAspect.init=function(){gs.Aspect.init.call(this);this.attributes.addBooleanMutableAttribute("visible",false);this.attributes.addIntegerMutableAttribute("blendingMode",0);this.attributes.addIntegerMutableAttribute("horizontalWrap",0);this.attributes.addIntegerMutableAttribute("verticalWrap",0);this.attributes.addIntegerMutableAttribute("horizontalAnchor",0);this.attributes.addIntegerMutableAttribute("verticalAnchor",0);this.attributes.addBooleanMutableAttribute("flipHorizontally",false);this.attributes.addBooleanMutableAttribute("flipVertically",false);this.attributes.addIntegerMutableAttribute("tileWidth",0);this.attributes.addIntegerMutableAttribute("tileHeight",0);return this};gs.MotionAspect=gs.Aspect.subclass("MotionAspect");gs.MotionAspect.init=function(){gs.Aspect.init.call(this);this.attributes.addPointMutableAttribute("linearVelocity",0,0);this.attributes.addRealMutableAttribute("angularVelocity",0);this.attributes.addRealMutableAttribute("maxSpeed",0);this.attributes.addBooleanMutableAttribute("applyMaxSpeed",false);this.attributes.addReservedCompoundAttribute("centerOfMass","point",{x:0,y:0});this.attributes.addBooleanMutableAttribute("pin",false);return this};gs.MotionAspect.start=function(actor,timestamp){var scene=actor.scene;var physicsAttrs=actor.aspects.physics.attributes;var movable=physicsAttrs.movable.getValue();var isBullet=physicsAttrs.betterColisions.getValue();var canSleep=physicsAttrs.canSleep.getValue();var positionX=actor.attributes.position.x.getValue();var positionY=actor.attributes.position.y.getValue();var rotation=actor.attributes.rotation.getValue();var angularDrag=physicsAttrs.angularDrag.getValue();var bodyDef=gs.physicsLib.GetBodyDef();bodyDef.setPosition(positionX,positionY);bodyDef.setAngle(rotation*gsMath.DEG2RAD);bodyDef.setFixedRotation(physicsAttrs.fixedRotation.getValue());bodyDef.setIsBullet(isBullet);bodyDef.setCanSleep(canSleep);if(movable){bodyDef.setType(gs.physicsLib.DYNAMIC_BODY)}else{bodyDef.setType(gs.physicsLib.STATIC_BODY)}var collisionController=scene._collisionController;this.actorID=collisionController.addCollidableActor(actor);this.updateHalfDiagonalFunction=gs.NOOP_FUNCTION;this.calculatedVelocity=gs.array.provide();this.calculatedVelocity[0]=1;this.calculatedVelocity[1]=0;var world=scene._world;var body=this._body;if(!body){body=world.createBody(bodyDef);this._body=body;if(!body){this.evaluate=gs.NOOP_FUNCTION;return}body.setActorID(this.actorID);var game=actor.game();body.addCollisionCategory(game.collisionCategoryManager.categoryIndexForObject(actor._prototypeID));var tags=actor.tags();var tagCount=tags.length;for(var i=0;i&lt;tagCount;++i){body.addCollisionCategory(game.collisionCategoryManager.categoryIndexForObject(tags[i]))}}var centerOfMassAttr=this.attributes.centerOfMass;body.setCenterOfMass(centerOfMassAttr.x.getValue(),centerOfMassAttr.y.getValue());body.pin(world,this.attributes.pin.getValue());this.actor=actor;this._updatingself=false;this.wasAwake=true;actor.attributes.position.x.addObserver(this);actor.attributes.position.y.addObserver(this);actor.attributes.rotation.addObserver(this);this._bodyPosition=gs.array.provide();this._bodyPosition[0]=0;this._bodyPosition[1]=0;var bodyPosition=body.getPosition(this._bodyPosition);this.currentPosition=gs.array.provide();this.currentPosition[0]=bodyPosition[0];this.currentPosition[1]=bodyPosition[1];this.currentRotation=body.angle();this.lastRotation=this.currentRotation;this.drag=actor.aspects.physics.attributes.drag.getValue();body.setAngularDamping(angularDrag);if(!movable){this.evaluate=gs.NOOP_FUNCTION;return}this.sceneWidth=scene.attributes.size.width.getValue();this.sceneHeight=scene.attributes.size.height.getValue();var scene=actor.scene;if(scene.wrappingEnabled()){this.updateHalfDiagonal();this.updateHalfDiagonalFunction=this.updateHalfDiagonal;this.maxDimension=0;this.wrapAxis=gs.Vector2.X_COMPONENT}this.sceneWrapX=scene.attributes.wrapX.getValue();if(this.sceneWrapX){this.checkWrappingXMethod=this.checkStartWrappingBodyX;this.destroyXFunction=this.returnFalseFunction;this.checkWrapPositionX(actor,body);this.checkWrappingXMethod(actor,body)}else{this.checkWrappingXMethod=this.returnFalseFunction;this.destroyXFunction=this.checkDestroyX}this.sceneWrapY=scene.attributes.wrapY.getValue();if(this.sceneWrapY){this.checkWrappingYMethod=this.checkStartWrappingBodyY;this.destroyYFunction=this.returnFalseFunction;this.checkWrapPositionY(actor,body);this.checkWrappingYMethod(actor,body)}else{this.checkWrappingYMethod=this.returnFalseFunction;this.destroyYFunction=this.checkDestroyY}actor.attributes.position.x.fastSetValue(this.currentPosition[0]);actor.attributes.position.y.fastSetValue(this.currentPosition[1]);if(this.destroyXFunction(actor)||this.destroyYFunction(actor)){return}body.setLinearVelocity(this.attributes.linearVelocity.x.getValue(),this.attributes.linearVelocity.y.getValue());body.setAngularVelocity(this.attributes.angularVelocity.getValue()*gsMath.DEG2RAD);this.attributes.linearVelocity.x.addObserver(this);this.attributes.linearVelocity.y.addObserver(this);this.attributes.angularVelocity.addObserver(this);this.attributes.centerOfMass.x.addObserver(this);this.attributes.centerOfMass.y.addObserver(this);this.attributes.pin.addObserver(this);this.attributes.maxSpeed.addObserver(this);physicsAttrs.drag.addObserver(this);physicsAttrs.angularDrag.addObserver(this);this.currentStackedVelocityBehavior=0;if(this.attributes.applyMaxSpeed.getValue()){this.limitMaxSpeedFunction=this.capVelocity}else{this.limitMaxSpeedFunction=gs.NOOP_FUNCTION}this.applyCalculatedVelocityFunction=gs.NOOP_FUNCTION};gs.MotionAspect.stop=function(actor,timestamp){var physicsAttrs=actor.aspects.physics.attributes;var scene=actor.scene;var world=scene._world;var collisionController=scene._collisionController;if(this._body){world.destroyBody(this._body);this._body=null}collisionController.removeCollidableActorForIndex(this.actorID);this.actorID=null;this._updatingself=null;actor.attributes.position.x.removeObserver(this);actor.attributes.position.y.removeObserver(this);actor.attributes.rotation.removeObserver(this);this.attributes.linearVelocity.x.removeObserver(this);this.attributes.linearVelocity.y.removeObserver(this);this.attributes.angularVelocity.removeObserver(this);this.attributes.maxSpeed.removeObserver(this);physicsAttrs.drag.removeObserver(this);physicsAttrs.angularDrag.removeObserver(this);actor.attributes.position.x.restoreInitialState();actor.attributes.position.y.restoreInitialState();actor.attributes.rotation.restoreInitialState();this.attributes.linearVelocity.x.restoreInitialState();this.attributes.linearVelocity.y.restoreInitialState();this.attributes.angularVelocity.restoreInitialState();this.attributes.maxSpeed.restoreInitialState();this.evaluate=gs.MotionAspect.evaluate;gs.array.recycle(this.calculatedVelocity);gs.array.recycle(this._bodyPosition);gs.array.recycle(this.currentPosition);this.actor=null;this.halfActorDiagonal=null;this.sceneWidth=null;this.sceneHeight=null;this.maxDimension=null;this.wrapAxis=null;this.checkWrappingXMethod=null;this.destroyXFunction=null;this.checkWrappingYMethod=null;this.destroyYFunction=null;this._bodyPosition=null;this.currentPosition=null;this.currentRotation=null;this.lastRotation=null};gs.MotionAspect.updateHalfDiagonal=function(){var sizeAttr=this.actor.attributes.size;var actorWidth=sizeAttr.width._value;var actorHeight=sizeAttr.height._value;var actorDiagonal=Math.sqrt(actorWidth*actorWidth+actorHeight*actorHeight);this.halfActorDiagonal=Math.min(actorDiagonal*.5,gs.physicsLib.SIMULATION_BORDER)};gs.MotionAspect.observeValueChange=function(attribute,value){if(this._updatingself||!this._body){return}this._updatingself=true;this._body.setAwake(true);this.wasAwake=true;var attributes=this.actor.attributes;var actorPosition=attributes.position;var actorRotation=attributes.rotation;var currentPosition=this.currentPosition;if(attribute===actorPosition.x||attribute==actorPosition.y||attribute==actorRotation){currentPosition[0]=actorPosition.x._value;currentPosition[1]=actorPosition.y._value;this.currentRotation=actorRotation._value*gsMath.DEG2RAD;this.lastRotation=this.currentRotation;this._body.setPositionAndAngle(currentPosition[0],currentPosition[1],this.currentRotation);this._updatingself=false;return}var linearVelocityAttr=this.attributes.linearVelocity;if(attribute===linearVelocityAttr.x||attribute===linearVelocityAttr.y){this._body.setLinearVelocity(linearVelocityAttr.x._value,linearVelocityAttr.y._value);this._updatingself=false;return}if(attribute===this.attributes.angularVelocity){this._body.setAngularVelocity(value*gsMath.DEG2RAD);this._updatingself=false;return}var centerOfMassAttr=this.attributes.centerOfMass;if(attribute==centerOfMassAttr.x||attribute==centerOfMassAttr.y){this._body.setCenterOfMass(centerOfMassAttr.x.getValue(),centerOfMassAttr.y.getValue());this._updatingself=false;return}if(attribute==this.attributes.pin){var scene=this.actor.scene;var world=scene.world;this._body.pin(world,this.attributes.pin.getValue());this._updatingself=false;return}var physicsAttrs=this.actor.aspects.physics.attributes;if(attribute===physicsAttrs.angularDrag){this._body.setAngularDamping(value)}if(attribute===physicsAttrs.drag){this.drag=value}this._updatingself=false};gs.MotionAspect.evaluate=function(actor,timestamp){this._updatingself=true;var isAwake=this._body.isAwake();if(isAwake||this.wasAwake){gs.Game.profiler.entityCounter.awake.increment();this.wasAwake=isAwake;this.evaluateBody(actor)}if(this.drag&gt;0){this.evaluateDrag()}this._updatingself=false};gs.MotionAspect.evaluateBody=function(actor){var body=this._body;var attributes=this.attributes;var actorAttributes=actor.attributes;this.applyCalculatedVelocityFunction();this.limitMaxSpeedFunction();this.currentRotation=body.angle();if(this.currentRotation!==this.lastRotation){actorAttributes.rotation.fastSetValue(this.currentRotation*gsMath.RAD2DEG);this.lastRotation=this.currentRotation}var newLinearVelocity=body.getLinearVelocity(this.calculatedVelocity);var linearVelocityAttribute=attributes.linearVelocity;linearVelocityAttribute.x.fastSetValue(newLinearVelocity[0]);linearVelocityAttribute.y.fastSetValue(newLinearVelocity[1]);var newAngularVelocity=body.angularVelocity();var angularVelocityAttribute=attributes.angularVelocity;angularVelocityAttribute.fastSetValue(newAngularVelocity*gsMath.DEG2RAD);var newCenterOfMass=body.centerOfMass();var centerOfMassAttribute=attributes.centerOfMass;centerOfMassAttribute.x.fastSetValue(newCenterOfMass[0]);centerOfMassAttribute.y.fastSetValue(newCenterOfMass[0]);var currentPosition=this.currentPosition;var newPosition=body.getPosition(this._bodyPosition);if(currentPosition[0]!==newPosition[0]||currentPosition[1]!==newPosition[1]){currentPosition[0]=newPosition[0];currentPosition[1]=newPosition[1];actorAttributes.position.x.fastSetValue(currentPosition[0]);actorAttributes.position.y.fastSetValue(currentPosition[1]);if(this.sceneWrapX){this.checkWrappingXMethod(actor,body)}else{this.destroyXFunction(actor)}if(this.sceneWrapY){this.checkWrappingYMethod(actor,body)}else{this.destroyYFunction(actor)}}var targetRotation=actor._targetRotation;if(targetRotation){actor._targetRotation=null;body.setPositionAndAngle(currentPosition[0],currentPosition[0],targetRotation*gsMath.RAD2DEG)}};gs.MotionAspect.evaluateDrag=function(){var velocityX=this.attributes.linearVelocity.x.getValue();var velocityY=this.attributes.linearVelocity.y.getValue();if(Math.abs(velocityX)&gt;0||Math.abs(velocityY)&gt;0){var body=this._body;var length=Math.sqrt(velocityX*velocityX+velocityY*velocityY);var force=gs.g_tempVec2d;var mass=body.getMass();var scalar=mass*-this.drag;force[0]=velocityX/length*scalar;force[1]=velocityY/length*scalar;var center=this._body.getWorldCenter();body.applyForce(force,center);this.wasAwake=true}};gs.MotionAspect.capVelocity=function(){var velocity=this._body.getLinearVelocity(this.calculatedVelocity);var velocitySquared=velocity[0]*velocity[0]+velocity[1]*velocity[1];var maxSpeed=this.attributes.maxSpeed._value;var maxSpeedSquared=maxSpeed*maxSpeed;if(velocitySquared&gt;=maxSpeedSquared){var length=Math.sqrt(velocity[0]*velocity[0]+velocity[1]*velocity[1]);if(length&gt;2){velocity[0]=velocity[0]/length;velocity[1]=velocity[1]/length}else{velocity[0]=0;velocity[0]=0}velocity[0]=velocity[0]*maxSpeed;velocity[1]=velocity[1]*maxSpeed;this._body.setLinearVelocity(velocity[0],velocity[1])}};gs.MotionAspect.checkStartWrappingBodyX=function(actor,body){var halfActorDiagonal=this.halfActorDiagonal;var currentX=this.currentPosition[0];if(currentX&lt;halfActorDiagonal||currentX&gt;=this.sceneWidth-halfActorDiagonal){this.checkWrappingXMethod=this.checkFinishWrappingBodyX;actor.game().eventCenter.postEvent("startedWrap",actor,gs.Vector2.X_COMPONENT,this.sceneWidth)}};gs.MotionAspect.checkStartWrappingBodyY=function(actor,body){var halfActorDiagonal=this.halfActorDiagonal;var currentY=this.currentPosition[1];if(currentY&lt;halfActorDiagonal||currentY&gt;=this.sceneHeight-halfActorDiagonal){this.checkWrappingYMethod=this.checkFinishWrappingBodyY;actor.game().eventCenter.postEvent("startedWrap",actor,gs.Vector2.Y_COMPONENT,this.sceneHeight)}};gs.MotionAspect.checkFinishWrappingBodyX=function(actor,body){this.checkWrapPositionX(actor,body);if(this.currentPosition[0]&gt;this.halfActorDiagonal&amp;&amp;this.currentPosition[0]&lt;this.sceneWidth-this.halfActorDiagonal){actor.game().eventCenter.postEvent("finishedWrap",actor,gs.Vector2.X_COMPONENT);this.checkWrappingXMethod=this.checkStartWrappingBodyX}};gs.MotionAspect.checkFinishWrappingBodyY=function(actor,body){this.checkWrapPositionY(actor,body);if(this.currentPosition[1]&gt;this.halfActorDiagonal&amp;&amp;this.currentPosition[1]&lt;this.sceneHeight-this.halfActorDiagonal){actor.game().eventCenter.postEvent("finishedWrap",actor,gs.Vector2.Y_COMPONENT);this.checkWrappingYMethod=this.checkStartWrappingBodyY}};gs.MotionAspect.checkWrapPositionX=function(actor,body){if(this.currentPosition[0]&lt;0||this.currentPosition[0]&gt;this.sceneWidth){while(this.currentPosition[0]&lt;0){this.currentPosition[0]+=this.sceneWidth}while(this.currentPosition[0]&gt;this.sceneWidth){this.currentPosition[0]-=this.sceneWidth}actor.attributes.position.x.setValue(this.currentPosition[0]);body.setPositionAndAngle(this.currentPosition[0],this.currentPosition[1],this.currentRotation);actor.game().eventCenter.postEvent("wrap",null,actor,gs.Vector2.X_COMPONENT,this.sceneWidth,0)}};gs.MotionAspect.checkWrapPositionY=function(actor,body){if(this.currentPosition[1]&lt;0||this.currentPosition[1]&gt;this.sceneHeight){while(this.currentPosition[1]&lt;0){this.currentPosition[1]+=this.sceneHeight}while(this.currentPosition[1]&gt;this.sceneHeight){this.currentPosition[1]-=this.sceneHeight}actor.attributes.position.y.setValue(this.currentPosition[1]);body.setPositionAndAngle(this.currentPosition[0],this.currentPosition[1],this.currentRotation);actor.game().eventCenter.postEvent("wrap",null,actor,gs.Vector2.Y_COMPONENT,this.sceneHeight,0)}};gs.MotionAspect.checkDestroyX=function(actor){if(this.currentPosition[0]&lt;-500||this.currentPosition[0]&gt;this.sceneWidth+500){actor.scene.markActorForDestruction(actor)}};gs.MotionAspect.checkDestroyY=function(actor){if(this.currentPosition[1]&lt;-500||this.currentPosition[1]&gt;this.sceneHeight+500){actor.scene.markActorForDestruction(actor)}};gs.MotionAspect.returnFalseFunction=function(){return false};gs.MotionAspect.modifyAdditiveVelocity=function(linearVelocity,behaviorID){if(!this._additiveVelocities){this._additiveVelocities=gs.Map.provide();this._additiveVelocitiesCount=0}if(!this._additiveVelocities[behaviorID]){this._additiveVelocities[behaviorID]=gs.array.provide();this._additiveVelocitiesCount++}this._additiveVelocities[behaviorID][0]=linearVelocity[0];this._additiveVelocities[behaviorID][1]=linearVelocity[1];this.modifyTotalVelocity();this.applyCalculatedVelocityFunction=this.applyCalculatedVelocity};gs.MotionAspect.removeAdditiveVelocity=function(behaviorID){if(this._additiveVelocities&amp;&amp;this._additiveVelocities[behaviorID]){gs.array.recycle(this._additiveVelocities[behaviorID]);delete this._additiveVelocities[behaviorID];if(--this._additiveVelocitiesCount===0){gs.Map.recycle(this._additiveVelocities);this._additiveVelocities=null;if(!this._stackedVelocities){this.attributes.linearVelocity.x.setValue(0);this.attributes.linearVelocity.y.setValue(0);this._body.setLinearVelocity(0,0);this.applyCalculatedVelocityFunction=gs.NOOP_FUNCTION}}this.modifyTotalVelocity()}};gs.MotionAspect.modifyStackedVelocity=function(linearVelocity,behavior){if(!this._stackedVelocities){this._stackedVelocities=gs.array.provide();this.stackedVelocityBehaviors=gs.array.provide()}var behaviorIndex=this.stackedVelocityBehaviors.indexOf(behavior);if(this.stackedVelocityBehaviors.indexOf(behavior)===-1){behaviorIndex=this.stackedVelocityBehaviors.length;this.stackedVelocityBehaviors.push(behavior);this.currentStackedVelocityBehavior=behaviorIndex}this._stackedVelocities[behaviorIndex]=gs.array.provide();this._stackedVelocities[behaviorIndex][0]=linearVelocity[0];this._stackedVelocities[behaviorIndex][1]=linearVelocity[1];this.modifyTotalVelocity();this.applyCalculatedVelocityFunction=this.applyCalculatedVelocity};gs.MotionAspect.removeStackedVelocity=function(behavior){if(this._stackedVelocities){var index=this.stackedVelocityBehaviors.indexOf(behavior);if(index!==-1){gs.array.recycle(this._stackedVelocities[index]);this._stackedVelocities.splice(index,1);this.stackedVelocityBehaviors.splice(index,1)}if(this._stackedVelocities.length===0){gs.array.recycle(this._stackedVelocities);gs.array.recycle(this.stackedVelocityBehaviors);this._stackedVelocities=null;this.stackedVelocityBehaviors=null;if(!this._additiveVelocities){this.attributes.linearVelocity.x.setValue(0);this.attributes.linearVelocity.y.setValue(0);this._body.setLinearVelocity(0,0);this.applyCalculatedVelocityFunction=gs.NOOP_FUNCTION}}else{this.currentStackedVelocityBehavior=this.stackedVelocityBehaviors.length-1}this.modifyTotalVelocity()}};gs.MotionAspect.modifyTotalVelocity=function(){var calculatedVelocity=this.calculatedVelocity;calculatedVelocity[0]=0;calculatedVelocity[1]=0;if(this._additiveVelocitiesCount&gt;0){for(var key in this._additiveVelocities){calculatedVelocity[0]+=this._additiveVelocities[key][0];calculatedVelocity[1]+=this._additiveVelocities[key][1]}}if(this._stackedVelocities&amp;&amp;this._stackedVelocities.length&gt;0){calculatedVelocity[0]+=this._stackedVelocities[this.currentStackedVelocityBehavior][0];calculatedVelocity[1]+=this._stackedVelocities[this.currentStackedVelocityBehavior][1]}this._body.setAwake(true);this.wasAwake=true};gs.MotionAspect.applyCalculatedVelocity=function(){this._body.setLinearVelocity(this.calculatedVelocity[0],this.calculatedVelocity[1])};gs.PhysicsAspect=gs.Aspect.subclass("PhysicsAspect");gs.PhysicsAspect.RECTANGLE_SHAPE=0;gs.PhysicsAspect.CIRCLE_SHAPE=1;gs.PhysicsAspect.CUSTOM_SHAPE=2;gs.PhysicsAspect.RestitutionConstraint=gs.NumberConstraint.provide().initWithParameters(0,2);gs.PhysicsAspect.init=function(){gs.Aspect.init.call(this);this.attributes.addRealPositiveMutableAttribute("density",0);this.attributes.addRealPositiveMutableAttribute("friction",0);this.attributes.addRealConstrainedMutableAttribute("restitution",0,0,2);this.attributes.addBooleanMutableAttribute("fixedRotation",false);this.attributes.addBooleanMutableAttribute("movable",false);this.attributes.addIntegerMutableAttribute("collisionShape",0);this.attributes.addRealPositiveMutableAttribute("drag",0);this.attributes.addRealPositiveMutableAttribute("angularDrag",0);this.attributes.addBooleanMutableAttribute("canSleep",true);this.attributes.addBooleanMutableAttribute("betterColisions",false);this.attributes.add;return this};gs.PhysicsAspect.loadFromLite=function(node,initialState){gs.PrototypicalImmutableObject.loadFromLite.call(this,node,initialState);if(parseInt(node.attributes.collisionShape)===gs.PhysicsAspect.CUSTOM_SHAPE&amp;&amp;node.customShape){this._customShape=gs.CustomShape.create();this._customShape.init(node.customShape.rescale,node.customShape.polygons);this._children.push(this._customShape)}};gs.PhysicsAspect.waitForImageBeforeFixtureLoad=function(actor){var physicsAttrs=this.attributes;var shapeType=physicsAttrs.collisionShape.getValue();if(shapeType===gs.PhysicsAspect.CUSTOM_SHAPE){var imageName=actor.attributes.image.getValue();if(imageName){var image=gs.AssetManager.current.imageForName(imageName);return!image.ready}}return false};gs.PhysicsAspect.makeFixtureDefinitions=function(actor,inset,isSensor){var actorSize=actor.attributes.size;var halfWidth=Math.max(actorSize.width.getValue()*.5-inset,.5);var halfHeight=Math.max(actorSize.height.getValue()*.5-inset,.5);var physicsAttrs=this.attributes;var shapeType=physicsAttrs.collisionShape.getValue();var shapes=null;if(shapeType===gs.PhysicsAspect.CUSTOM_SHAPE&amp;&amp;this._customShape){var shapeAspectRatioY=1;var normalizeToWidth=this._customShape.rescale;if(normalizeToWidth&amp;&amp;normalizeToWidth!=0){var imageName=actor.attributes.image.getValue();if(imageName){var image=gs.AssetManager.current.imageForName(imageName);shapeAspectRatioY=image.width/image.height}}shapes=gs.physicsLib.GetPolygonShapes(halfWidth,halfHeight,this._customShape.polygons,shapeAspectRatioY)}else if(shapeType===gs.PhysicsAspect.CIRCLE_SHAPE){var radius=Math.min(halfWidth,halfHeight);shapes=[gs.physicsLib.GetCircleShape(radius)]}else{shapes=[gs.physicsLib.GetPolygonShapeAsBox(halfWidth,halfHeight)]}var fixtureDefs=[];for(var i=0;i&lt;shapes.length;i++){var fixtureDef=new gs.physicsLib.FixtureDef;fixtureDef.setShape(shapes[i]);fixtureDef.setDensity(physicsAttrs.density.getValue());fixtureDef.setFriction(physicsAttrs.friction.getValue());fixtureDef.setRestitution(physicsAttrs.restitution.getValue());fixtureDef.setIsSensor(isSensor);fixtureDefs.push(fixtureDef)}return fixtureDefs};gs.ShapeAspect=gs.Aspect.subclass("ShapeAspect",{createFixtureClosure:function(body,actor){var _this=this;return function(){_this.createFixtures(body,actor)}},start:function(actor,timestamp){var body=actor.aspects.motion._body;if(!body){gs.Log.warn("ShapeAspect.start, physics body is null");return}var imageName=actor.attributes.image.getValue();this.createFixtures(body,actor);actor.attributes.size.width.addObserver(this);actor.attributes.size.height.addObserver(this);actor.aspects.physics.attributes.density.addObserver(this);actor.aspects.physics.attributes.friction.addObserver(this);actor.aspects.physics.attributes.restitution.addObserver(this)},observeValueChange:function(attribute,value){var actor=this.actor();var body=actor.aspects.motion._body;var physics=actor.aspects.physics.attributes;if(attribute===physics.density){body.changeFixtureDensities(value)}else if(attribute===physics.friction){body.changeFixtureFrictions(value)}else if(attribute===physics.restitution){body.changeFixtureRestitutions(value)}else{var inset=this.shapeInset(actor);var actorSize=actor.attributes.size;var halfWidth=Math.max(actorSize.width.getValue()*.5-inset,.5);var halfHeight=Math.max(actorSize.height.getValue()*.5-inset,.5);var shapeType=actor.aspects.physics.attributes.collisionShape.getValue();if(shapeType===gs.PhysicsAspect.CIRCLE_SHAPE){var radius=Math.min(halfWidth,halfHeight);body.resizeFixtureShapesAsCircle(radius)}else{body.resizeFixtureShapesAsBox(halfWidth,halfHeight)}}},shapeInset:function(actor){if(actor.aspects.physics.attributes.movable.getValue()){return.5}else{return 0}},stop:function(actor,timestamp){var body=actor.aspects.motion._body;if(body&amp;&amp;this.fixtures){var centerOfMass=actor.aspects.motion.attributes.centerOfMass;var comx=centerOfMass.x.getValue();var comy=centerOfMass.y.getValue();for(var i=0;i&lt;this.fixtures.length;i++){body.destroyFixture(this.fixtures[i])}body.setCenterOfMass(comx,comy);this.fixtures=null}actor.attributes.size.width.removeObserver(this);actor.attributes.size.height.removeObserver(this);actor.aspects.physics.attributes.density.removeObserver(this);actor.aspects.physics.attributes.friction.removeObserver(this);actor.aspects.physics.attributes.restitution.removeObserver(this)},addCollisionMaskCategory:function(category){if(this.fixtures){this.fixtures.forEach(function(fixture,idx){fixture.addCollisionMaskCategory(category)})}},removeCollisionMaskCategory:function(category){if(this.fixtures){this.fixtures.forEach(function(fixture,idx){fixture.removeCollisionMaskCategory(category)})}},testPoint:function(point){if(this.fixtures){var point={x:point[0]/50,y:point[1]/50};for(var i=0;i&lt;this.fixtures.length;i++){var result=this.fixtures[i]._fixture.TestPoint(point);if(result){return true}}}return false}});gs.CollisionShapeAspect=gs.ShapeAspect.subclass("CollisionShapeAspect",{createFixtures:function(body,actor){var physicsAspect=actor.aspects.physics;var fixtureDefs=physicsAspect.makeFixtureDefinitions(actor,this.shapeInset(actor),false);this.fixtures=[];for(var i=0;i&lt;fixtureDefs.length;i++){var fixtureDef=fixtureDefs[i];var fixture=body.createFixture(fixtureDef);fixture.setFixtureID(gs.GS_COLLISION_SHAPE_ID);this.fixtures.push(fixture)}}});gs.CollisionSensorAspect=gs.ShapeAspect.subclass("CollisionSensorAspect",{createFixtures:function(body,actor){var physicsAspect=actor.aspects.physics;var fixtureDefs=physicsAspect.makeFixtureDefinitions(actor,this.shapeInset(actor),true);this.fixtures=[];for(var i=0;i&lt;fixtureDefs.length;i++){var fixtureDef=fixtureDefs[i];fixtureDef.setIsSensor(true);var fixture=body.createFixture(fixtureDef);fixture.setFixtureID(gs.GS_SENSOR_SHAPE_ID);this.fixtures.push(fixture)}}});gs.AspectList=gs.PrototypicalArray.subclass("AspectList");gs.AspectList.aspectClassMap={graphics:gs.GraphicsAspect,motion:gs.MotionAspect,physics:gs.PhysicsAspect,collisionShape:gs.CollisionShapeAspect,collisionSensor:gs.CollisionSensorAspect};gs.AspectList.initPrime=function(){this.graphics=null;this.motion=null;this.physics=null;this.collisionShape=null;this.collisionSensor=null;return this};gs.AspectList.hasAspect=function(name){return!!this[name]};gs.AspectList.addAspect=function(name){if(!this.hasAspect(name)){var aspectClass=gs.AspectList.aspectClassMap[name];if(aspectClass){var newAspect=aspectClass.provide().init();this.addObjectAtIndex(newAspect,null,name);if(this._started){var actor=this.getParent();newAspect.start(actor,actor.actorTime)}}}return this[name]};gs.AspectList.removeAspect=function(name){var aspect=this[name];if(aspect){if(this._started){var actor=this.getParent();aspect.stop(actor,actor.actorTime)}this.removeObject(aspect)}};gs.AspectList.start=function(actor,timestamp){var array=this.array;for(var i=0,iend=array.length;i&lt;iend;i++){array[i].start(actor,timestamp)}this._started=true};gs.AspectList.stop=function(actor,timestamp){for(var i=this.array.length-1;i&gt;=0;i=i-1){var aspect=this.array[i];aspect.stop(actor,timestamp)}this._started=false};gs.AspectList.loadFromLite=function(node,initialState){var obfuscationLookupTable=gs.CompoundAttribute.obfuscationLookupTable;for(var rawKey in node){var child=node[rawKey];var key=obfuscationLookupTable[rawKey]||rawKey;var aspect=this[key];if(!aspect){aspect=this.addAspect(key)}aspect.loadFromLite(child,initialState)}};gs.AspectList.loadFromTable=function(t,initialState){var len=0;if(t){len=t.length}for(var i=0;i&lt;len;++i){var node=t[i];var type=gs.Project.nodeTypeNameMap[node[gs.JXON._type]];this.addAspect(type);var aspect=this[type];if(aspect){aspect.loadFromTable(node,initialState)}}};gs.AspectList.restoreInitialState=function(){this.graphics.restoreInitialState();this.motion.restoreInitialState();this.physics.restoreInitialState();this.collisionShape&amp;&amp;this.collisionShape.restoreInitialState();this.collisionSensor&amp;&amp;this.collisionSensor.restoreInitialState()};gs.EventCenter=function(){this.eventRegistrations={};this.objectsQueuedForDeregister=[];this.eventBeingHandled=null;this.eventQueue=[]};gs.EventCenterRegistration=function(){this.observer=null;this.eventHandler=null;this.predicates=null};gs.Pool.init(gs.EventCenterRegistration);gs.EventCenter.prototype={globalEvents:["systemPause","behaviorPause","resume","keyDown","keyUp","mouseDown","mouseMoved","mouseUp","accelerated","touchDown","touchMoved","touchUp","touchCancel","collision","wrap","destroyed","changeToScene","sceneWillStart","sceneWillEnd","behaviorWasAdded","resetScene","resetGame","startedWrap","finishedWrap","autorotationStarted","autorotationEnded","startPauseScene","endPauseScene","sceneWillPause","sceneWillResume","keyboardInputEntered","keyboardInputCancelled","purchaseItemSuccess","purchaseItemFailure","purchaseItemCancel","giveAdReward","localeDetected","externalWriteGameAttribute","loadExternalImage"],registerForEvent:function(eventName,object,eventHandler,predicates,targetObject){var registration=gs.EventCenterRegistration.provide();registration.observer=object;registration.eventHandler=eventHandler;registration.predicates=predicates;var eventTable=null;if(targetObject){if(!targetObject.eventRegistrations){targetObject.eventRegistrations=gs.Map.provide()}eventTable=targetObject.eventRegistrations[eventName];if(!eventTable){targetObject.eventRegistrations[eventName]=gs.array.provide();eventTable=targetObject.eventRegistrations[eventName]}}else{eventTable=this.eventRegistrations[eventName];if(!eventTable){this.eventRegistrations[eventName]=gs.array.provide();eventTable=this.eventRegistrations[eventName]}}eventTable.push(registration)},deregisterForEvent:function(eventName,object,targetObject){var eventTable=null;if(targetObject){if(targetObject.eventRegistrations){eventTable=targetObject.eventRegistrations[eventName]}}else if(this.eventRegistrations){eventTable=this.eventRegistrations[eventName]}if(eventTable){if(this.eventBeingHandled!==eventName){this.removeObjectFromEventTable(eventTable,object)}else{this.objectsQueuedForDeregister.push(object);object.queuedForDeregister=true}if(eventTable.length===0){if(targetObject){gs.array.recycle(targetObject.eventRegistrations[eventName]);delete targetObject.eventRegistrations[eventName]}else{gs.array.recycle(this.eventRegistrations[eventName]);delete this.eventRegistrations[eventName]}}}},removeObjectFromEventTable:function(eventTable,objectToRemove){var callbackCount=eventTable.length;for(var i=0;i&lt;callbackCount;++i){var registration=eventTable[i];if(registration.observer===objectToRemove){gs.EventCenterRegistration.recycle(registration);eventTable.splice(i,1);break}}objectToRemove.queuedForDeregister=false},postEvent:function(eventName,objectOfInterest){var observerCount=0;var didChangeRule=false;var i;var args=null;if(arguments.length&gt;2){args=gs.array.provide()}for(i=2;i&lt;arguments.length;i++){args.push(arguments[i])}var argsLength=args?args.length:0;var eventTable=null;if(objectOfInterest){if(objectOfInterest.eventRegistrations){eventTable=objectOfInterest.eventRegistrations[eventName]}else{eventTable=null}}else{eventTable=this.eventRegistrations[eventName]}var callbackCount=0;if(eventTable){callbackCount=eventTable.length;this.eventBeingHandled=eventName;for(var index=callbackCount-1;index&gt;=0;--index){var registration=eventTable[index];var observer=registration.observer;var matchesPredicate=true;var predicates=registration.predicates;if(!observer.queuedForDeregister){if(predicates){for(i=0;i&lt;argsLength;i++){var argument=args[i];var predicate=predicates[i];if(predicate&amp;&amp;predicate(argument)===false){matchesPredicate=false;break}}}if(matchesPredicate){observerCount++;var eventHandler=registration.eventHandler;var returnValue=null;switch(argsLength){case 0:returnValue=observer[eventHandler]();break;case 1:returnValue=observer[eventHandler](args[0]);break;case 2:returnValue=observer[eventHandler](args[0],args[1]);break;case 3:returnValue=observer[eventHandler](args[0],args[1],args[2]);break;default:returnValue=observer[eventHandler].apply(observer,args)}didChangeRule=didChangeRule||returnValue}}}if(args){gs.array.recycle(args)}this.eventBeingHandled=null;var objectCount=this.objectsQueuedForDeregister.length;for(i=0;i&lt;objectCount;i++){this.deregisterForEvent(eventName,this.objectsQueuedForDeregister[i])}this.objectsQueuedForDeregister.length=0}return didChangeRule},postDelayedEvent:function(eventName,objectOfInterest){var args=[];for(var i=2;i&lt;arguments.length;++i){args.push(arguments[i])}var event={eventName:eventName,objectOfInterest:objectOfInterest,args:args};this.eventQueue.push(event)},checkEventQueue:function(){var eventQueue=this.eventQueue;var queueCount=eventQueue.length;for(var i=0;i&lt;queueCount;++i){var event=eventQueue[i];var argCount=event.args.length;switch(argCount){case 0:this.postEvent(event.eventName,event.objectOfInterest);break;case 1:this.postEvent(event.eventName,event.objectOfInterest,event.args[0]);break;case 2:this.postEvent(event.eventName,event.objectOfInterest,event.args[0],event.args[1]);break;case 3:this.postEvent(event.eventName,event.objectOfInterest,event.args[0],event.args[1],event.args[2]);break;default:var args=[event.eventName,event.objectOfInterest];for(var j=0;j&lt;argCount;++j){args.push(event.args[j])}this.postEvent.apply(this,args)}}eventQueue.length=0},registrationsForEvent:function(eventName){return this.eventRegistrations[eventName]!=null?this.eventRegistrations[eventName]:[]}};gs.AllocationHintCache=function(){this.scenes=gs.Map.provide();this.storageKeyPrefix="engine/gs.AllocationHintCache/scenes/";gs.AllocationHintCache.current=this};gs.AllocationHintCache.instance=function(){return gs.util.lazySingleton(this)};gs.AllocationHintCache.prototype={getScene:function(sceneID){var scene=this.scenes[sceneID];if(!scene){scene=gs.Map.provide();scene.actors=gs.Map.provide();this.scenes[sceneID]=scene}return scene},recordActorCount:function(sceneID,prototypeID,count){var scene=this.getScene(sceneID);var previous=scene.actors[prototypeID];if(!previous||count&gt;previous){scene.actors[prototypeID]=count}},recordActorCounts:function(sceneID,countMap){for(var prototypeID in countMap){this.recordActorCount(sceneID,prototypeID,countMap[prototypeID])}},getActorCount:function(sceneID,prototypeID){var scene=this.getScene(sceneID);var count=scene.actors[prototypeID];return count||0},readFromStorage:function(sceneID){var key=this.storageKeyPrefix+sceneID;this.scenes[sceneID]=gs.LocalStorage.getObject(key)},writeToStorage:function(sceneID){var key=this.storageKeyPrefix+sceneID;var scene=this.scenes[sceneID];if(scene){for(var prototypeID in scene.actors){if(scene.actors[prototypeID]&lt;=1){delete scene.actors[prototypeID]}}gs.LocalStorage.setObject(key,this.scenes[sceneID])}}};gs.ActorFactory=function(){this.prototypeIDs=gs.array.provide();this.prototypeByID={};this.poolMap={};this.rawDataByID={};this.sceneID=null;this.outMap={};this.maxMap={};this.maxPoolSize=8;gs.ActorFactory.current=this};gs.ActorFactory.instance=function(){return gs.util.lazySingleton(this)};gs.ActorFactory.prototype={getPrototypeIDs:function(){return this.prototypeIDs},preloadActorPrototypeByIndex:function(index){var hashService=gs.platform.HashService.instance();var promise=new gs.Promise;var that=this;gs.Project.instance.virtualFileCache.loadActorPrototypeByIndex(index).then(function successLoadActorPrototypeByIndex(file){var rawData=file.getData();var prototypeID=hashService.id(rawData.hash,rawData.id);that.rawDataByID[prototypeID]=rawData;that.prototypeIDs.push(prototypeID);that.poolMap[prototypeID]=gs.array.provide();that.outMap[prototypeID]=0;that.maxMap[prototypeID]=0;that.loadActorPrototype(prototypeID)},function failureLoadActorPrototypeByIndex(){gs.Log.error("failed to load actor by index:",index)});return promise},loadActorPrototype:function(prototypeID){try{var rawData=this.rawDataByID[prototypeID];if(!rawData){return false}var actorPrototype=gs.Actor.provide().init();actorPrototype._prototypeID=prototypeID;actorPrototype.loadFromLite(rawData,true);this.prototypeByID[prototypeID]=actorPrototype;gs.array.recycleJXONTree(rawData);delete this.rawDataByID[prototypeID];this.poolMap[prototypeID].push(actorPrototype)}catch(exception){gs.Log.error(exception)}return true},ensureActorPrototype:function(prototypeID){if(this.prototypeByID[prototypeID]){return true}return this.loadActorPrototype(prototypeID)},getActorPrototype:function(prototypeID){this.ensureActorPrototype(prototypeID);return this.prototypeByID[prototypeID]},provideActorInstance:function(prototypeID,instanceData){this.ensureActorPrototype(prototypeID);var actorInstance;var pool=this.poolMap[prototypeID];if(!pool){actorInstance=gs.Actor.provide().init()}else if(pool.length&gt;0){actorInstance=pool.pop()}else{actorInstance=this.allocateActorInstance(prototypeID)}if(instanceData){actorInstance.loadFromLite(instanceData,false)}var out=++this.outMap[prototypeID];this.maxMap[prototypeID]=Math.max(out,this.maxMap[prototypeID]);return actorInstance},spawnActorInstance:function(prototypeID){var actorInstance=this.provideActorInstance(prototypeID,null);if(actorInstance){actorInstance._objectKey=gs.ObjectBase.generateUniqueObjectKey()}return actorInstance},recycleActorInstance:function(actorInstance){var prototypeID=actorInstance._prototypeID;if(prototypeID){actorInstance.restoreInitialState();var pool=this.poolMap[prototypeID];if(!pool){pool=this.poolMap[prototypeID]=gs.array.provide()}pool.push(actorInstance);if(prototypeID in this.outMap){this.outMap[prototypeID]--}else{this.outMap[prototypeID]=0}}},allocateActorInstance:function(prototypeID){var actorPrototype=this.prototypeByID[prototypeID];var actorClone=actorPrototype.clone();return actorClone},clearOutMax:function(){for(var key in this.prototypeByID){this.outMap[key]=0;this.maxMap[key]=0}},primePool:function(prototypeID,count){this.ensureActorPrototype(prototypeID);var pool=this.poolMap[prototypeID];while(pool.length&lt;count){pool.push(this.allocateActorInstance(prototypeID))}},primeSpawnPools:function(spawnPrototypeSet){for(var prototypeID in spawnPrototypeSet){var n=spawnPrototypeSet[prototypeID];this.ensureActorPrototype(prototypeID);var pool=this.poolMap[prototypeID];while(pool.length&lt;n){pool.push(this.allocateActorInstance(prototypeID))}}},managePools:function(sceneID,spawnPrototypeSet){var cache=gs.AllocationHintCache.instance();this.sceneID=sceneID;cache.readFromStorage(sceneID);this.primeSpawnPools(spawnPrototypeSet);for(var prototypeID in this.prototypeByID){var count=cache.getActorCount(sceneID,prototypeID);var pool=this.poolMap[prototypeID];if(count&amp;&amp;count&gt;this.outMap[prototypeID]){this.primePool(prototypeID,count-this.outMap[prototypeID])}else if(pool.length&gt;this.maxPoolSize){pool.length=this.maxPoolSize}}},onSceneStop:function(sceneID){if(sceneID===this.sceneID){var cache=gs.AllocationHintCache.instance();cache.recordActorCounts(this.sceneID,this.maxMap);cache.writeToStorage(this.sceneID);this.clearOutMax()}}};gs.LOCAL_STORAGE_KEY_PREFIX="";gs.update=function(game){gs.EngineContext.current.update()};gs.loadGame=function(url,displayAnchor,loaderProgress){var engineContext=gs.EngineContext.instance();var renderContext=engineContext.getRenderContext();renderContext.setCanvas(displayAnchor.canvas);engineContext.load(url);var project=engineContext.project;project.setLoaderProgress(loaderProgress);return project};gs.playGame=function(project){gs.EngineContext.current.play()};gs.pauseGame=function(project){gs.EngineContext.current.pause()};gs.stopGame=function(project){gs.EngineContext.current.halt()};gs.resetGame=function(project){gs.EngineContext.current.reset()};gs.getCurrentSceneKey=function(project){return gs.EngineContext.current.getCurrentSceneKey()};gs.changeScene=function(project,sceneKey){gs.EngineContext.current.changeScene(sceneKey)};gs.getScenes=function(project,callback){gs.EngineContext.current.getMetadataForAllScenes().then(callback)};gs.setGameVolume=function(project,volume){return gs.EngineContext.current.setVolume(volume)};gs.getGameVolume=function(project){return gs.EngineContext.current.getVolume()};gs.addActionListener=function(project,area,action,listener){gs.LegacyDelegate.addActionListener(area,action,listener)};gs.clearTouchState=function(project){gs.Game.current.clearTouchState()};gs.registerSocialConsoleCallback=function(project,action,callback){if(!project.socialConsoleCallbacks){project.socialConsoleCallbacks={}}project.socialConsoleCallbacks[action]=callback};gs.callSocialConsole=function(project,action){if(!project.socialConsoleCallbacks){project.socialConsoleCallbacks={}}try{var callback=project.socialConsoleCallbacks[action];if(callback){callback(project)}else{gs.Log.info("Social Console didn't registered action:",action)}}catch(exception){gs.Log.error(exception.message)}};gs.afterNextFrame=function(callback){gs.EngineContext.current.waitAfterNextFrame().then(callback)};gs.setExternalDelegate=function(delegate){if(!gs.externalDelegate){gs.externalDelegate=new gs.api.ExternalDelegate}gs.externalDelegate.setDelegate(delegate)};gs.beginSession=function(){gs.EngineContext.current.beginSession()};gs.endSession=function(){gs.EngineContext.current.endSession()};gs.writeGameAttribute=function(keypath,value){var game=gs.Game.instance;game.eventCenter.postDelayedEvent("externalWriteGameAttribute",null,keypath,value)};gs.getTableRowCount=function(tableKeypath){var reference=gs.Reference.lookup(tableKeypath);var tableAttribute=reference.resolveRelativeTo(gs.Game.instance);return tableAttribute.getRowCount()};gs.readTableCell=function(tableKeypath,row,column){var reference=gs.Reference.lookup(tableKeypath);var tableAttribute=reference.resolveRelativeTo(gs.Game.instance);return tableAttribute.getCellSafe(row,column)};gs.writeTableCell=function(tableKeypath,row,column,value){var reference=gs.Reference.lookup(tableKeypath);var tableAttribute=reference.resolveRelativeTo(gs.Game.instance);tableAttribute.setCellSafe(row,column,value)};gs.setLoaderProgress=function(loaderObject){var project=gs.EngineContext.current.project;project.setLoaderProgress(loaderObject)};gs["addActionListener"]=gs.addActionListener;gs["afterNextFrame"]=gs.afterNextFrame;gs["beginSession"]=gs.beginSession;gs["callSocialConsole"]=gs.callSocialConsole;gs["clearTouchState"]=gs.clearTouchState;gs["endSession"]=gs.endSession;gs["getGameVolume"]=gs.getGameVolume;gs["getTableRowCount"]=gs.getTableRowCount;gs["loadGame"]=gs.loadGame;gs["pauseGame"]=gs.pauseGame;gs["playGame"]=gs.playGame;gs["readTableCell"]=gs.readTableCell;gs["registerSocialConsoleCallback"]=gs.registerSocialConsoleCallback;gs["resetGame"]=gs.resetGame;gs["setExternalDelegate"]=gs.setExternalDelegate;gs["setGameVolume"]=gs.setGameVolume;gs["setLoaderProgress"]=gs.setLoaderProgress;gs["writeGameAttribute"]=gs.writeGameAttribute;gs["writeTableCell"]=gs.writeTableCell;gs.devices={start:function(game){game.devices.mouse.button.fastSetValue(false);game.devices.touches.count.fastSetValue(0);game.eventCenter.registerForEvent("mouseMoved",game,"updateMousePosition");game.eventCenter.registerForEvent("mouseDown",game,"mouseButtonDown");game.eventCenter.registerForEvent("mouseUp",game,"mouseButtonUp");game.eventCenter.registerForEvent("accelerated",game,"updateAccelerometer");game.eventCenter.registerForEvent("touchMoved",game,"updateTouchPosition");game.eventCenter.registerForEvent("touchDown",game,"touchDown");game.eventCenter.registerForEvent("touchUp",game,"touchUp")},stop:function(game){game.eventCenter.deregisterForEvent("mouseMoved",game);game.eventCenter.deregisterForEvent("mouseDown",game);game.eventCenter.deregisterForEvent("mouseUp",game);game.eventCenter.deregisterForEvent("accelerated",game);game.eventCenter.deregisterForEvent("touchMoved",game);game.eventCenter.deregisterForEvent("touchDown",game);game.eventCenter.deregisterForEvent("touchUp",game)},deviceRotationForInterfaceOrientation:function(newInterfaceOrientation){if(newInterfaceOrientation===0){return-90}else if(newInterfaceOrientation===1){return 90}else if(newInterfaceOrientation===2){return 0}else{return 180}}};gs.orientSize=function(width,height,orientation){var max=Math.max(width,height);var min=Math.min(width,height);if(gs.isPortrait(orientation)){return[min,max]}else if(gs.isLandscape(orientation)){return[max,min]}else{return[width,height]}};gs.isLandscape=function(orientation){return orientation===0||orientation===1};gs.isPortrait=function(orientation){return orientation===2||orientation===3};gs.Resolution={LEGACY_IPHONE_LANDSCAPE:0,LEGACY_IPHONE_PORTRAIT:1,LEGACY_WEB:2,IPAD_LANDSCAPE:3,IPAD_PORTRAIT:4,HD_720:5,MACBOOK:6,ARCADE:7,NOOK_LANDSCAPE:8,NOOK_PORTRAIT:9,KINDLE_FIRE_LANDSCAPE:10,KINDLE_FIRE_PORTRAIT:11,IPHONE_LANDSCAPE:12,IPHONE_PORTRAIT:13,IPHONE6_LANDSCAPE:14,IPHONE6_PORTRAIT:15,IPHONEPLUS_LANDSCAPE:16,IPHONEPLUS_PORTRAIT:17,MACBOOK_PORTRAIT:18,FULL_HD:19,FULL_HD_PORTRAIT:20};gs.sizeAndOrientationForResolution=function(resolution){var orientation=1;var width;var height;switch(resolution){case gs.Resolution.LEGACY_IPHONE_LANDSCAPE:width=480;height=320;break;case gs.Resolution.LEGACY_IPHONE_PORTRAIT:orientation=2;width=320;height=480;break;case gs.Resolution.LEGACY_WEB:width=720;height=480;break;case gs.Resolution.IPAD_LANDSCAPE:width=1024;height=768;break;case gs.Resolution.IPAD_PORTRAIT:orientation=2;width=768;height=1024;break;case gs.Resolution.HD_720:width=1280;height=720;break;case gs.Resolution.MACBOOK:width=1280;height=800;break;case gs.Resolution.ARCADE:width=480;height=320;break;case gs.Resolution.NOOK_LANDSCAPE:width=1024;height=600;break;case gs.Resolution.NOOK_PORTRAIT:orientation=2;width=600;height=1024;break;case gs.Resolution.KINDLE_FIRE_LANDSCAPE:width=1024;height=580;break;case gs.Resolution.KINDLE_FIRE_PORTRAIT:orientation=2;width=600;height=1004;break;case gs.Resolution.IPHONE_LANDSCAPE:width=568;height=320;break;case gs.Resolution.IPHONE_PORTRAIT:orientation=2;width=320;height=568;break;case gs.Resolution.IPHONE6_LANDSCAPE:width=667;height=375;break;case gs.Resolution.IPHONE6_PORTRAIT:orientation=2;width=375;height=667;break;case gs.Resolution.IPHONEPLUS_LANDSCAPE:width=736;height=414;break;case gs.Resolution.IPHONEPLUS_PORTRAIT:orientation=2;width=414;height=736;break;case gs.Resolution.MACBOOK_PORTRAIT:orientation=2;width=800;height=1280;break;case gs.Resolution.FULL_HD:width=1920;height=1080;break;case gs.Resolution.FULL_HD_PORTRAIT:orientation=2;width=1080;height=1920;break;default:gs.Log.error("Unrecognized resolution:",resolution);width=480;height=320;break}return[width,height,orientation]};gs.AudioManagerBase=function(){this.masterVolume=1;this.musicVolume=1;this.soundVolume=1;this.actualMusicVolume=1;this.actualSoundVolume=1;this.musicIsActive=false;this.musicIsPlaying=false;this.isAllPaused=false};gs.AudioManagerBase.prototype={initWithGame:function(game){},getAssetPath:function(id){return gs.Project.current.pathForSound(id)},getMasterVolume:function(){return this.masterVolume},getMusicVolume:function(){return this.musicVolume},getSoundVolume:function(){return this.soundVolume},setMasterVolume:function(volume){this.masterVolume=gsMath.clampf(volume,0,1);this.actualMusicVolume=this.masterVolume*this.musicVolume;this.actualSoundVolume=this.masterVolume*this.soundVolume;this.updateMusicVolume(this.actualMusicVolume);this.updateSoundVolume(this.actualSoundVolume)},setMusicVolume:function(volume){this.musicVolume=gsMath.clampf(volume,0,1);this.actualMusicVolume=this.masterVolume*this.musicVolume;this.updateMusicVolume(this.actualMusicVolume)},setSoundVolume:function(volume){this.soundVolume=gsMath.clampf(volume,0,1);this.actualSoundVolume=this.masterVolume*this.soundVolume;this.updateSoundVolume(this.actualSoundVolume)},updateMusicVolume:function(volume){},updateSoundVolume:function(volume){},playMusic:function(id,loop){if(id){if(this.musicIsActive){this.stopMusic()}this.startMusic(id,loop)}else if(this.musicIsActive&amp;&amp;!this.musicIsPlaying){this.unpauseMusic()}},startMusic:function(id,loop){this.musicIsActive=true;this.musicIsPlaying=true},stopMusic:function(){this.musicIsActive=false;this.musicIsPlaying=false},pauseMusic:function(){this.musicIsPlaying=false},unpauseMusic:function(){if(this.musicIsActive){this.musicIsPlaying=true}},playSound:function(id,volume,loop,pitch,positional){return null},stopInstance:function(instance){},pauseInstance:function(instance){},unpauseInstance:function(instance){},setInstanceVolume:function(instance,volume){},setInstancePitch:function(instance,pitch){},pauseAll:function(){if(!this.isAllPaused){this.isAllPaused=true}},unpauseAll:function(){if(this.isAllPaused){this.isAllPaused=false}}};gs.StandardAudioManager=function(){gs.AudioManagerBase.call(this);this.currentMusic=this.createAudioElement();this.currentMusic.isMusic=true;this.activeSounds=gs.array.provide();this.inactiveSounds=gs.array.provide();var poolSize=gs.globalOptions.audioPoolSize;for(var i=0;i&lt;poolSize;i++){this.inactiveSounds[i]=this.createAudioElement()}var userAgent=navigator.userAgent;this.waitForTouch=/safari/i.test(userAgent);if(this.waitForTouch){gs.Log.debug("gs.StandardAudioManager","waitForTouch",this.waitForTouch);this.musicWaitingForTouch=true;this.musicWaitingForTouchArgs={};window.addEventListener("mousedown",gs.StandardAudioManager.onTouchStart,false);window.addEventListener("touchstart",gs.StandardAudioManager.onTouchStart,false)}};gs.StandardAudioManager.onAudioError=function(event){gs.AudioManager.current.onAudioError(this,event)};gs.StandardAudioManager.onAudioEnded=function(event){gs.AudioManager.current.onAudioEnded(this,event)};gs.StandardAudioManager.onTouchStart=function(event){gs.AudioManager.current.onTouchStart(this,event)};gs.StandardAudioManager.prototype=gs.subclass(gs.AudioManagerBase,{startMusic:function(id,loop){if(this.musicWaitingForTouch){this.musicWaitingForTouchArgs.id=id;this.musicWaitingForTouchArgs.loop=loop}try{var path=this.getAssetPath(id);if(path){this.currentMusic.src=path;this.currentMusic.assetID=id;this.currentMusic.autoplay=true;this.currentMusic.load();this.currentMusic.volume=this.actualMusicVolume;this.currentMusic.loop=loop;this.currentMusic.play()}}catch(exception){gs.Log.error(exception)}gs.AudioManagerBase.prototype.startMusic.call(this,id,loop)},stopMusic:function(){if(this.musicWaitingForTouch){this.musicWaitingForTouchArgs.id=null}if(this.musicIsActive){if(this.musicIsPlaying){this.currentMusic.pause()}}gs.AudioManagerBase.prototype.stopMusic.call(this)},pauseMusic:function(){if(this.musicIsActive&amp;&amp;this.musicIsPlaying){this.currentMusic.pause()}gs.AudioManagerBase.prototype.pauseMusic.call(this)},unpauseMusic:function(){if(this.musicIsActive&amp;&amp;!this.musicIsPlaying){this.currentMusic.play()}gs.AudioManagerBase.prototype.unpauseMusic.call(this)},updateMusicVolume:function(volume){this.currentMusic.volume=volume},playSound:function(id,volume,loop,pitch,positional){var instance=this.provideInstance(id);if(!instance){return null}instance.assetID=id;instance.instanceVolume=volume;instance.volume=this.actualSoundVolume*volume;instance.loop=loop;instance.pitch=pitch;instance.play();this.activeSounds.push(instance);return instance},stopInstance:function(instance){if(instance){instance.pause();this.recycleInstance(instance)}},pauseInstance:function(instance){if(instance){instance.pause()}},unpauseInstance:function(instance){if(instance){instance.play()}},setInstanceVolume:function(instance,volume){if(instance){instance.instanceVolume=volume;instance.volume=this.actualSoundVolume*volume}},setInstancePitch:function(instance,pitch){},updateSoundVolume:function(volume){for(var i=0,iend=this.activeSounds.length;i&lt;iend;i++){var instance=this.activeSounds[i];instance.volume=volume*instance.instanceVolume}},pauseAll:function(){if(!this.isAllPaused){if(this.musicIsActive&amp;&amp;this.musicIsPlaying){this.currentMusic.pause()}for(var i=0,iend=this.activeSounds.length;i&lt;iend;i++){var instance=this.activeSounds[i];instance.pause()}}gs.AudioManagerBase.prototype.pauseAll.call(this)},unpauseAll:function(){if(this.isAllPaused){if(this.musicIsActive&amp;&amp;this.musicIsPlaying){this.currentMusic.play()}for(var i=0,iend=this.activeSounds.length;i&lt;iend;i++){var instance=this.activeSounds[i];instance.play()}}gs.AudioManagerBase.prototype.unpauseAll.call(this)},createAudioElement:function(){var audioElement=gs.html5.Audio.createAudioElement();audioElement.autobuffer=true;audioElement.preload="auto";audioElement.addEventListener("error",gs.StandardAudioManager.onAudioError,false);audioElement.addEventListener("ended",gs.StandardAudioManager.onAudioEnded,false);audioElement.assetID=null;audioElement.isMusic=false;audioElement.instanceVolume=1;return audioElement},onAudioError:function(audioElement,event){gs.Log.error(event)},onAudioEnded:function(audioElement,event){if(!audioElement.isMusic){this.recycleInstance(audioElement)}},provideInstance:function(id){var path=this.getAssetPath(id);if(!path){return null}var inactiveCount=this.inactiveSounds.length;if(inactiveCount&lt;1){return null}var instance=null;for(var i=0;i&lt;inactiveCount;i++){var inactive=this.inactiveSounds[i];if(inactive.assetID===id){try{inactive.currentTime=0;instance=inactive;this.inactiveSounds.splice(i,1);break}catch(e){}}}if(!instance){instance=this.inactiveSounds.shift();instance.src=path;instance.load()}return instance},recycleInstance:function(instance){var index=this.activeSounds.indexOf(instance);if(index!==-1){this.activeSounds.splice(index,1);this.inactiveSounds.push(instance)}},loadAssets:function(sounds){var n=0;for(var i=0,iend=sounds.length;i&lt;iend;i++){var path=this.getAssetPath(sounds[i]);if(path){var audio=this.createAudioElement();audio.src=path;audio.load();this.inactiveSounds[n++]=audio}}},playMusicWaitingForTouch:function(){var args=this.musicWaitingForTouchArgs;if(args.id){this.playMusic(args.id,args.loop);return true}return false},onTouchStart:function(){if(this.musicWaitingForTouch){var didPlay=this.playMusicWaitingForTouch();if(didPlay){this.musicWaitingForTouch=false}}}});gs.ExtensionAudioManager=function(){gs.StandardAudioManager.call(this);this.context=null;this.masterGain=null;this.soundGain=null;this.bufferMap={};this.instanceMap={};this.waitQueue=[];this.activeInstances=gs.array.provide();this.currentMusic=this.createAudioElement();this.currentMusic.isMusic=true;this.initContext();this.contextWaitingForTouch=this.waitForTouch};gs.ExtensionAudioManager.onRequestLoad=function(event){gs.AudioManager.current.onRequestLoad(this,event)};gs.ExtensionAudioManager.onRequestError=function(event){var request=this;gs.Log.error("gs.ExtensionAudioManager.onRequestError",request.assetID,event)};gs.ExtensionAudioManager.onDecodeError=function(event){gs.Log.error("gs.ExtensionAudioManager.onDecodeError")};gs.ExtensionAudioManager.onBufferSourceEnded=function(event){gs.AudioManager.current.onSourceBufferEnded(this,event)};gs.ExtensionAudioManager.prototype={useAudioBuffer:function(){if(this.isAppleWebkit===undefined){var userAgent=navigator.userAgent;this.isAppleWebkit=/iPad|iPhone|iPod/.test(navigator.platform)||navigator.userAgent.includes("Mac")&amp;&amp;"ontouchend"in document||/Safari/i.test(userAgent)&amp;&amp;!/Chrome/i.test(userAgent)}return!this.isAppleWebkit},initContext:function(){var context=gs.html5.Audio.createAudioContext();this.context=context;this.masterGain=context.createGain();this.masterGain.connect(context.destination);this.soundGain=context.createGain();this.soundGain.connect(this.masterGain);this.musicGain=context.createGain();this.musicGain.connect(this.masterGain);if(!this.useAudioBuffer()){var musicSrc=context.createMediaElementSource(this.currentMusic);musicSrc.connect(this.musicGain)}},setMasterVolume:function(volume){this.masterVolume=gsMath.clampf(volume,0,1);this.masterGain.gain.value=this.masterVolume},setSoundVolume:function(volume){if(volume===0){this.soundGain.disconnect()}else{this.soundGain.connect(this.masterGain)}this.actualSoundVolume=gsMath.clampf(volume,0,1);this.soundGain.gain.value=this.actualSoundVolume},setMusicVolume:function(volume){if(volume===0){this.musicGain.disconnect()}else{this.musicGain.connect(this.masterGain)}this.actualMusicVolume=gsMath.clampf(volume,0,1);this.musicGain.gain.value=this.actualMusicVolume},startMusic:function(id,loop){try{if(this.musicWaitingForTouch){this.musicWaitingForTouchArgs.id=id;this.musicWaitingForTouchArgs.loop=loop}if(!this.useAudioBuffer()){this.__super.startMusic.call(this,id,loop);return}if(this.musicInstance){if(this.musicInstance.assetID===id&amp;&amp;this.musicIsActive&amp;&amp;!this.musicIsPlaying){this.musicInstance.sourceNode.playbackRate.value=1;return}if(this.musicInstance.didStart){this.musicInstance.sourceNode.stop(0)}this.musicInstance.sourceNode.disconnect();this.musicInstance=null}var instance=this.instanceMap[id];if(instance){this.instanceMap[id]=null}this.prepareSoundForNextPlay(id,true);if(!instance){this.loadAsset(id)}instance=this.instanceMap[id];if(!instance){return}instance.loop=loop;if(instance.ready){if(!instance.didStart){instance.sourceNode.start(0);instance.didStart=true}}else{this.waitQueue.push(instance)}this.musicInstance=instance;gs.AudioManagerBase.prototype.startMusic.call(this,id,loop)}catch(e){console.log("Error starting music",e)}},stopMusic:function(){if(this.musicWaitingForTouch){this.musicWaitingForTouchArgs.id=null}if(!this.useAudioBuffer()){this.__super.stopMusic.call(this);return}if(this.musicInstance&amp;&amp;this.musicInstance.didStart){if(this.musicIsActive&amp;&amp;this.musicIsPlaying){this.musicInstance.sourceNode.stop(0)}}gs.AudioManagerBase.prototype.stopMusic.call(this)},pauseMusic:function(){if(this.useAudioBuffer()){if(this.musicIsActive&amp;&amp;this.musicIsPlaying){this.musicInstance.sourceNode.playbackRate.value=0}gs.AudioManagerBase.prototype.pauseMusic.call(this)}else{this.__super.pauseMusic.call(this)}},updateMusicVolume:function(volume){this.currentMusic.volume=volume},unpauseMusic:function(){if(this.useAudioBuffer()){if(this.musicIsActive&amp;&amp;!this.musicIsPlaying){this.musicInstance.sourceNode.playbackRate.value=1}gs.AudioManagerBase.prototype.unpauseMusic.call(this)}else{this.__super.unpauseMusic.call(this)}},playSound:function(id,volume,loop,pitch,positional){var instance=this.createSoundInstance(id,volume,loop,pitch,positional);if(!instance){return null}if(instance.ready){instance.sourceNode.start(0);instance.didStart=true}else{this.waitQueue.push(instance)}this.activeInstances.push(instance);return instance},createSoundInstance:function(id,volume,loop,pitch,positional){var instance=this.instanceMap[id];if(instance){this.instanceMap[id]=null;this.prepareSoundForNextPlay(id)}else{this.prepareSoundForNextPlay(id);instance=this.instanceMap[id];this.instanceMap[id]=null;this.loadAsset(id)}if(!instance){return null}instance.gainNode.gain.value=volume;instance.volume=volume;instance.loop=loop;var initPitch=pitch===undefined||pitch===null?1:pitch;this.setInstancePitch(instance,initPitch);if(positional){instance.pannerNode=this.context.createPanner();instance.pannerNode.panningModel="equalpower";instance.pannerNode.distanceModel="inverse";instance.pannerNode.refDistance=50;instance.pannerNode.connect(instance.gainNode)}return instance},stopInstance:function(instance){if(instance){var index=this.activeInstances.indexOf(instance);if(index!==-1){this.activeInstances.splice(index,1);try{if(instance.ready){instance.sourceNode.stop(0)}instance.gainNode.disconnect();if(instance.pannerNode){instance.pannerNode.disconnect()}instance.sourceNode.disconnect()}catch(exception){gs.Log.error("gs.ExtensionAudioManager.stopInstance",instance.assetID,exception)}}index=this.waitQueue.indexOf(instance);if(index!==-1){this.waitQueue.splice(index,1)}}},pauseInstance:function(instance){if(instance){if(instance.loop){try{instance.sourceNode.disconnect();instance.gainNode.disconnect();if(instance.ready){instance.sourceNode.stop()}}catch(exception){gs.Log.error("gs.ExtensionAudioManager.pauseInstance",instance.assetID,exception)}var replacement=this.createSoundInstance(instance.assetID,instance.volume,instance.loop,instance.pitch);instance.sourceNode=replacement;instance.gainNode=replacement.gainNode;instance.didStart=false}else{this.stopInstance(instance)}}},unpauseInstance:function(instance){if(instance){if(instance.loop&amp;&amp;!instance.didStart){instance.sourceNode.start(0);instance.didStart=true}}},setInstanceVolume:function(instance,volume){if(instance){instance.gainNode.gain.value=volume;instance.volume=volume}},setInstancePitch:function(instance,pitch){if(instance&amp;&amp;instance.detune){instance.detune.value=(pitch-1)*16*100}},setInstanceX:function(instance,x){if(instance&amp;&amp;instance.pannerNode&amp;&amp;instance.pannerNode.positionX){instance.pannerNode.positionX.value=x}},setInstanceY:function(instance,y){if(instance&amp;&amp;instance.pannerNode&amp;&amp;instance.pannerNode.positionY){instance.pannerNode.positionY.value=y}},pauseAll:function(){this.context.suspend();if(!this.useAudioBuffer()){gs.StandardAudioManager.prototype.pauseAll.call(this)}},unpauseAll:function(){this.context.resume();if(!this.useAudioBuffer()){gs.StandardAudioManager.prototype.unpauseAll.call(this)}},stopAllSounds:function(){while(this.activeInstances.length&gt;0){this.stopInstance(this.activeInstances[0])}this.removeAllWaitingInstances()},startWaitingInstances:function(id,buffer){for(var i=0;i&lt;this.waitQueue.length;i++){var instance=this.waitQueue[i];if(instance.assetID===id){instance.buffer=buffer;instance.sourceNode.start(0);instance.didStart=true}}this.removeWaitingInstances(id)},removeWaitingInstances:function(id){for(var i=0;i&lt;this.waitQueue.length;i++){var instance=this.waitQueue[i];if(instance.assetID===id){this.waitQueue.splice(i,1);i--}}},removeAllWaitingInstances:function(id){this.waitQueue.length=0},prepareSoundForNextPlay:function(id,isMusic){try{var instance=this.context.createBufferSource();instance.assetID=id;instance.sourceNode=instance;instance.didStart=false;var buffer=this.bufferMap[id];if(buffer){instance.buffer=buffer;instance.ready=true}if(instance.addEventListener){instance.addEventListener("ended",gs.ExtensionAudioManager.onBufferSourceEnded,false)}else{instance.onended=gs.ExtensionAudioManager.onBufferSourceEnded}if(isMusic){instance.sourceNode.connect(this.musicGain)}else{var gain=this.context.createGain();instance.sourceNode.connect(gain);instance.gainNode=gain;gain.connect(this.soundGain)}this.instanceMap[id]=instance}catch(exception){gs.Log.error("gs.ExtensionAudioManager.prepareSoundForNextPlay",exception)}},initWithGame:function(game){this.__super.initWithGame.call(this,game);gs.Game.current.eventCenter.registerForEvent("sceneWillEnd",this,"removeAllWaitingInstances",null)},loadAssets:function(sounds){for(var i=0,iend=sounds.length;i&lt;iend;i++){var id=sounds[i];if(!this.bufferMap.hasOwnProperty(id)){this.loadAsset(id)}}},loadAsset:function(id){if(this.bufferMap[id]||this.bufferMap[id]===null){return}this.bufferMap[id]=null;var path=this.getAssetPath(id);var request=new XMLHttpRequest;request.open("GET",path,true);request.assetID=id;request.responseType="arraybuffer";request.addEventListener("load",gs.ExtensionAudioManager.onRequestLoad,false);request.addEventListener("error",gs.ExtensionAudioManager.onRequestError,false);request.send()},onRequestLoad:function(request,event){var ok=request.status===200||request.status===0;if(!ok||!request.response){gs.Log.error("Sound load failed:",request.assetID,request.status,request.readyState);return}var that=this;this.context.decodeAudioData(request.response,function successDecodeAudioData(buffer){that.bufferMap[request.assetID]=buffer;that.startWaitingInstances(request.assetID,buffer);that.prepareSoundForNextPlay(request.assetID)},function failureDecodeAudioData(e){console.log("Error decoding audio: ",e);gs.ExtensionAudioManager.onDecodeError()})},onSourceBufferEnded:function(source,event){this.stopInstance(source)},playEmptySound:function(){var context=this.context;var gainNode=context.createGain();gainNode.gain.value=1/64;gainNode.connect(this.soundGain);var buffer=context.createBuffer(1,1,22050);var sourceNode=context.createBufferSource();sourceNode.buffer=buffer;sourceNode.connect(gainNode);sourceNode.start(0)},onTouchStart:function(){if(this.contextWaitingForTouch){this.playEmptySound();this.contextWaitingForTouch=false}this.__super.onTouchStart.call(this)}};gs.inherits(gs.ExtensionAudioManager,gs.StandardAudioManager);gs.AudioManager={current:null,init:function(option){gs.AudioManager.current=gs.AudioManager.create(option)},create:function(option){if(option!==gs.AudioOption.STANDARD){if(gs.html5.Audio.isWebAudioExtensionSupported()){return new gs.ExtensionAudioManager}}return new gs.StandardAudioManager}};gs.Condition=function(){this.__superclass.call(this);this.rule=null;this.ruleIndex=0;this.predicate=null;this.subjectPredicate=null;this.subjectAttribute=null;this.testMethod=gs.Condition.prototype.nullTest;this._parent=null};gs.Condition.EVENT_TYPE=0;gs.Condition.ATTRIBUTE_TYPE=1;gs.Condition.NUMERIC_EXPRESSION_TYPE=2;gs.Condition.STRING_EXPRESSION_TYPE=3;gs.Condition.prototype={declareAttributes:function(attributes){attributes.addReferenceImmutableAttribute("subjectAttribute")},clone:function(){var other=this.__class.provide();other.attributes=this.attributes.clone();other.testMethod=this.testMethod;if(this.predicate){other.predicate=this.predicate.clone();other.predicate._parent=other}if(this.subjectPredicate){other.subjectPredicate=this.subjectPredicate.clone();other.subjectPredicate._parent=other}return other},start:function(actor){if(this.predicate){this.predicate.start(actor)}if(this.subjectPredicate){this.subjectPredicate.start(actor);this.subjectPredicate.attributes.RHS.addObserver(this)}if(this.subjectAttribute){this.subjectAttribute.addObserver(this)}},stop:function(actor){if(this.subjectAttribute){this.subjectAttribute.removeObserver(this)}if(this.predicate){this.predicate.stop(actor)}if(this.subjectPredicate){this.subjectPredicate.attributes.RHS.removeObserver(this);this.subjectPredicate.stop(actor)}},didEnter:function(actor,isInitTime,rule,ruleIndex){this.rule=rule;this.ruleIndex=ruleIndex;var subjectAttributeReference=this.attributes.subjectAttribute.getValue();if(subjectAttributeReference){this.subjectAttribute=subjectAttributeReference.resolveRelativeTo(actor);if(!this.subjectAttribute){this.testMethod=this.nullTest}}if(this.predicate){this.predicate.didEnter(actor,isInitTime)}if(this.subjectPredicate){this.subjectPredicate.didEnter(actor,isInitTime)}},willExit:function(actor){if(this.predicate){this.predicate.willExit(actor)}if(this.subjectPredicate){this.subjectPredicate.willExit(actor)}this.subjectAttribute=null;this.rule=null},testAttribute:function(){var value=this.subjectAttribute.getValue();return this.predicate.testValue(value)},testEvent:function(){return this.predicate.test()},testExpression:function(){return this.predicate.testValue(this.subjectPredicate._RHS)},nullTest:function(){return false},test:function(){return this.testMethod.call(this)},predicateChangedState:function(newState){if(!this.rule){return false}return this.rule.conditionChangedState(this.ruleIndex,newState)},observeValueChange:function(attribute,value){if(this.predicate){this.predicate.valueChanged(value)}},loadFromLite:function(node,initialState){this.__super.loadFromLite.call(this,node,initialState);var attributes=node["attributes"];var predicate=node["predicate"];var subjectPredicate=node["subjectPredicate"];if(predicate){this.predicate=gs.Parser.parsePredicate(predicate,initialState);this.predicate._parent=this}else{gs.Log.warn("Condition missing predicate");this.testMethod=this.nullTest;return}if(subjectPredicate){this.subjectPredicate=gs.Parser.parsePredicate(subjectPredicate,initialState);this.subjectPredicate._parent=this}var conditionType=gs.Condition.EVENT_TYPE;if(attributes){var rawValue=gs.Parser.parseAttributeValue(attributes,"conditionType");if(rawValue){conditionType=parseInt(rawValue,10)}}if(conditionType===gs.Condition.ATTRIBUTE_TYPE){var reference=this.attributes.subjectAttribute.getValue();if(reference){this.testMethod=this.testAttribute}else{gs.Log.warn("Condition subject reference not found");this.testMethod=this.nullTest}}else{this.attributes.subjectAttribute.changeDefaultValue(null);switch(conditionType){case gs.Condition.EVENT_TYPE:this.testMethod=this.testEvent;break;default:this.testMethod=this.testExpression;break}}}};gs.inherits(gs.Condition,gs.ObjectWithImmutableAttributes);gs.Predicate=gs.PrototypicalImmutableObject.subclass("Predicate",{initPrime:function(){this.attributes=null;this.state=null},start:function(actor){},stop:function(actor){},didEnter:function(actor,isInitTime){},willExit:function(actor){this.state=false},setState:function(newState){if(newState!==this.state){this.state=newState;this._parent.predicateChangedState(newState)}}});gs.EventPredicate=gs.Predicate.subclass("EventPredicate",{test:function(){return this.state},willExit:function(){this.state=false}});gs.AutorotatePredicate=gs.EventPredicate.subclass("AutorotatePredicate");gs.AutorotatePredicate.init=function(){gs.EventPredicate.init.call(this);this.attributes.addIntegerImmutableAttribute("mode",0);return this};gs.AutorotatePredicate.didEnter=function(actor,isInitTime){var game=gs.Game.current;game.eventCenter.registerForEvent("autorotationStarted",this,"autorotationStarted");game.eventCenter.registerForEvent("autorotationEnded",this,"autorotationEnded");this.state=false};gs.AutorotatePredicate.willExit=function(actor){var game=gs.Game.current;game.eventCenter.deregisterForEvent("autorotationStarted",this);game.eventCenter.deregisterForEvent("autorotationEnded",this);gs.EventPredicate.willExit.call(this)};gs.AutorotatePredicate.autorotationStarted=function(){this.state=this.attributes.mode.getValue()===0;this._parent.predicateChangedState(this.state)};gs.AutorotatePredicate.autorotationEnded=function(){this.state=this.attributes.mode.getValue()===1;this._parent.predicateChangedState(this.state)};gs.ValuePredicate=gs.Predicate.subclass("ValuePredicate");gs.ValuePredicate.convertValue=function(value){return value};gs.ValuePredicate.testValue=function(value){this._LHS=this.convertValue(value);this.state=this.test(this._LHS,this._RHS);return this.state};gs.ValuePredicate.start=function(actor){this._RHS=this.attributes.RHS.getValue();this.attributes.RHS.addObserver(this)};gs.ValuePredicate.stop=function(actor){this.attributes.RHS.removeObserver(this)};gs.ValuePredicate.valueChanged=function(value){this._LHS=this.convertValue(value);var state=this.test(this._LHS,this._RHS);this.setState(state)};gs.ValuePredicate.observeValueChange=function(attribute,newValue){this._RHS=newValue;if(this._LHS||this._LHS===0){var state=this.test(this._LHS,newValue);this.setState(state)}};gs.EnumerationPredicate=gs.ValuePredicate.subclass("EnumerationPredicate");gs.EnumerationPredicate.init=function(){gs.ValuePredicate.init.call(this);this.attributes.addStringImmutableAttribute("operator","is");this.attributes.addIntegerExpressionAttribute("RHS",0);return this};gs.EnumerationPredicate.willExit=function(actor){this.attributes.RHS.releaseExpressionInputs();this.state=false};gs.EnumerationPredicate.test=function(LHS,RHS){var operator=this.attributes.operator.getValue();if(operator==="is"){return LHS===RHS}else{return LHS!==RHS}};gs.HibernatePredicate=gs.EventPredicate.subclass("HibernatePredicate",{init:function(){gs.EventPredicate.init.call(this);this.recievedStartEvent=false;return this},didEnter:function(actor,isInitTime){gs.EventPredicate.didEnter.call(this,actor,isInitTime);var eventCenter=gs.Game.current.eventCenter;eventCenter.registerForEvent("AppHibernateStart",this,"appHibernateStart");eventCenter.registerForEvent("AppHibernateResume",this,"appHibernateResume");this.state=false},willExit:function(actor){var eventCenter=gs.Game.current.eventCenter;eventCenter.deregisterForEvent("AppHibernateStart",this);eventCenter.deregisterForEvent("AppHibernateResume",this);gs.EventPredicate.willExit.call(this,actor)},appHibernateStart:function(){if(!this.recievedStartEvent){this.recievedStartEvent=true;this.state=true;this._parent.predicateChangedState(this.state);this._parent.ruleBehavior().everyFrame()}},appHibernateResume:function(){if(this.recievedStartEvent){this.recievedStartEvent=false;this.state=false;this._parent.predicateChangedState(this.state)}}});gs.MousePredicate=gs.EventPredicate.subclass("MousePredicate");gs.MousePredicate.init=function(){gs.EventPredicate.init.call(this);this.mouseState="down";return this};gs.MousePredicate.clone=function(){var other=gs.EventPredicate.clone.call(this);other.mouseState=this.mouseState;return other};gs.MousePredicate.start=function(actor){var game=gs.Game.current;game.eventCenter.registerForEvent("mouseDown",this,"mouseDown");game.eventCenter.registerForEvent("mouseUp",this,"mouseUp")};gs.MousePredicate.stop=function(actor){var game=gs.Game.current;game.eventCenter.deregisterForEvent("mouseDown",this);game.eventCenter.deregisterForEvent("mouseUp",this)};gs.MousePredicate.test=function(){var game=gs.Game.current;return game.devices.mouse.button.getValue()};gs.MousePredicate.mouseDown=function(locationInViewX,locationInViewY){var state=this.mouseState==="down";this._parent.predicateChangedState(state)};gs.MousePredicate.mouseUp=function(locationInViewX,locationInViewY){var state=this.mouseState==="up";this._parent.predicateChangedState(state)};gs.MousePredicate.loadFromLite=function(node,initialState){gs.EventPredicate.loadFromLite.call(this,node,initialState);this.mouseState=node["mouseState"]};gs.MousePredicate.loadFromTable=function(t,initialState){gs.EventPredicate.loadFromTable.call(this,t,initialState);this.mouseState=t["mouseState"]};gs.MousePositionPredicate=gs.EventPredicate.subclass("MousePositionPredicate");gs.MousePositionPredicate.OVER_ACTOR=0;gs.MousePositionPredicate.NOT_OVER_ACTOR=1;gs.MousePositionPredicate.init=function(){gs.EventPredicate.init.call(this);this.conditionType=gs.MousePositionPredicate.OVER_ACTOR;return this};gs.MousePositionPredicate.clone=function(){var other=gs.EventPredicate.clone.call(this);other.conditionType=this.conditionType;return other};gs.MousePositionPredicate.start=function(actor){this._entity=actor;var game=gs.Game.current;game.eventCenter.registerForEvent("mouseMoved",this,"mousePositionChanged");game.eventCenter.registerForEvent("mouseDown",this,"mousePositionChanged");actor.attributes.position.x.addObserver(this);actor.attributes.position.y.addObserver(this);actor.attributes.size.width.addObserver(this);actor.attributes.size.height.addObserver(this);actor.attributes.rotation.addObserver(this)};gs.MousePositionPredicate.stop=function(actor){var game=gs.Game.current;game.eventCenter.deregisterForEvent("mouseDown",this);game.eventCenter.deregisterForEvent("mouseMoved",this);actor.attributes.position.x.removeObserver(this);actor.attributes.position.y.removeObserver(this);actor.attributes.size.width.removeObserver(this);actor.attributes.size.height.removeObserver(this);actor.attributes.rotation.removeObserver(this);this._entity=null};gs.MousePositionPredicate.observeValueChange=function(attribute,newValue){var game=gs.Game.current;var actor=this._entity;var layer=actor.layer;var mousePosition=gs.g_tempVec2d;mousePosition[0]=game.devices.mouse.position.x.getValue();mousePosition[1]=game.devices.mouse.position.y.getValue();if(layer.scrollable()){mousePosition=layer.scene.convertViewToScene(mousePosition)}var newState=actor.testPoint(mousePosition);this.setState(newState)};gs.MousePositionPredicate.mousePositionChanged=function(locationInViewX,locationInViewY){var actor=this._entity;var layer=actor.layer;var point=gs.g_tempVec2d;point[0]=locationInViewX;point[1]=locationInViewY;if(layer.scrollable()){point=layer.scene.convertViewToScene(point)}var overActor=actor.testPoint(point);var newState;if(overActor){newState=this.conditionType===gs.MousePositionPredicate.OVER_ACTOR}else{newState=this.conditionType===gs.MousePositionPredicate.NOT_OVER_ACTOR}this.setState(newState)};gs.MousePositionPredicate.test=function(){var game=gs.Game.current;var actor=this._entity;var layer=actor.layer;var mousePosition=gs.g_tempVec2d;mousePosition[0]=game.devices.mouse.position.x.getValue();mousePosition[1]=game.devices.mouse.position.y.getValue();if(layer.scrollable()){mousePosition=layer.scene.convertViewToScene(mousePosition)}this.state=actor.testPoint(mousePosition);return this.state};gs.MousePositionPredicate.loadFromLite=function(node,initialState){gs.EventPredicate.loadFromLite.call(this,node,initialState);if(node["conditionType"]==="over actor"){this.conditionType=gs.MousePositionPredicate.OVER_ACTOR}else{this.conditionType=gs.MousePositionPredicate.NOT_OVER_ACTOR}};gs.MousePositionPredicate.loadFromTable=function(t,initialState){gs.EventPredicate.loadFromTable.call(this,t,initialState);if(t["conditionType"]==="over actor"){this.conditionType=gs.MousePositionPredicate.OVER_ACTOR}else{this.conditionType=gs.MousePositionPredicate.NOT_OVER_ACTOR}};gs.NullPredicate=gs.Predicate.subclass("NullPredicate",{init:function(){gs.Predicate.init.call(this);return this},test:function(){return false}});gs.TouchPredicate=gs.EventPredicate.subclass("TouchPredicate",{PRESSED:0,RELEASED:1,INSIDE:2,OUTSIDE:3,MAX_TOUCH_COUNT:5,init:function(){gs.EventPredicate.init.call(this);this.conditionType=gs.TouchPredicate.PRESSED;return this},clone:function(){var other=gs.EventPredicate.clone.call(this);other.conditionType=this.conditionType;return other},didEnter:function(actor,isInitTime){this._entity=actor;this._isActive=true;if(!this.touchStates){this.touchStates=gs.array.provide()}this.trackingTouch=null;var game=gs.Game.current;game.eventCenter.registerForEvent("touchDown",this,"touchDown");game.eventCenter.registerForEvent("touchUp",this,"touchUp");game.eventCenter.registerForEvent("touchCancel",this,"touchCancel");game.eventCenter.registerForEvent("sceneWillPause",this,"sceneWillPause");game.eventCenter.registerForEvent("sceneWillResume",this,"sceneWillResume");if(this.conditionType===gs.TouchPredicate.INSIDE||this.conditionType===gs.TouchPredicate.OUTSIDE){game.eventCenter.registerForEvent("touchMoved",this,"touchMoved");for(var i=0;i&lt;gs.TouchPredicate.MAX_TOUCH_COUNT;i++){this.touchStates[i]=false}}this.state=false},willExit:function(actor){gs.EventPredicate.willExit.call(this,actor);this._isActive=false;this.touchStates.length=0;var game=gs.Game.current;game.eventCenter.deregisterForEvent("touchDown",this);game.eventCenter.deregisterForEvent("touchUp",this);game.eventCenter.deregisterForEvent("touchCancel",this);game.eventCenter.deregisterForEvent("sceneWillPause",this);game.eventCenter.deregisterForEvent("sceneWillResume",this);if(this.conditionType===gs.TouchPredicate.INSIDE||this.conditionType===gs.TouchPredicate.OUTSIDE){game.eventCenter.deregisterForEvent("touchMoved",this);this.touchStates.length=0}this.trackingTouch=null;this._entity=null},updateStateForTouch:function(index,state){var offset=index-1;var touchStates=this.touchStates;if(touchStates[offset]!==state){touchStates[offset]=state;var combinedState=false;for(var i=0,end=touchStates.length;i&lt;end;i++){combinedState=combinedState||touchStates[i]}this.setState(combinedState)}},touchDown:function(index,locationInViewX,locationInViewY){var actor=this._entity;var layer=actor.layer;var point=gs.g_tempVec2d;point[0]=locationInViewX;point[1]=locationInViewY;if(layer.scrollable()){point=layer.scene.convertViewToScene(point)}var overActor=actor.testPoint(point);var conditionType=this.conditionType;if(conditionType===gs.TouchPredicate.PRESSED||conditionType===gs.TouchPredicate.RELEASED){if(overActor){this.trackingTouch=index;this.setState(this.conditionType===gs.TouchPredicate.PRESSED)}}else{if(conditionType===gs.TouchPredicate.INSIDE){this.updateStateForTouch(index,overActor)}else{this.updateStateForTouch(index,!overActor)}}},touchUp:function(index,locationInViewX,locationInViewY){var actor=this._entity;var layer=actor.layer;var point=gs.g_tempVec2d;point[0]=locationInViewX;point[1]=locationInViewY;if(layer.scrollable()){point=layer.scene.convertViewToScene(point)}var overActor=actor.testPoint(point);var conditionType=this.conditionType;if(conditionType===gs.TouchPredicate.PRESSED||conditionType===gs.TouchPredicate.RELEASED){if(index===this.trackingTouch){this.setState(overActor&amp;&amp;this.conditionType===gs.TouchPredicate.RELEASED);this.trackingTouch=null}}else{this.updateStateForTouch(index,false)}},touchCancel:function(){var touchStatesLength=this.touchStates.length;for(var index=1;index&lt;=touchStatesLength;index++){this.updateStateForTouch(index,false)}},touchMoved:function(index,locationInViewX,locationInViewY){var actor=this._entity;var layer=actor.layer;var point=gs.g_tempVec2d;point[0]=locationInViewX;point[1]=locationInViewY;if(layer.scrollable()){point=layer.scene.convertViewToScene(point)}var overActor=actor.testPoint(point);if(this.conditionType===gs.TouchPredicate.INSIDE){this.updateStateForTouch(index,overActor)}else{this.updateStateForTouch(index,!overActor)}},sceneWillPause:function(scene){var actor=this._entity;if(this._isActive&amp;&amp;scene===actor.scene){var game=gs.Game.current;game.eventCenter.deregisterForEvent("touchDown",this);game.eventCenter.deregisterForEvent("touchUp",this)}},sceneWillResume:function(scene){var actor=this._entity;if(this._isActive&amp;&amp;scene===actor.scene){var game=gs.Game.current;game.eventCenter.registerForEvent("touchDown",this,"touchDown");game.eventCenter.registerForEvent("touchUp",this,"touchUp");if(this.conditionType===gs.TouchPredicate.PRESSED&amp;&amp;this.trackingTouch!==null){this.setState(false);this.trackingTouch=null}}},loadFromLite:function(node,initialState){gs.EventPredicate.loadFromLite.call(this,node,initialState);switch(node["conditionType"]){case"released":this.conditionType=gs.TouchPredicate.RELEASED;break;case"inside":this.conditionType=gs.TouchPredicate.INSIDE;break;case"outside":this.conditionType=gs.TouchPredicate.OUTSIDE;break;default:this.conditionType=gs.TouchPredicate.PRESSED;break}},loadFromTable:function(t,initialState){gs.EventPredicate.loadFromTable.call(this,t,initialState);switch(t["conditionType"]){case"released":this.conditionType=gs.TouchPredicate.RELEASED;break;case"inside":this.conditionType=gs.TouchPredicate.INSIDE;break;case"outside":this.conditionType=gs.TouchPredicate.OUTSIDE;break;default:this.conditionType=gs.TouchPredicate.PRESSED;break}}});gs.KeyPredicate=gs.EventPredicate.subclass("KeyPredicate");gs.KeyPredicate.init=function(){gs.EventPredicate.init.call(this);this.attributes.addStringImmutableAttribute("mode","down");this.attributes.addStringImmutableAttribute("keyString","");return this};gs.KeyPredicate.didEnter=function(actor,isInitTime){var game=gs.Game.current;game.eventCenter.registerForEvent("keyDown",this,"keyDown");game.eventCenter.registerForEvent("keyUp",this,"keyUp");this.keyString=this.attributes.keyString.getValue();this.state=this.attributes.mode.getValue()==="up"};gs.KeyPredicate.willExit=function(actor){var game=gs.Game.current;game.eventCenter.deregisterForEvent("keyDown",this);game.eventCenter.deregisterForEvent("keyUp",this);this.keyString=null};gs.KeyPredicate.keyEvent=function(key,keyState){var didChangeRule=false;if(this.keyString===key.toUpperCase()||this.keyString===key.toLowerCase()){var priorState=this.state;var newState=this.attributes.mode.getValue()===keyState;if(priorState!==newState){this.state=newState;var condition=this._parent;didChangeRule=condition.predicateChangedState(newState)}}return didChangeRule};gs.KeyPredicate.keyDown=function(key){return this.keyEvent(key,"down")};gs.KeyPredicate.keyUp=function(key){return this.keyEvent(key,"up")};gs.CollisionPredicate=gs.EventPredicate.subclass("CollisionPredicate");gs.CollisionPredicate.PROTOTYPE_MODE=0;gs.CollisionPredicate.TAG_MODE=1;gs.CollisionPredicate.init=function(){gs.EventPredicate.init.call(this);this.attributes.addStringImmutableAttribute("prototypeKey","");this.attributes.addStringImmutableAttribute("actorTag","");this.attributes.addIntegerImmutableAttribute("mode",gs.CollisionPredicate.PROTOTYPE_MODE);this._numCollisions=0;return this};gs.CollisionPredicate.clone=function(){var other=this.__class.provide();other._category=this._category;return other};gs.CollisionPredicate.didEnter=function(actor,isInitTime){var category=this._category;this._numCollisions=0;this.state=false;if(!category){return}var scene=actor.scene;if(!actor.aspects.physics.waitForImageBeforeFixtureLoad(actor)){scene._collisionController.addActorSensor(actor,category,this);return}var imageName=actor.attributes.image.getValue();var image=gs.AssetManager.current.imageForName(imageName);var _this=this;image.registerOnLoadCallback(function(){scene._collisionController.addActorSensor(actor,category,_this)})};gs.CollisionPredicate.willExit=function(actor){var category=this._category;if(category){var scene=actor.scene;scene._collisionController.removeActorSensor(actor,category,this)}gs.EventPredicate.willExit.call(this)};gs.CollisionPredicate.collisionBegan=function(actor1,actor2){this._numCollisions++;if(this._numCollisions===1){this.state=true;this._parent.predicateChangedState(true)}};gs.CollisionPredicate.collisionEnded=function(actor1,actor2){this._numCollisions--;if(this._numCollisions===0){this.state=false;this._parent.predicateChangedState(false)}};gs.CollisionPredicate.loadFromLite=function(node,initialState){gs.EventPredicate.loadFromLite.call(this,node,initialState);this.didLoad(initialState)};gs.CollisionPredicate.loadFromTable=function(t,initialState){gs.EventPredicate.loadFromTable.call(this,t,initialState);this.didLoad(initialState)};gs.CollisionPredicate.didLoad=function(initialState){var mode=this.attributes.mode.getValue();if(mode===gs.CollisionPredicate.PROTOTYPE_MODE){var prototypeKey=this.attributes.prototypeKey.getValue();if(prototypeKey&amp;&amp;prototypeKey.length&gt;0){this._category=prototypeKey}}else{this._category=this.attributes.actorTag.getValue()}};gs.NumberPredicate=gs.ValuePredicate.subclass("NumberPredicate");gs.NumberPredicate.init=function(){gs.ValuePredicate.init.call(this);this.attributes.addStringImmutableAttribute("operator","=");this.attributes.addRealExpressionAttribute("RHS",0);return this};gs.NumberPredicate.clone=function(){var other=gs.ValuePredicate.clone.call(this);other.test=this.test;return other};gs.NumberPredicate.willExit=function(actor){this.attributes.RHS.releaseExpressionInputs();this.state=false};gs.NumberPredicate.testEquality=function(LHS,RHS){return Math.abs(LHS-RHS)&lt;.1};gs.NumberPredicate.testInequality=function(LHS,RHS){return Math.abs(LHS-RHS)&gt;=.1};gs.NumberPredicate.testGreaterThan=function(LHS,RHS){return LHS&gt;RHS};gs.NumberPredicate.testLessThan=function(LHS,RHS){return LHS&lt;RHS};gs.NumberPredicate.testGreaterThanOrEqual=function(LHS,RHS){return LHS&gt;=RHS};gs.NumberPredicate.testLessThanOrEqual=function(LHS,RHS){return LHS&lt;=RHS};gs.NumberPredicate.convertValue=function(value){return typeof value==="number"?value:Number(value)};gs.NumberPredicate.loadFromLite=function(node,initialState){gs.ValuePredicate.loadFromLite.call(this,node,initialState);this.didLoad(initialState)};gs.NumberPredicate.loadFromTable=function(t,initialState){gs.ValuePredicate.loadFromTable.call(this,t,initialState);this.didLoad(initialState)};gs.NumberPredicate.didLoad=function(initialState){var operator=this.attributes.operator.getValue();if(operator==="="){this.test=this.testEquality}else if(operator==="!="){this.test=this.testInequality}else if(operator==="&gt;"){this.test=this.testGreaterThan}else if(operator==="&lt;"){this.test=this.testLessThan}else if(operator==="&gt;="){this.test=this.testGreaterThanOrEqual}else if(operator==="&lt;="){this.test=this.testLessThanOrEqual}};gs.BooleanPredicate=gs.ValuePredicate.subclass("BooleanPredicate");gs.BooleanPredicate.init=function(){gs.ValuePredicate.init.call(this);this.attributes.addIntegerImmutableAttribute("RHS",true);return this};gs.BooleanPredicate.didEnter=function(actor,isInitTime){this._RHS=this.convertValue(this.attributes.RHS.getValue())};gs.BooleanPredicate.start=gs.NOOP_FUNCTION;gs.BooleanPredicate.stop=gs.NOOP_FUNCTION;gs.BooleanPredicate.convertValue=function(value){return!(value===false||value===0||value==="false")};gs.BooleanPredicate.test=function(LHS,RHS){return LHS==RHS};gs.PurchasePredicate=gs.EventPredicate.subclass("PurchasePredicate",{ITEM_ANY:0,EVENT:{ANY:0,SUCCESS:1,FAILURE:2,CANCEL:3},init:function(){gs.EventPredicate.init.call(this);this.attributes.addIntegerImmutableAttribute("item",0);this.attributes.addIntegerImmutableAttribute("conditionType",0);return this},didEnter:function(actor,isInitTime){gs.EventPredicate.didEnter.call(this,actor,isInitTime);this._conditionType=this.attributes.conditionType.getValue();this._itemIndex=this.attributes.item.getValue();var game=gs.Game.current;if(this._conditionType==gs.PurchasePredicate.EVENT.ANY||this._conditionType==gs.PurchasePredicate.EVENT.SUCCESS){game.eventCenter.registerForEvent("purchaseItemSuccess",this,"purchaseItemSuccess")}if(this._conditionType==gs.PurchasePredicate.EVENT.ANY||this._conditionType==gs.PurchasePredicate.EVENT.FAILURE){game.eventCenter.registerForEvent("purchaseItemFailure",this,"purchaseItemFailure")}if(this._conditionType==gs.PurchasePredicate.EVENT.ANY||this._conditionType==gs.PurchasePredicate.EVENT.CANCEL){game.eventCenter.registerForEvent("purchaseItemCancel",this,"purchaseItemCancel")}this.state=false},willExit:function(actor){var game=gs.Game.current;game.eventCenter.deregisterForEvent("purchaseItemSuccess",this,"purchaseItemSuccess");game.eventCenter.deregisterForEvent("purchaseItemFailure",this,"purchaseItemFailure");game.eventCenter.deregisterForEvent("purchaseItemCancel",this,"purchaseItemCancel");gs.EventPredicate.willExit.call(this,actor)},purchaseItemSuccess:function(item){item=parseInt(item,10);if(this._itemIndex===gs.PurchasePredicate.ITEM_ANY||this._itemIndex===item){this.setState(this._conditionType===gs.PurchasePredicate.EVENT.SUCCESS||this._conditionType===gs.PurchasePredicate.EVENT.ANY);this.updateGameServiceStatus(item,gs.PurchasePredicate.EVENT.SUCCESS)}},purchaseItemFailure:function(item){item=parseInt(item,10);if(this._itemIndex===gs.PurchasePredicate.ITEM_ANY||this._itemIndex===item){this.setState(this._conditionType===gs.PurchasePredicate.EVENT.FAILURE||this._conditionType===gs.PurchasePredicate.EVENT.ANY);this.updateGameServiceStatus(item,gs.PurchasePredicate.EVENT.FAILURE)}},purchaseItemCancel:function(item){item=parseInt(item,10);if(this._itemIndex===gs.PurchasePredicate.ITEM_ANY||this._itemIndex===item){this.setState(this._conditionType===gs.PurchasePredicate.EVENT.CANCEL||this._conditionType===gs.PurchasePredicate.EVENT.ANY);this.updateGameServiceStatus(item,gs.PurchasePredicate.EVENT.CANCEL)}},updateGameServiceStatus:function(item,status){var game=gs.Game.current;game.services.purchases.item.setValue(item);game.services.purchases.status.setValue(status)}});gs.StringPredicate=gs.ValuePredicate.subclass("StringPredicate");gs.StringPredicate.init=function(){gs.ValuePredicate.init.call(this);this.attributes.addStringImmutableAttribute("operator","contains");this.attributes.addStringExpressionAttribute("RHS","");return this};gs.StringPredicate.willExit=function(actor){gs.ValuePredicate.willExit.call(this,actor);this.attributes.RHS.releaseExpressionInputs()};gs.StringPredicate.test=function(LHS,RHS){var value=LHS;if(value===null||value===undefined){return false}if(typeof value!=="string"){value=String(value)}var operator=this.attributes.operator.getValue();switch(operator){case"is":return value===RHS;case"contains":return gs.string.contains(value,RHS);case"beginsWith":return gs.string.beginsWith(value,RHS);case"endsWith":return gs.string.endsWith(value,RHS);case"isNot":return value!==RHS;case"doesNotContain":return!gs.string.contains(value,RHS);case"doesNotBeginWith":return!gs.string.beginsWith(value,RHS);case"doesNotEndWith":return!gs.string.endsWith(value,RHS);default:gs.Log.strict("Unrecognized text predicate operator:",operator);return false}};gs.Reference=function(){this.keypath=null;this.components=null;this.game=false;this.scene=false;this.attributes=false;this.leaf=null};gs.Reference.cache={};gs.Reference.lookup=function(keypath){var reference=gs.Reference.cache[keypath];if(!reference){reference=new gs.Reference;reference.keypath=keypath;var components=keypath.split(".");var root=components.shift();if(root==="game"){reference.game=true}else if(root==="scene"){reference.scene=true}if(components[0]==="attributes"){reference.attributes=true;components.shift()}if(components.length===1){reference.leaf=components[0];gs.array.recycle(components)}else{reference.components=components}gs.Reference.cache[keypath]=reference}return reference};gs.Reference.loadFromLiteStatic=function(node){debugger};gs.Reference.loadFromTableStatic=function(t){var keypath=t["keypath"];return gs.Reference.lookup(keypath)};gs.Reference.prototype={sourceRoot:function(entity){if(this.game){entity=gs.Game.current}else if(this.scene){entity=gs.Game.current.getCurrentScene()}if(this.attributes){entity=entity.attributes}return entity},resolveRelativeTo:function(entity){var rootEntity=this.sourceRoot(entity);var result;if(this.leaf){result=rootEntity[this.leaf]}else{result=rootEntity.valueForKeypathArray(this.components)}if(!result){gs.Log.strict("Could not resolve keypath:",this.keypath)}return result}};gs.Expression=gs.GameSaladObject.subclass("Expression");gs.Expression._sharedLoadArray=[];gs.FAILURE_EXPRESSION=function(vars){return"Invalid Expression"};gs.Expression.init=function(){this.expressionTree=null;this.inputReferences=null;this.inputReferenceCount=0;this.entity=null;this.inputAttributes=null;this.needsUpdate=true;this.alwaysNeedsUpdate=false;this.delegate=null;this.isObservingAttributes=false;return this};gs.Expression.clone=function(){var other=this.__class.provide();other.expressionTree=this.expressionTree;other.inputReferenceCount=this.inputReferenceCount;other.inputReferences=this.inputReferences;other.entity=null;other.inputAttributes=null;other.needsUpdate=true;other.alwaysNeedsUpdate=this.alwaysNeedsUpdate;other.delegate=null;other.hasResolvedAttributes=false;other.isObservingAttributes=false;return other};gs.Expression.evaluateForEntity=function(entity){if(entity!==this.entity){this.resolveInputAttributesForEntity(entity);this.entity=entity;this.needsUpdate=true}if(!this.isObservingAttributes){this.observeInputs(this.inputAttributes)}var inputAttributes=this.inputAttributes;var expressionTree=this.expressionTree;for(var keypath in inputAttributes){var attribute=inputAttributes[keypath];var attributeValue=attribute.getValue();expressionTree.setVariable(keypath,attributeValue)}this.needsUpdate=this.alwaysNeedsUpdate;return expressionTree.evaluateRoot()};gs.Expression.evaluateForEntityStateless=function(entity){var expressionTree=this.expressionTree;var inputReferences=this.inputReferences;if(inputReferences){for(var keypath in inputReferences){var reference=inputReferences[keypath];var attribute=reference.resolveRelativeTo(entity);if(attribute){expressionTree.setVariable(keypath,attribute.getValue())}}}return expressionTree.evaluateRoot()};gs.Expression.resolveInputAttributesForEntity=function(entity){var inputReferences=this.inputReferences;if(inputReferences){var inputAttributes=this.inputAttributes;if(!inputAttributes){inputAttributes=gs.Map.provide();this.inputAttributes=inputAttributes}for(var keypath in inputReferences){var reference=inputReferences[keypath];var attribute=reference.resolveRelativeTo(entity);if(attribute){inputAttributes[keypath]=attribute}else{gs.Log.warn("Expression could not resolve reference ",keypath);delete inputAttributes[keypath]}}}};gs.Expression.toExpressionString=function(elementArray){var expressionString="";for(var i=0,iend=elementArray.length;i&lt;iend;i++){var token=elementArray[i];if(typeof token==="object"){expressionString+=token.keypath}else{expressionString+=token;if(/random/.test(token)){this.alwaysNeedsUpdate=true}}}return expressionString};gs.Expression.observeInputs=function(inputs){for(var key in inputs){var input=inputs[key];input.addObserver(this)}this.isObservingAttributes=true};gs.Expression.releaseInputs=function(){var inputs=this.inputAttributes;for(var key in inputs){var input=inputs[key];input.removeObserver(this)}this.entity=null;this.isObservingAttributes=false;this.needsUpdate=true};gs.Expression.setDelegate=function(delegate){this.delegate=delegate};gs.Expression.observeValueChange=function(object,newValue){var delegate=this.delegate;this.needsUpdate=true;if(delegate){delegate.expressionInputsChanged()}};gs.Expression.loadFromLite=function(node,initialState){var array=gs.Expression._sharedLoadArray;array.length=0;var inputReferences=this.inputReferences;var gs_Reference_lookup=gs.Reference.lookup;var referenceCount=0;if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){var segment=node[i];var keypath=segment["keypath"];if(keypath){if(!inputReferences){inputReferences=gs.Map.provide();this.inputReferences=inputReferences}var reference=gs_Reference_lookup(keypath);inputReferences[keypath]=reference;referenceCount++;array[i]=reference}else{array[i]=segment}}}else{var segment=node;var keypath=segment["keypath"];if(keypath){if(!inputReferences){inputReferences=gs.Map.provide();this.inputReferences=inputReferences}var reference=gs_Reference_lookup(keypath);inputReferences[keypath]=reference;referenceCount++;array[0]=reference}else{array[0]=segment}}this.inputReferenceCount+=referenceCount;var expressionString=this.toExpressionString(array);this.expressionTree=gs.SafeExpression.provide().init(expressionString)};gs.Expression.loadFromTable=function(t){var array=gs.Expression._sharedLoadArray;array.length=0;var tagKey=gs.JXON._type;var contentTag=gs.JXON._text;var inputReferences=this.inputReferences;var gs_Reference_lookup=gs.Reference.lookup;var referenceCount=0;var elements=t[gs.JXON._children];for(var i=0,iend=elements.length;i&lt;iend;i++){var element=elements[i];var tag=element[tagKey];if(tag==="string"){array[i]=element[contentTag]}else{if(!inputReferences){inputReferences=gs.Map.provide();this.inputReferences=inputReferences}var keypath=element["keypath"];var reference=gs_Reference_lookup(keypath);inputReferences[keypath]=reference;referenceCount++;array[i]=reference}}this.inputReferenceCount+=referenceCount;var expressionString=this.toExpressionString(array);this.expressionTree=gs.SafeExpression.provide().init(expressionString)};var parser=function(){var parser={trace:function trace(){},yy:{},symbols_:{error:2,start:3,expression:4,CONCATENATE:5,"+":6,"-":7,"*":8,"/":9,"%":10,"^":11,functionCall:12,"(":13,")":14,term:15,FUNCTION_NAME:16,argumentList:17,IDENTIFIER:18,expressionList:19,LIST_SEPARATOR:20,reference:21,NUMERIC_LITERAL:22,BOOLEAN_LITERAL:23,STRING_LITERAL:24,KEYWORD:25,KEYPATH_SEPARATOR:26,keypath:27,$accept:0,$end:1},terminals_:{2:"error",5:"CONCATENATE",6:"+",7:"-",8:"*",9:"/",10:"%",11:"^",13:"(",14:")",16:"FUNCTION_NAME",18:"IDENTIFIER",20:"LIST_SEPARATOR",22:"NUMERIC_LITERAL",23:"BOOLEAN_LITERAL",24:"STRING_LITERAL",25:"KEYWORD",26:"KEYPATH_SEPARATOR"},productions_:[0,[3,1],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,2],[4,2],[4,3],[4,1],[4,3],[4,1],[12,2],[12,2],[17,2],[17,3],[19,1],[19,3],[15,1],[15,1],[15,1],[15,1],[15,1],[21,1],[21,3],[27,1],[27,3]],performAction:function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$){var $0=$$.length-1;switch(yystate){case 1:this.$=$$[$0];return this.$;break;case 2:this.$={kind:"operation",type:"string",operation:"concatenate",operands:[$$[$0-2],$$[$0]]};break;case 3:this.$={kind:"operation",type:"number",operation:$$[$0-1],operands:[$$[$0-2],$$[$0]]};break;case 4:this.$={kind:"operation",type:"number",operation:$$[$0-1],operands:[$$[$0-2],$$[$0]]};break;case 5:this.$={kind:"operation",type:"number",operation:$$[$0-1],operands:[$$[$0-2],$$[$0]]};break;case 6:this.$={kind:"operation",type:"number",operation:$$[$0-1],operands:[$$[$0-2],$$[$0]]};break;case 7:this.$={kind:"operation",type:"number",operation:"mod",operands:[$$[$0-2],$$[$0]]};break;case 8:this.$={kind:"operation",type:"number",operation:"negate",operands:[$$[$0]]};break;case 9:this.$=$$[$0];break;case 10:this.$={kind:"operation",type:"number",operation:"pow",operands:[$$[$0-2],$$[$0]]};break;case 11:this.$=$$[$0];break;case 12:this.$=$$[$0-1];break;case 13:this.$=$$[$0];break;case 14:this.$={kind:"operation",type:"infer",operation:$$[$0-1],operands:$$[$0]};break;case 15:this.$={error:true,kind:"operation",type:"error",operation:$$[$0-1],operands:$$[$0]};break;case 16:this.$=[];break;case 17:this.$=$$[$0-1];break;case 18:this.$=[$$[$0]];break;case 19:this.$=$$[$0-2];this.$.push($$[$0]);break;case 20:this.$={kind:"reference",type:"infer",reference:$$[$0]};break;case 21:this.$={kind:"literal",type:"number",literal:parseFloat($$[$0])};break;case 22:this.$={kind:"literal",type:"boolean",literal:$$[$0]==="true"};break;case 23:this.$={kind:"literal",type:"string",literal:$$[$0].substr(1,$$[$0].length-2)};break;case 24:this.$={error:true,kind:"reference",type:"error",reference:$$[$0]};break;case 25:this.$=$$[$0];break;case 26:this.$=[$$[$0-2],$$[$0-1],$$[$0]].join("");break;case 27:this.$=$$[$0];break;case 28:this.$=[$$[$0-2],$$[$0-1],$$[$0]].join("");break}},table:[{3:1,4:2,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{1:[3]},{1:[2,1],5:[1,15],6:[1,16],7:[1,17],8:[1,18],9:[1,19],10:[1,20],11:[1,21]},{4:22,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{4:23,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{1:[2,11],5:[2,11],6:[2,11],7:[2,11],8:[2,11],9:[2,11],10:[2,11],11:[2,11],14:[2,11],20:[2,11]},{4:24,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{1:[2,13],5:[2,13],6:[2,13],7:[2,13],8:[2,13],9:[2,13],10:[2,13],11:[2,13],14:[2,13],20:[2,13]},{13:[1,26],17:25},{1:[2,24],5:[2,24],6:[2,24],7:[2,24],8:[2,24],9:[2,24],10:[2,24],11:[2,24],13:[1,26],14:[2,24],17:27,20:[2,24]},{1:[2,20],5:[2,20],6:[2,20],7:[2,20],8:[2,20],9:[2,20],10:[2,20],11:[2,20],14:[2,20],20:[2,20]},{1:[2,21],5:[2,21],6:[2,21],7:[2,21],8:[2,21],9:[2,21],10:[2,21],11:[2,21],14:[2,21],20:[2,21]},{1:[2,22],5:[2,22],6:[2,22],7:[2,22],8:[2,22],9:[2,22],10:[2,22],11:[2,22],14:[2,22],20:[2,22]},{1:[2,23],5:[2,23],6:[2,23],7:[2,23],8:[2,23],9:[2,23],10:[2,23],11:[2,23],14:[2,23],20:[2,23]},{1:[2,25],5:[2,25],6:[2,25],7:[2,25],8:[2,25],9:[2,25],10:[2,25],11:[2,25],14:[2,25],20:[2,25],26:[1,28]},{4:29,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{4:30,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{4:31,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{4:32,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{4:33,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{4:34,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{4:35,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{1:[2,8],5:[2,8],6:[2,8],7:[2,8],8:[2,8],9:[2,8],10:[2,8],11:[1,21],14:[2,8],20:[2,8]},{1:[2,9],5:[2,9],6:[2,9],7:[2,9],8:[2,9],9:[2,9],10:[2,9],11:[1,21],14:[2,9],20:[2,9]},{5:[1,15],6:[1,16],7:[1,17],8:[1,18],9:[1,19],10:[1,20],11:[1,21],14:[1,36]},{1:[2,14],5:[2,14],6:[2,14],7:[2,14],8:[2,14],9:[2,14],10:[2,14],11:[2,14],14:[2,14],20:[2,14]},{4:39,6:[1,4],7:[1,3],12:5,13:[1,6],14:[1,37],15:7,16:[1,8],18:[1,9],19:38,21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{1:[2,15],5:[2,15],6:[2,15],7:[2,15],8:[2,15],9:[2,15],10:[2,15],11:[2,15],14:[2,15],20:[2,15]},{18:[1,41],27:40},{1:[2,2],5:[1,15],6:[1,16],7:[1,17],8:[1,18],9:[1,19],10:[1,20],11:[1,21],14:[2,2],20:[2,2]},{1:[2,3],5:[2,3],6:[2,3],7:[2,3],8:[1,18],9:[1,19],10:[1,20],11:[1,21],14:[2,3],20:[2,3]},{1:[2,4],5:[2,4],6:[2,4],7:[2,4],8:[1,18],9:[1,19],10:[1,20],11:[1,21],14:[2,4],20:[2,4]},{1:[2,5],5:[2,5],6:[2,5],7:[2,5],8:[2,5],9:[2,5],10:[2,5],11:[1,21],14:[2,5],20:[2,5]},{1:[2,6],5:[2,6],6:[2,6],7:[2,6],8:[2,6],9:[2,6],10:[2,6],11:[1,21],14:[2,6],20:[2,6]},{1:[2,7],5:[2,7],6:[2,7],7:[2,7],8:[2,7],9:[2,7],10:[2,7],11:[1,21],14:[2,7],20:[2,7]},{1:[2,10],5:[2,10],6:[2,10],7:[2,10],8:[2,10],9:[2,10],10:[2,10],11:[1,21],14:[2,10],20:[2,10]},{1:[2,12],5:[2,12],6:[2,12],7:[2,12],8:[2,12],9:[2,12],10:[2,12],11:[2,12],14:[2,12],20:[2,12]},{1:[2,16],5:[2,16],6:[2,16],7:[2,16],8:[2,16],9:[2,16],10:[2,16],11:[2,16],14:[2,16],20:[2,16]},{14:[1,42],20:[1,43]},{5:[1,15],6:[1,16],7:[1,17],8:[1,18],9:[1,19],10:[1,20],11:[1,21],14:[2,18],20:[2,18]},{1:[2,26],5:[2,26],6:[2,26],7:[2,26],8:[2,26],9:[2,26],10:[2,26],11:[2,26],14:[2,26],20:[2,26],26:[1,44]},{1:[2,27],5:[2,27],6:[2,27],7:[2,27],8:[2,27],9:[2,27],10:[2,27],11:[2,27],14:[2,27],20:[2,27],26:[2,27]},{1:[2,17],5:[2,17],6:[2,17],7:[2,17],8:[2,17],9:[2,17],10:[2,17],11:[2,17],14:[2,17],20:[2,17]},{4:45,6:[1,4],7:[1,3],12:5,13:[1,6],15:7,16:[1,8],18:[1,9],21:10,22:[1,11],23:[1,12],24:[1,13],25:[1,14]},{18:[1,46]},{5:[1,15],6:[1,16],7:[1,17],8:[1,18],9:[1,19],10:[1,20],11:[1,21],14:[2,19],20:[2,19]},{1:[2,28],5:[2,28],6:[2,28],7:[2,28],8:[2,28],9:[2,28],10:[2,28],11:[2,28],14:[2,28],20:[2,28],26:[2,28]}],defaultActions:{},parseError:function parseError(str,hash){throw new Error(str)},parse:function parse(input){var self=this,stack=[0],vstack=[null],lstack=[],table=this.table,yytext="",yylineno=0,yyleng=0,recovering=0,TERROR=2,EOF=1;this.lexer.setInput(input);this.lexer.yy=this.yy;this.yy.lexer=this.lexer;if(typeof this.lexer.yylloc=="undefined")this.lexer.yylloc={};var yyloc=this.lexer.yylloc;lstack.push(yyloc);if(typeof this.yy.parseError==="function")this.parseError=this.yy.parseError;function popStack(n){stack.length=stack.length-2*n;vstack.length=vstack.length-n;lstack.length=lstack.length-n}function lex(){var token;token=self.lexer.lex()||1;if(typeof token!=="number"){token=self.symbols_[token]||token}return token}var symbol,preErrorSymbol,state,action,a,r,yyval={},p,len,newState,expected;while(true){state=stack[stack.length-1];if(this.defaultActions[state]){action=this.defaultActions[state]}else{if(symbol==null)symbol=lex();action=table[state]&amp;&amp;table[state][symbol]}if(typeof action==="undefined"||!action.length||!action[0]){if(!recovering){expected=[];for(p in table[state])if(this.terminals_[p]&amp;&amp;p&gt;2){expected.push("'"+this.terminals_[p]+"'")}var errStr="";if(this.lexer.showPosition){errStr="Parse error on line "+(yylineno+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+expected.join(", ")+", got '"+this.terminals_[symbol]+"'"}else{errStr="Parse error on line "+(yylineno+1)+": Unexpected "+(symbol==1?"end of input":"'"+(this.terminals_[symbol]||symbol)+"'")}this.parseError(errStr,{text:this.lexer.match,token:this.terminals_[symbol]||symbol,line:this.lexer.yylineno,loc:yyloc,expected:expected})}if(recovering==3){if(symbol==EOF){throw new Error(errStr||"Parsing halted.")}yyleng=this.lexer.yyleng;yytext=this.lexer.yytext;yylineno=this.lexer.yylineno;yyloc=this.lexer.yylloc;symbol=lex()}while(1){if(TERROR.toString()in table[state]){break}if(state==0){throw new Error(errStr||"Parsing halted.")}popStack(1);state=stack[stack.length-1]}preErrorSymbol=symbol;symbol=TERROR;state=stack[stack.length-1];action=table[state]&amp;&amp;table[state][TERROR];recovering=3}if(action[0]instanceof Array&amp;&amp;action.length&gt;1){throw new Error("Parse Error: multiple actions possible at state: "+state+", token: "+symbol)}switch(action[0]){case 1:stack.push(symbol);vstack.push(this.lexer.yytext);lstack.push(this.lexer.yylloc);stack.push(action[1]);symbol=null;if(!preErrorSymbol){yyleng=this.lexer.yyleng;yytext=this.lexer.yytext;yylineno=this.lexer.yylineno;yyloc=this.lexer.yylloc;if(recovering&gt;0)recovering--}else{symbol=preErrorSymbol;preErrorSymbol=null}break;case 2:len=this.productions_[action[1]][1];yyval.$=vstack[vstack.length-len];yyval._$={first_line:lstack[lstack.length-(len||1)].first_line,last_line:lstack[lstack.length-1].last_line,first_column:lstack[lstack.length-(len||1)].first_column,last_column:lstack[lstack.length-1].last_column};r=this.performAction.call(yyval,yytext,yyleng,yylineno,this.yy,action[1],vstack,lstack);if(typeof r!=="undefined"){return r}if(len){stack=stack.slice(0,-1*len*2);vstack=vstack.slice(0,-1*len);lstack=lstack.slice(0,-1*len)}stack.push(this.productions_[action[1]][0]);vstack.push(yyval.$);lstack.push(yyval._$);newState=table[stack[stack.length-2]][stack[stack.length-1]];stack.push(newState);break;case 3:return true}}return true}};var lexer=function(){var lexer={EOF:1,parseError:function parseError(str,hash){if(this.yy.parseError){this.yy.parseError(str,hash)}else{throw new Error(str)}},setInput:function(input){this._input=input;this._more=this._less=this.done=false;this.yylineno=this.yyleng=0;this.yytext=this.matched=this.match="";this.conditionStack=["INITIAL"];this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0};return this},input:function(){var ch=this._input[0];this.yytext+=ch;this.yyleng++;this.match+=ch;this.matched+=ch;var lines=ch.match(/\n/);if(lines)this.yylineno++;this._input=this._input.slice(1);return ch},unput:function(ch){this._input=ch+this._input;return this},more:function(){this._more=true;return this},pastInput:function(){var past=this.matched.substr(0,this.matched.length-this.match.length);return(past.length&gt;20?"...":"")+past.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var next=this.match;if(next.length&lt;20){next+=this._input.substr(0,20-next.length)}return(next.substr(0,20)+(next.length&gt;20?"...":"")).replace(/\n/g,"")},showPosition:function(){var pre=this.pastInput();var c=new Array(pre.length+1).join("-");return pre+this.upcomingInput()+"\n"+c+"^"},next:function(){if(this.done){return this.EOF}if(!this._input)this.done=true;var token,match,col,lines;if(!this._more){this.yytext="";this.match=""}var rules=this._currentRules();for(var i=0;i&lt;rules.length;i++){match=this._input.match(this.rules[rules[i]]);if(match){lines=match[0].match(/\n.*/g);if(lines)this.yylineno+=lines.length;this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:lines?lines[lines.length-1].length-1:this.yylloc.last_column+match[0].length};this.yytext+=match[0];this.match+=match[0];this.matches=match;this.yyleng=this.yytext.length;this._more=false;this._input=this._input.slice(match[0].length);this.matched+=match[0];token=this.performAction.call(this,this.yy,this,rules[i],this.conditionStack[this.conditionStack.length-1]);if(token)return token;else return}}if(this._input===""){return this.EOF}else{this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})}},lex:function lex(){var r=this.next();if(typeof r!=="undefined"){return r}else{return this.lex()}},begin:function begin(condition){this.conditionStack.push(condition)},popState:function popState(){return this.conditionStack.pop()},_currentRules:function _currentRules(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules}};lexer.performAction=function anonymous(yy,yy_,$avoiding_name_collisions,YY_START){var YYSTATE=YY_START;switch($avoiding_name_collisions){case 0:return"KEYWORD";break;case 1:return"FUNCTION_NAME";break;case 2:return"FUNCTION_NAME";break;case 3:return"FUNCTION_NAME";break;case 4:return"FUNCTION_NAME";break;case 5:return"BOOLEAN_LITERAL";break;case 6:return"IDENTIFIER";break;case 7:return"NUMERIC_LITERAL";break;case 8:return"STRING_LITERAL";break;case 9:return"STRING_LITERAL";break;case 10:return"+";break;case 11:return"-";break;case 12:return"*";break;case 13:return"/";break;case 14:return"%";break;case 15:return"^";break;case 16:return"CONCATENATE";break;case 17:return"KEYPATH_SEPARATOR";break;case 18:return"LIST_SEPARATOR";break;case 19:return"(";break;case 20:return")";break;case 21:break}};lexer.rules=[/^\b(self|scene|game)\b/,/^\b(random|abs|max|min|sqrt|sin|cos|tan|asin|acos|atan|vectorToAngle|magnitude|ceil|floor|round|roundTo|log10|ln|exp|pow|mod)\b/,/^\b(prec|padInt|padReal|textFind|textLength|textRepeat|textReplace|textReplaceAll|textSubStr)\b/,/^\b(tableCellValue|tableRowCount|tableColCount|tableColNumber|tableColSum|tableMergeValues|tableRowNumber|tableSearch)\b/,/^\b(networkPlayerTableForId|networkPlayerIdForTable|networkPlayerNumberForId|networkPlayerIdForNumber)\b/,/^\b(true|false)\b/,/^[_a-zA-Z][_a-zA-Z0-9]*/,/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/,/^'[^']*'/,/^"[^\"]*"/,/^\+/,/^-/,/^\*/,/^\//,/^%/,/^\^/,/^\.\./,/^\./,/^,/,/^\(/,/^\)/,/^\s+/];lexer.conditions={INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21],inclusive:true}};return lexer}();parser.lexer=lexer;return parser}();gs.SafeExpressionCache={};gs.SafeExpression=function(){this.original=null;this.vars=null;this.root=null};gs.Pool.init(gs.SafeExpression);gs.SafeExpression.prototype={defaultValue:0,constantPattern:/^[-+]?[.\d]+$/,useConstant:false,constantValue:0,referencePattern:/^(self|scene|game)(\.\w+)*$/,useFastReference:false,fastReference:null,fastReferenceValue:0,randomPattern:/^\s*random\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)\s*$/,useFastRandom:false,fastRandomA:0,fastRandomB:0,init:function(expression){this.original=expression;var constantTest=this.constantPattern.test(expression);if(constantTest){this.useConstant=true;this.constantValue=parseFloat(expression,10);return this}var referenceTest=this.referencePattern.test(expression);if(referenceTest){this.useFastReference=true;this.fastReference=expression;this.fastReferenceValue=0;return this}var randomTest=this.randomPattern.test(expression);if(randomTest){var randomMatch=this.randomPattern.exec(expression);this.useFastRandom=true;this.fastRandomA=randomMatch[1]|0;this.fastRandomB=randomMatch[2]|0;if(this.fastRandomA&gt;this.fastRandomB){this.fastRandomA=randomMatch[2]|0;this.fastRandomB=randomMatch[1]|0}gs.array.recycle(randomMatch);return this}this.vars=gs.Map.provide();var tree=gs.SafeExpressionCache[expression];if(!tree){try{tree=parser.parse(expression);this.normalize(tree);tree=this.reduce(tree);gs.SafeExpressionCache[expression]=tree}catch(error){gs.Log.strict("Expression syntax error in:",expression,"\n"+error.message);this.root=parser.parse(String(this.defaultValue))}}this.root=tree;return this},ensureString:function(s){if(typeof s!=="string"){return String(s)}return s},padInt:function(num,count,round){if(round===undefined){round=true}var numZeropad=(round?Math.floor(num):num)+"";while(numZeropad.length&lt;count){numZeropad="0"+numZeropad}return numZeropad},prec:function(number,decimalPlaces){return number.toFixed(decimalPlaces)},padReal:function(number,count,decimalPlaces){return this.padInt(this.prec(number,decimalPlaces),count,false)},textFind:function(text,pattern,begin){text=this.ensureString(text);pattern=this.ensureString(pattern);var index=text.indexOf(pattern,begin-1);return index!==-1?index+1:-1},textLength:function(text){text=this.ensureString(text);return text.length},textRepeat:function(text,n){var s="";text=this.ensureString(text);for(var i=0;i&lt;n;i++){s+=text}return s},textReplace:function(text,pattern,replacement){text=this.ensureString(text);pattern=this.ensureString(pattern);return text.replace(pattern,replacement)},textReplaceAll:function(text,pattern,replacement){text=this.ensureString(text);pattern=this.ensureString(pattern);var regex=new RegExp(pattern,"g");return text.replace(regex,replacement)},textSubStr:function(text,begin,end){text=this.ensureString(text);return text.substring(begin-1,end)},sin:function(x){return Math.sin(x*gsMath.DEG2RAD)},cos:function(x){return Math.cos(x*gsMath.DEG2RAD)},tan:function(x){return Math.tan(x*gsMath.DEG2RAD)},asin:function(x){return Math.asin(x)*gsMath.RAD2DEG},acos:function(x){return Math.acos(x)*gsMath.RAD2DEG},atan:function(x){return Math.atan(x)*gsMath.RAD2DEG},vectorToAngle:function(x,y){return Math.atan2(y,x)*gsMath.RAD2DEG},magnitude:function(x,y){return Math.sqrt(x*x+y*y)},lua_mod:function(a,b){return a-Math.floor(a/b)*b},legacy_mod:function(x,y){x=x|0;y=y|0;return x-Math.floor(x/y)*y},random:function(a,b){if(a&gt;=b){return a}a=a|0;b=b|0;var r=gs.Random();return a+r*(b-a+1)|0},fastRandom:function(a,b){var r=gs.Random();return a+r*(b-a+1)|0},log10:function(x){return Math.log(x)/Math.log(10)},roundTo:function(x,n){var k=Math.pow(10,n);return Math.floor(x*k+.5)/k},tableCellValue:function(table,row,column){if(!table||!table.getCellSafe){return 0}return table.getCellSafe(row,column)},tableRowCount:function(table){return table.getRowCount()},tableColCount:function(table){return table.getColumnCount()},tableRowNumber:function(table,label){return table.lookupRow(label)},tableColNumber:function(table,label){return table.lookupColumn(label)},tableColSum:function(table,col,startRow,endRow){return table.sumColumn(col,startRow,endRow)},tableMergeValues:function(table,rowOrCol,rowColNum,startRange,endRange,separator){if(rowOrCol==="row"){return table.mergeRowValues(rowColNum,startRange,endRange,separator)}else{return table.mergeColumnValues(rowColNum,startRange,endRange,separator)}},tableSearch:function(table,key,rowOrCol,rowColNum,startRange,endRange,predicate){if(rowOrCol==="row"){return table.searchRow(key,rowColNum,startRange,endRange,predicate)}else{return table.searchColumn(key,rowColNum,startRange,endRange,predicate)}},setVariable:function(key,value){if(this.useFastReference){this.fastReferenceValue=value}else{this.vars[key]=value}},reduce:function(tree){if(typeof tree!=="object"){return tree}switch(tree.kind){case"operation":var operands=tree.operands;for(var i=0;i&lt;operands.length;i++){if(this.canReduce(operands[i])){tree.operands[i]=this.evaluate(operands[i])}else{tree.operands[i]=this.reduce(operands[i])}}if(this.canReduce(tree)){return this.evaluate(tree)}return tree;case"reference":return tree;case"literal":return tree.literal;default:gs.Log.strict("Expression evaluation error in:",this.original,"\nNode kind unknown");return this.defaultValue}},canReduce:function(tree){if(typeof tree!=="object"){return true}switch(tree.kind){case"operation":if(tree.operation==="random"){return false}var operands=tree.operands;for(var i=0;i&lt;operands.length;i++){if(!this.canReduce(operands[i])){return false}}return true;case"reference":return false;case"literal":return true;default:gs.Log.strict("Expression evaluation error in:",this.original,"\nNode kind unknown");return false}},assertOperandCount:function(operation,operands,expected){var actual=operands.length;if(actual!==expected){gs.Log.strict("Expression evaluation error in:",this.original,"\nWrong number of arguments to",operation,"\nExpected",expected,"but received",actual)}},evaluate:function(tree){if(tree===undefined){gs.Log.strict("Expression evaluation error in:",this.original,"\nA value was undefined");return this.defaultValue}else if(typeof tree!=="object"){return tree}else{switch(tree.kind){case"operation":var op=tree.operation;var operands=tree.operands;var operandCount=tree.operandCount;var operandIsObject=tree.operandIsObject;var a,b,c,d,e,f,g;a=operandIsObject[0]?this.evaluate(operands[0]):operands[0];if(operandCount&gt;1){b=operandIsObject[1]?this.evaluate(operands[1]):operands[1];if(operandCount&gt;2){c=operandIsObject[2]?this.evaluate(operands[2]):operands[2];if(operandCount&gt;3){d=operandIsObject[3]?this.evaluate(operands[3]):operands[3];if(operandCount&gt;4){e=operandIsObject[4]?this.evaluate(operands[4]):operands[4];if(operandCount&gt;5){f=operandIsObject[5]?this.evaluate(operands[5]):operands[5];if(operandCount&gt;6){g=operandIsObject[6]?this.evaluate(operands[6]):operands[6]}}}}}}switch(op){case"negate":return 0-a;case"abs":return Math.abs(a);case"sqrt":return Math.sqrt(a);case"sin":return this.sin(a);case"cos":return this.cos(a);case"tan":return this.tan(a);case"asin":return this.asin(a);case"acos":return this.acos(a);case"atan":return this.atan(a);case"ceil":return Math.ceil(a);case"floor":return Math.floor(a);case"round":return Math.floor(a+.5);case"roundTo":return this.roundTo(a,b);case"log10":return this.log10(a);case"ln":return Math.log(a);case"exp":return Math.exp(a);case"+":return Number(a)+Number(b);case"-":return a-b;case"*":return a*b;case"/":return a/b;case"^":return Math.pow(a,b);case"concatenate":return""+a+b;case"random":return this.random(a,b);case"max":return a&lt;b?b:a;case"min":return a&lt;b?a:b;case"vectorToAngle":return this.vectorToAngle(a,b);case"magnitude":return this.magnitude(a,b);case"pow":return Math.pow(a,b);case"mod":return this.lua_mod(a,b);case"legacy_mod":return this.legacy_mod(a,b);case"prec":return this.prec(a,b);case"padReal":return this.padReal(a,b,c);case"padInt":return this.padInt(a,b,c);case"tableCellValue":return this.tableCellValue(a,b,c);case"tableColCount":return this.tableColCount(a);case"tableColNumber":return this.tableColNumber(a,b);case"tableRowCount":return this.tableRowCount(a);case"tableRowNumber":return this.tableRowNumber(a,b);case"tableColSum":return this.tableColSum(a,b,c,d);case"tableMergeValues":return this.tableMergeValues(a,b,c,d,e,f);case"tableSearch":return this.tableSearch(a,b,c,d,e,f,g);case"textFind":return this.textFind(a,b,c);case"textLength":return this.textLength(a);case"textRepeat":return this.textRepeat(a,b);case"textReplace":return this.textReplace(a,b,c);case"textReplaceAll":return this.textReplaceAll(a,b,c);case"textSubStr":return this.textSubStr(a,b,c);default:gs.Log.strict("Expression evaluation error in:",this.original,"\nUnrecognized operation",op);return this.defaultValue}case"reference":var value=this.vars[tree.reference];if(value===undefined){gs.Log.strict("Expression reference error in:",this.original,"\nThe variable ",tree.reference," has no value");return this.defaultValue}return value;case"literal":return tree.literal;default:gs.Log.strict("Expression evaluation error in:",this.original,"\nUnrecognized kind",tree.kind);return this.defaultValue}}},evaluateRoot:function(){if(this.useConstant){return this.constantValue}if(this.useFastReference){return this.fastReferenceValue}if(this.useFastRandom){return this.fastRandom(this.fastRandomA,this.fastRandomB)}return this.evaluate(this.root)},normalize:function(tree){if(typeof tree==="object"&amp;&amp;tree.kind==="operation"){var count=tree.operands.length;tree.operandCount=count;tree.operandIsObject=gs.array.provide();for(var i=0;i&lt;count;i++){this.normalize(tree.operands[i]);tree.operandIsObject[i]=typeof tree.operands[i]==="object"}}}};gs.BehaviorBase=function(){gs.ObjectWithImmutableAttributes.call(this)};gs.BehaviorBase.prototype={isImmutable:function(){return false},start:function(actor,timestamp){},stop:function(actor,timestamp){},didEnter:function(actor,isInitTime){},willExit:function(actor){},everyFrame:function(actor){},registerForEveryFrame:function(actor){actor.registerForEveryFrame(this)},deregisterForEveryFrame:function(actor){actor.deregisterForEveryFrame(this)},getRequiredAssets:function(imageSet,soundSet,fontSet,strategy){},getRequiredActors:function(actorSet,spawnableActorsOnly){},resolveTableReferenceAttribute:function(referenceAttribute){return gs.Game.current.getTableAttribute(referenceAttribute.getValue())},doStub:function(area,action,args){if(args===undefined){args=null}gs.Game.current.project.deferAction(area,action,args)},loadFromLite:function(node,initialState){var attributes=node["attributes"];if(attributes){this.attributes.loadFromLite(attributes,initialState)}}};gs.inherits(gs.BehaviorBase,gs.ObjectWithImmutableAttributes);gs.ImmutableBehavior=function(){gs.ImmutableAttributeCollection.call(this);this.attributes=this};gs.ImmutableBehavior.prototype={isImmutable:function(){return true},init:function(){this.declareAttributes(this);return this},declareAttributes:function(attributes){},clone:function(){return this},start:function(actor,timestamp){},stop:function(actor,timestamp){},didEnter:function(actor,isInitTime){},willExit:function(actor){},everyFrame:function(actor){},registerForEveryFrame:function(actor){actor.registerForEveryFrame(this)},deregisterForEveryFrame:function(actor){actor.deregisterForEveryFrame(this)},getRequiredAssets:function(imageSet,soundSet,fontSet,strategy){},getRequiredActors:function(actorSet,spawnableActorsOnly){},loadFromLite:function(node,initialState){var attributes=node["attributes"];if(attributes){var superclass=gs.ImmutableAttributeCollection.prototype;superclass.loadFromLite.call(this,attributes,initialState)}},resolveTableReferenceAttribute:function(referenceAttribute){var keypath=referenceAttribute.getValue();if(!keypath){return null}return gs.Game.current.getTableAttribute(keypath)},doStub:function(area,action,args){if(args===undefined){args=null}gs.Game.current.project.deferAction(area,action,args)}};gs.inherits(gs.ImmutableBehavior,gs.ImmutableAttributeCollection);gs.SingletonBehavior=function(){gs.ImmutableBehavior.call(this)};gs.SingletonBehavior.prototype={loadFromLite:function(node,initialState){}};gs.inherits(gs.SingletonBehavior,gs.ImmutableBehavior);gs.StatelessBehavior=function(){gs.ImmutableBehavior.call(this)};gs.StatelessBehavior.prototype={};gs.inherits(gs.StatelessBehavior,gs.ImmutableBehavior);gs.MutableBehavior=function(){gs.BehaviorBase.call(this)};gs.MutableBehavior.prototype={isImmutable:function(){return false}};gs.inherits(gs.MutableBehavior,gs.BehaviorBase);gs.KeyValuePair=gs.PrototypicalImmutableObject.subclass("KeyValuePair");gs.KeyValuePair.init=function(){gs.PrototypicalImmutableObject.init.call(this);this.attributes.addVariantExpressionAttribute("key","");this.attributes.addVariantExpressionAttribute("value","");return this};gs.KeyValuePair.entity=function(){return this.tableBehavior()._entity};gs.KeyValuePair.tableBehavior=function(){return this._parent._parent};gs.Behavior=gs.PrototypicalImmutableObject.subclass("Behavior");gs.Behavior.isImmutable=function(){return false};gs.Behavior.start=function(actor,timestamp){};gs.Behavior.stop=function(actor,timestamp){};gs.Behavior.didEnter=function(actor,isInitTime){this._entity=actor};gs.Behavior.willExit=function(actor){if(this.attributes){this.attributes.releaseExpressionInputs()}this._entity=null};gs.Behavior.registerForEveryFrame=function(){this._entity.registerForEveryFrame(this)};gs.Behavior.deregisterForEveryFrame=function(){this._entity.deregisterForEveryFrame(this)};gs.Behavior.everyFrame=function(actor,timestamp){};gs.Behavior.getRequiredAssets=gs.NOOP_FUNCTION;gs.Behavior.getRequiredActors=gs.NOOP_FUNCTION;gs.Behavior.getUniqueKey=function(){if(!this._uniqueKey){this._uniqueKey=gs.ObjectBase.generateUniqueObjectKey()}return this._uniqueKey};gs.Behavior.resolveTableReferenceAttribute=function(referenceAttribute){return gs.Game.current.getTableAttribute(referenceAttribute.getValue())};gs.Behavior.doStub=function(area,action,args){if(args===undefined){args=null}gs.Game.current.project.deferAction(area,action,args)};gs.CompoundBehavior=gs.Behavior.subclass("CompoundBehavior");gs.CompoundBehavior.init=function(){gs.Behavior.init.call(this);this.behaviors=new gs.BehaviorList;this.behaviors._parent=this;return this};gs.CompoundBehavior.initPrime=function(){this.attributes=null;this.behaviors=null;return this};gs.CompoundBehavior.clone=function(){var other=gs.Behavior.clone.call(this);other.behaviors=this.behaviors.clone();other.behaviors._parent=other;return other};gs.CompoundBehavior.start=function(actor,timestamp){this.behaviors.start(actor,timestamp)};gs.CompoundBehavior.stop=function(actor,timestamp){this.behaviors.stop(actor,timestamp)};gs.CompoundBehavior.didEnter=function(actor,isInitTime){gs.Behavior.didEnter.call(this,actor,isInitTime);this.behaviors.didEnter(actor,isInitTime)};gs.CompoundBehavior.willExit=function(actor){this.behaviors.willExit(actor);gs.Behavior.willExit.call(this,actor)};gs.CompoundBehavior.loadFromLite=function(node,initialState){gs.Behavior.loadFromLite.call(this,node,initialState);var behaviors=node["behaviors"];if(behaviors){this.behaviors.loadFromLite(behaviors,initialState)}};gs.CompoundBehavior.loadFromTable=function(t,initialState){gs.Behavior.loadFromTable.call(this,t,initialState);var gs_JXON=gs.JXON;var gs_JXON__children=gs_JXON._children;var gs_Project_nodeTypeNameMap=gs.Project.nodeTypeNameMap;var children=t[gs_JXON__children];if(children){for(var i=0,iend=children.length;i&lt;iend;i++){var child=children[i];var tag=gs_Project_nodeTypeNameMap[child[gs_JXON._type]];if(tag==="behaviors"){this.behaviors.loadFromTable(child[gs_JXON__children],initialState);break}}}};gs.CompoundBehavior.getRequiredAssets=function(imageSet,soundSet,fontSet,strategy){return this.behaviors.getRequiredAssets(imageSet,soundSet,fontSet,strategy)};gs.CompoundBehavior.getRequiredActors=function(actorSet,spawnableActorsOnly){this.behaviors.getRequiredActors(actorSet,spawnableActorsOnly)};gs.CompletingBehavior=gs.Behavior.subclass("CompletingBehavior");gs.CompletingBehavior.init=function(){gs.Behavior.init.call(this);this.attributes.addBooleanImmutableAttribute("runToCompletion",false);this._running=false;this._completed=false;return this};gs.CompletingBehavior.completed=function(){return this._completed};gs.CompletingBehavior.setCompleted=function(completed){this._completed=completed};gs.CompletingBehavior.completeStart=function(actor,timestamp){this.registerForEveryFrame()};gs.CompletingBehavior.completeEvaluate=function(actor,timestamp){};gs.CompletingBehavior.completeStop=function(actor,timestamp){this._running=false};gs.CompletingBehavior.start=function(actor,timestamp){if(!this._running){this._completed=false;this.completeStart(actor,timestamp);this._running=true;this.completeEvaluate(actor,timestamp)}};gs.CompletingBehavior.everyFrame=function(actor,timestamp){if(this._completed){this.completeStop(actor,timestamp);this.deregisterForEveryFrame()}else{this.completeEvaluate(actor,timestamp)}};gs.CompletingBehavior.stop=function(actor,timestamp){if(this._running&amp;&amp;!this.attributes.runToCompletion.getValue()){this.completeStop(actor,timestamp);this.deregisterForEveryFrame()}};gs.CompletingBehavior.willExit=function(actor){if(this._running){this.completeStop(actor);this.deregisterForEveryFrame()}gs.Behavior.willExit.call(this,actor)};gs.BehaviorList=function(){this.count=0;this.immutable=true};gs.BehaviorList.prototype={clone:function(){if(this.immutable){return this}var other=new gs.BehaviorList;other.count=this.count;for(var i=0;i&lt;this.count;i++){other[i]=this[i].clone();other[i]._parent=other}return other},start:function(actor,timestamp){for(var i=0;i&lt;this.count;i++){this[i].start(actor,timestamp)}},stop:function(actor,timestamp){for(var i=0;i&lt;this.count;i++){this[i].stop(actor,timestamp)}},didEnter:function(actor,isInitTime){for(var i=0;i&lt;this.count;i++){this[i].didEnter(actor,isInitTime)}},willExit:function(actor){for(var i=0;i&lt;this.count;i++){this[i].willExit(actor)}},getRequiredAssets:function(imageSet,soundSet,fontSet,strategy){for(var i=0;i&lt;this.count;i++){this[i].getRequiredAssets(imageSet,soundSet,fontSet,strategy)}},getRequiredActors:function(actorSet,spawnableActorsOnly){for(var i=0;i&lt;this.count;i++){this[i].getRequiredActors(actorSet,spawnableActorsOnly)}},loadFromLite:function(node,initialState){var parseBehaviorClass=gs.Parser.parseBehaviorClass;var behavior;if(Array.isArray(node)){this.count=node.length;for(var i=0;i&lt;node.length;i++){behavior=parseBehaviorClass(node[i]);behavior.loadFromLite(node[i],initialState);behavior._objectKey=node[i]["id"];behavior._parent=this;this[i]=behavior;this.immutable=this.immutable&amp;&amp;behavior.isImmutable()}}else{this.count=1;behavior=parseBehaviorClass(node);behavior.loadFromLite(node,initialState);behavior._objectKey=node["id"];behavior._parent=this;this[0]=behavior;this.immutable=this.immutable&amp;&amp;behavior.isImmutable()}}};gs.inherits(gs.BehaviorList,Object);gs.AccelerateBehavior=gs.Behavior.subclass("AccelerateBehavior",{init:function(){gs.Behavior.init.call(this);this.attributes.addRealExpressionAttribute("direction",0);this.attributes.addIntegerImmutableAttribute("space",gs.MoveBehavior.SPACE_ACTOR);this.attributes.addRealExpressionAttribute("acceleration",100);return this},start:function(actor,timestamp){this.registerForEveryFrame();this.actor=actor;this.attributes.direction.addObserver(this);this.attributes.acceleration.addObserver(this)},stop:function(actor,timestamp){this.deregisterForEveryFrame();this.attributes.direction.removeObserver(this);this.attributes.acceleration.removeObserver(this)},everyFrame:function(actor,timestamp){var body=actor.aspects.motion._body;if(body){var space=this.attributes.space.getValue();var directionDeg=this.attributes.direction.getValue();if(space===gs.MoveBehavior.SPACE_ACTOR){directionDeg+=this.actor.attributes.rotation.getValue()}var directionRad=directionDeg*gsMath.DEG2RAD;var dx=Math.cos(directionRad);var dy=Math.sin(directionRad);var acceleration=this.attributes.acceleration.getValue();var ma=body.getMass()*acceleration;var force=gs.g_tempVec2d;force[0]=dx*ma;force[1]=dy*ma;var center=body.getWorldCenter();body.applyForce(force,center)}}});gs.AccelerateTowardBehavior=gs.Behavior.subclass("AccelerateTowardBehavior");gs.AccelerateTowardBehavior.init=function(){gs.Behavior.init.call(this);this.attributes.addPointExpressionAttribute("position",0,0);this.attributes.addIntegerImmutableAttribute("space",gs.MoveBehavior.SPACE_SCENE);this.attributes.addRealExpressionAttribute("acceleration",100);return this};gs.AccelerateTowardBehavior.start=function(actor,timestamp){this.registerForEveryFrame()};gs.AccelerateTowardBehavior.stop=function(actor,timestamp){this.deregisterForEveryFrame()};gs.AccelerateTowardBehavior.everyFrame=function(actor,timestamp){var actor=this._entity;var body=actor.aspects.motion._body;if(body){var space=this.attributes.space.getValue();var positionX=this.attributes.position.x.getValue();var positionY=this.attributes.position.y.getValue();var forceVector=gs.g_tempVec2d;forceVector[0]=positionX;forceVector[1]=positionY;if(space===gs.MoveBehavior.SPACE_ACTOR){var rotation=actor.attributes.rotation.getValue();gs.Vector2.vectorRotate2D(forceVector,forceVector,rotation*Math.PI/180)}else{var actorPositionX=actor.attributes.position.x.getValue();var actorPositionY=actor.attributes.position.y.getValue();forceVector[0]=forceVector[0]-actorPositionX;forceVector[1]=forceVector[1]-actorPositionY}var length=Math.sqrt(forceVector[0]*forceVector[0]+forceVector[1]*forceVector[1]);if(length&gt;0){forceVector[0]=forceVector[0]/length;forceVector[1]=forceVector[1]/length}else{forceVector[0]=0;forceVector[1]=0}var mass=body.getMass();var acceleration=this.attributes.acceleration.getValue();var multiplicand=mass*acceleration;forceVector[0]=forceVector[0]*multiplicand;forceVector[1]=forceVector[1]*multiplicand;var center=body.getWorldCenter();body.applyForce(forceVector,center)}};gs.AddRemoveRowAction=function(){gs.StatelessBehavior.call(this)};gs.AddRemoveRowAction.Command={ADD_ROW:0,REMOVE_ROW:1};gs.AddRemoveRowAction.Location={AT_BEGINNING:0,AT_END:1,AT_INDEX:2};gs.AddRemoveRowAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("tableID","");attributes.addIntegerImmutableAttribute("command",0);attributes.addIntegerImmutableAttribute("location",0);attributes.addStringExpressionAttribute("index","")},start:function(actor,timestamp){if(!this.targetTable){this.targetTable=this.resolveTableReferenceAttribute(this.attributes.tableID)}var command=this.attributes.command.getValue();var location=this.attributes.location.getValue();var index;switch(location){case gs.AddRemoveRowAction.Location.AT_BEGINNING:index=1;break;case gs.AddRemoveRowAction.Location.AT_END:index=-1;break;case gs.AddRemoveRowAction.Location.AT_INDEX:index=this.attributes.index.getValueForEntityStateless(actor);break;default:break}if(this.targetTable){switch(command){case gs.AddRemoveRowAction.Command.ADD_ROW:this.targetTable.addRow(index);break;case gs.AddRemoveRowAction.Command.REMOVE_ROW:this.targetTable.removeRow(index);break;default:break}}}};gs.inherits(gs.AddRemoveRowAction,gs.StatelessBehavior);gs.AnimateBehavior=function(){this.__superclass.call(this)};gs.AnimateBehavior.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("images","");attributes.addIntegerImmutableAttribute("speed",10);attributes.addBooleanImmutableAttribute("loop",true);attributes.addBooleanImmutableAttribute("restoreActorImage",true)},clone:function(){var other=this.__super.clone.call(this);other._imagesArray=this._imagesArray;other._timePerFrame=this._timePerFrame;return other},nextFrame:function(actor){this._currentImageIndex++;if(this._currentImageIndex===this._imagesArray.length){if(this._loop){this._currentImageIndex=0}else{this.stop(actor,null);return}}var currentImage=this._imagesArray[this._currentImageIndex];actor.attributes.image.fastSetValue(currentImage)},start:function(actor,timestamp){if(this._imagesArray.length===0){return}if(!this._timebase){this._timebase=gs.Timebase.provide()}this._timebase.initWithTime(timestamp);this._timebase.convertTimeStamp(timestamp);this._animationTime=this._timebase.getTimeStamp();this._savedActorImage=actor.attributes.image.getValue();this._loop=this.attributes.loop.getValue();this._currentImageIndex=-1;this._timeOfLastFrame=this._animationTime.time;this.nextFrame(actor);this.registerForEveryFrame(actor)},stop:function(actor,timestamp){this.deregisterForEveryFrame(actor);if(!this._imagesArray){return}if(this.attributes.restoreActorImage.getValue()&amp;&amp;this._savedActorImage){actor.attributes.image.fastSetValue(this._savedActorImage)}this._animationTime=null;if(this._timebase){gs.Timebase.recycle(this._timebase);this._timebase=null}this._loop=null;this._timeOfLastFrame=null;this._currentImageIndex=null;this._savedActorImage=null},everyFrame:function(actor,timestamp){if(!this._imagesArray){return}this._timebase.convertTimeStamp(timestamp);var elapsedTime=this._animationTime.time-this._timeOfLastFrame;if(elapsedTime&gt;=this._timePerFrame){this._timeOfLastFrame=this._animationTime.time;this.nextFrame(actor)}},getRequiredAssets:function(imageSet,soundSet,fontSet,strategy){var images=this._imagesArray;for(var i=0,iend=images.length;i&lt;iend;i++){var image=images[i];imageSet[image]=true}},loadFromLite:function(node,initialState){this.__super.loadFromLite.call(this,node,initialState);var images=this.attributes.images.getValue();this._imagesArray=images.split("\t");this._timePerFrame=1/this.attributes.speed.getValue()}};gs.inherits(gs.AnimateBehavior,gs.MutableBehavior);gs.BuzzAction=function(){gs.SingletonBehavior.call(this)};gs.BuzzAction.prototype={start:function(actor,timestamp){if(gs.globalOptions.supportsVibrate){var vibrate=navigator.vibrate||navigator.mozVibrate;vibrate.call(navigator,400)}if(gs.globalOptions.exitOnBuzz){window.close()}}};gs.inherits(gs.BuzzAction,gs.SingletonBehavior);gs.singleton(gs.BuzzAction);gs.CallExternalFunctionAction=gs.Behavior.subclass("CallExternalFunctionAction",{inputAttributeKeys:["input1","input2","input3","input4","input5","input6","input7","input8","input9","input10"],init:function(){gs.Behavior.init.call(this);this.attributes.addStringImmutableAttribute("functionName","");this.attributes.addIntegerImmutableAttribute("numberOfInputs",0);this.attributes.addStringImmutableAttribute("returnAttribute","");this.attributes.addVariantExpressionAttribute("input1","");this.attributes.addVariantExpressionAttribute("input2","");this.attributes.addVariantExpressionAttribute("input3","");this.attributes.addVariantExpressionAttribute("input4","");this.attributes.addVariantExpressionAttribute("input5","");this.attributes.addVariantExpressionAttribute("input6","");this.attributes.addVariantExpressionAttribute("input7","");this.attributes.addVariantExpressionAttribute("input8","");this.attributes.addVariantExpressionAttribute("input9","");this.attributes.addVariantExpressionAttribute("input10","");this.attributes.addStringImmutableAttribute("notes","");return this},start:function(actor,timestamp){var functionName=this.attributes.functionName.getValue();var numberOfInputs=this.attributes.numberOfInputs.getValue();var parameters=[];for(var i=0;i&lt;numberOfInputs;i++){var inputAttributeKey=this.inputAttributeKeys[i];var inputAttribute=this.attributes[inputAttributeKey];parameters.push(inputAttribute.getValue())}switch(functionName){case"registerOptions":var tableKeypath=parameters[0];if(typeof tableKeypath!=="string"){tableKeypath=gs.tables.getKeypath(tableKeypath._objectKey)}var attributeKeypath=this.attributes.returnAttribute.getValue();var game=gs.Game.instance;game.eventCenter.registerForEvent("externalWriteGameAttribute",game,"externalWriteGameAttribute");try{gs.externalDelegate.registerOptions(tableKeypath,attributeKeypath)}catch(exception){gs.Log.warn("ExternalFunctionCall ignored:",functionName)}break}}});gs.ChangeAttributeAction=function(){gs.StatelessBehavior.call(this)};gs.ChangeAttributeAction.prototype={declareAttributes:function(attributes){attributes.addReferenceImmutableAttribute("targetAttribute");attributes.addVariantExpressionAttribute("RHS","")},start:function(actor,timestamp){var targetAttributeReference=this.attributes.targetAttribute.getValue();if(targetAttributeReference){var targetAttribute=targetAttributeReference.resolveRelativeTo(actor);if(targetAttribute){var rvalue=this.attributes.RHS.getValueForEntityStateless(actor);if(rvalue!==undefined){if(targetAttribute._isRotationAttribute){var motionAspectAttributes=actor.aspects.motion.attributes;var com=motionAspectAttributes.centerOfMass;var pin=motionAspectAttributes.pin.getValue();if(com.x._value!==0||com.y._value!==0||pin){actor._targetRotation=rvalue}else{targetAttribute.setValue(rvalue)}}else{targetAttribute.setValue(rvalue)}}}}}};gs.inherits(gs.ChangeAttributeAction,gs.StatelessBehavior);gs.ChangeImageAction=function(){gs.StatelessBehavior.call(this)};gs.ChangeImageAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("image","")},start:function(actor,timestamp){var imageName=this.attributes.image.getValue();actor.attributes.image.setValue(imageName)},getRequiredAssets:function(imageSet,soundSet,fontSet,strategy){var imageName=this.attributes.image.getValue();if(imageName&amp;&amp;imageName.length&gt;0){imageSet[imageName]=true}}};gs.inherits(gs.ChangeImageAction,gs.StatelessBehavior);gs.ChangeRowAction=gs.Behavior.subclass("ChangeRowAction",{init:function(){gs.Behavior.init.call(this);this.attributes.addStringImmutableAttribute("table","");this.attributes.addIntegerImmutableAttribute("row",0);this.setObjectForKey(gs.PrototypicalArray.provide().init(),"tableColumns");this.tableColumns.addObjectAtIndex(gs.KeyValuePair.provide().init());return this},start:function(actor,timestamp){var tableKeypath=this.attributes.table.getValue();if(!tableKeypath){return}var reference=gs.Reference.lookup(tableKeypath);var target=reference.resolveRelativeTo(this._entity);if(!target){gs.Log.warn("Table does not exist:",this.attributes.table.getValue());return}if(target._type==="table"){var rowStr=String(this.attributes.row.getValue());var columns=this.tableColumns;for(var i=0;i&lt;columns.array.length;i++){var column=columns.array[i];var colStr=String(column.attributes.key.getValue());var rValue=String(column.attributes.value.getValue());target.setCell(rowStr,colStr,rValue)}}},loadFromLite:function(node,initialState){debugger},loadFromTable:function(t,initialState){gs.Behavior.loadFromTable.call(this,t,initialState);if(this.tableColumns.array[0]!=null){this.tableColumns.removeObjectAtIndex(0)}var table=gs.JXON.children(t);if(!table){return}var itemCount=table.length;for(var i=0;i&lt;itemCount;++i){var node=table[i];var nodetype=gs.Project.nodeTypeNameMap[gs.JXON.tag(node)];if(nodetype==="tablecolumns"){this.tableColumns.loadFromTable(gs.JXON.children(node),initialState)}}}});gs.ChangeSceneAction=function(){gs.StatelessBehavior.call(this)};gs.ChangeSceneAction.NEXT="next";gs.ChangeSceneAction.PREVIOUS="prev";gs.ChangeSceneAction.INDEX="index";gs.ChangeSceneAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("sceneKey",gs.ChangeSceneAction.NEXT);attributes.addIntegerImmutableAttribute("enableAdvertisement",0);attributes.addIntegerExpressionAttribute("index",1)},loadScene:function(actor,timestamp){var newSceneKey=this.attributes.sceneKey.getValue();var enableAdvertisement=this.attributes.enableAdvertisement.getValue();var game=gs.Game.current;var currentScene=game.getCurrentScene();var currentSceneIndex=game.scenes.indexAndKey(currentScene._objectKey);var numberOfScenes=game.scenes.numberOfScenes();var newSceneIndex;if(newSceneKey===gs.ChangeSceneAction.NEXT){newSceneIndex=currentSceneIndex+1;if(newSceneIndex&gt;=numberOfScenes){newSceneIndex=0}newSceneKey=game.scenes.keyForScene(newSceneIndex)}else if(newSceneKey===gs.ChangeSceneAction.PREVIOUS){newSceneIndex=currentSceneIndex-1;if(newSceneIndex&lt;0){newSceneIndex=numberOfScenes-1}newSceneKey=game.scenes.keyForScene(newSceneIndex)}else if(newSceneKey===gs.ChangeSceneAction.INDEX){newSceneIndex=this.attributes.index.getValueForEntityStateless(actor)-1;newSceneKey=game.scenes.keyForScene(newSceneIndex)}game.eventCenter.postEvent("changeToScene",null,newSceneKey,enableAdvertisement);gs.EngineContext.current.delegate.onSceneAboutToChange(newSceneKey,"",enableAdvertisement)},start:function(actor,timestamp){var game=gs.Game.current;if(!game.loadingFlag){this.loadScene(actor,timestamp)}else{this.registerForEveryFrame(actor)}},everyFrame:function(actor,timestamp){var game=gs.Game.current;if(!game.loadingFlag){this.deregisterForEveryFrame(actor);this.loadScene(actor,timestamp)}}};gs.inherits(gs.ChangeSceneAction,gs.StatelessBehavior);gs.ChangeTableValueAction=function(){gs.StatelessBehavior.call(this)};gs.ChangeTableValueAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("tableID","");attributes.addVariantExpressionAttribute("tableExpression",null);attributes.addStringExpressionAttribute("rowNumber","");attributes.addReservedCompoundAttribute("assignments","array",null,true)},start:function(actor,timestamp){var table=this.targetTable;if(!table){var tableID=this.attributes.tableID.getValue();if(tableID){table=this.resolveTableReferenceAttribute(this.attributes.tableID)}else{table=this.attributes.tableExpression.getValueForEntityStateless(actor)}this.targetTable=table;if(!table){return}}var row=this.attributes.rowNumber.getValueForEntityStateless(actor);var rowOffset=table.lookupRow(row);var assignments=this.attributes.assignments;var size=assignments.size();for(var index=1;index&lt;=size;index++){var pair=assignments.at(index);var column=pair.first.getValueForEntityStateless(actor);var columnOffset=table.lookupColumn(column);var value=pair.second.getValueForEntityStateless(actor);table.setCell(rowOffset,columnOffset,value)}}};gs.inherits(gs.ChangeTableValueAction,gs.StatelessBehavior);gs.ChangeVelocityAction=gs.Behavior.subclass("ChangeVelocityAction");gs.ChangeVelocityAction.SPACE_ACTOR=0;gs.ChangeVelocityAction.SPACE_SCENE=1;gs.ChangeVelocityAction.init=function(){gs.Behavior.init.call(this);this.attributes.addRealExpressionAttribute("direction",0);this.attributes.addIntegerImmutableAttribute("space",gs.ChangeVelocityAction.SPACE_ACTOR);this.attributes.addRealExpressionAttribute("speed",300);return this};gs.ChangeVelocityAction.start=function(actor,timestamp){var speed=this.attributes.speed.getValue();var direction=this.attributes.direction.getValue();this.calculateVelocity(speed,direction)};gs.ChangeVelocityAction.calculateVelocity=function(newSpeed,newDirection){var actor=this._entity;var space=this.attributes.space.getValue();var velocity=gs.g_tempVec2d;if(space===gs.ChangeVelocityAction.SPACE_ACTOR){var actorRotation=actor.attributes.rotation.getValue();var newRotation=newDirection+actorRotation;while(newRotation&lt;0){newRotation+=360}while(newRotation&gt;360){newRotation-=360}var radians=newRotation*(Math.PI/180);velocity[0]=Math.cos(radians);velocity[1]=Math.sin(radians)}else if(space===gs.ChangeVelocityAction.SPACE_SCENE){var radians=newDirection*(Math.PI/180);velocity[0]=Math.cos(radians);velocity[1]=Math.sin(radians)}var motionAspect=actor.aspects.motion;velocity[0]=velocity[0]*newSpeed;velocity[1]=velocity[1]*newSpeed;motionAspect.attributes.linearVelocity.x.setValue(velocity[0]);motionAspect.attributes.linearVelocity.y.setValue(velocity[1])};gs.CollideBehavior=function(){gs.StatelessBehavior.call(this)};gs.CollideBehavior.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("prototypeKey","");attributes.addStringImmutableAttribute("actorTag","");attributes.addIntegerImmutableAttribute("mode",gs.CollisionPredicate.PROTOTYPE_MODE)},filterCategory:function(){var mode=this.attributes.mode.getValue();if(mode===gs.CollisionPredicate.PROTOTYPE_MODE){var prototypeKey=this.attributes.prototypeKey.getValue();return prototypeKey}else{return this.attributes.actorTag.getValue()}},start:function(actor,timestamp){var category=this.filterCategory();if(!category){return}var scene=actor.scene;if(!actor.aspects.physics.waitForImageBeforeFixtureLoad(actor)){scene._collisionController.addActorCollision(actor,category)}var imageName=actor.attributes.image.getValue();var image=gs.AssetManager.current.imageForName(imageName);image.registerOnLoadCallback(function(){scene._collisionController.addActorCollision(actor,category)})},stop:function(actor,timestamp){var category=this.filterCategory();if(!category){return}var scene=actor.scene;scene._collisionController.removeActorCollision(actor,category)}};gs.inherits(gs.CollideBehavior,gs.StatelessBehavior);gs.ConstrainAttributeBehavior=gs.Behavior.subclass("ConstrainAttributeBehavior",{init:function(){gs.Behavior.init.call(this);this.attributes.addReferenceImmutableAttribute("targetAttribute");this.attributes.addVariantExpressionAttribute("RHS","");return this},start:function(actor,timestamp){var reference=this.attributes.targetAttribute.getValue();if(reference&amp;&amp;reference.keypath.indexOf("scene")&gt;-1){this.targetAttribute=null}if(!this.targetAttribute){if(!reference){return}this.targetAttribute=reference.resolveRelativeTo(actor)}if(!this.targetAttribute){gs.Log.debug("Degenerate ConstrainAttributeBehavior");return}var value=this.attributes.RHS.getValue();this.targetAttribute.setValue(value);this.registerForEveryFrame(actor)},stop:function(actor,timestamp){this.deregisterForEveryFrame(actor)},everyFrame:function(actor,timestamp){var rvalue=this.attributes.RHS.getValueForEntityStateless(actor);if(rvalue!==undefined){this.targetAttribute.setValue(rvalue)}}});gs.ControlCameraBehavior=gs.Behavior.subclass("ControlCameraBehavior");gs.ControlCameraBehavior.start=function(actor,timestamp){if(actor.layer.scrollable()){gs.ControlCameraBehavior.cameraControl=this;var scene=actor.scene;this.scene=scene;this.trackingAreaWidth=scene.attributes.camera.trackingArea.width.getValue();this.trackingAreaHeight=scene.attributes.camera.trackingArea.height.getValue();this.cameraRect={x:scene.attributes.camera.origin.x.getValue(),y:scene.attributes.camera.origin.y.getValue(),width:scene.attributes.camera.size.width.getValue(),height:scene.attributes.camera.size.height.getValue()};this.sceneRect={x:0,y:0,width:Math.max(scene.attributes.size.width.getValue()-this.cameraRect.width,0),height:Math.max(scene.attributes.size.height.getValue()-this.cameraRect.height,0)};scene.attributes.camera.size.width.addObserver(this);scene.attributes.camera.size.height.addObserver(this);this.trackingRect={x:0,y:0,width:0,height:0};this.registerForEveryFrame()}};gs.ControlCameraBehavior.observeValueChange=function(attribute,value){var scene=this.scene;var camera=scene.attributes.camera;this.cameraRect.x=camera.origin.x.getValue();this.cameraRect.y=camera.origin.y.getValue();this.cameraRect.width=camera.size.width.getValue();this.cameraRect.height=camera.size.height.getValue();this.sceneRect.width=Math.max(scene.attributes.size.width.getValue()-this.cameraRect.width,0);this.sceneRect.height=Math.max(scene.attributes.size.height.getValue()-this.cameraRect.height,0)};gs.ControlCameraBehavior.stop=function(actor,timestamp){var scene=actor.scene;scene.attributes.camera.size.width.removeObserver(this);scene.attributes.camera.size.height.removeObserver(this);if(gs.ControlCameraBehavior.cameraControl===this){gs.ControlCameraBehavior.cameraControl=null}this.cameraRect=null;this.sceneRect=null;this.trackingRect=null;this.deregisterForEveryFrame()};gs.ControlCameraBehavior.everyFrame=function(actor,timestamp){if(gs.ControlCameraBehavior.cameraControl!==this){this.deregisterForEveryFrame();return}var scene=actor.scene;var positionAttr=actor.attributes.position;var targetX=positionAttr.x.getValue();var targetY=positionAttr.y.getValue();var cameraPosAttr=scene.attributes.camera.origin;var cameraRect=this.cameraRect;cameraRect.x=cameraPosAttr.x.getValue();cameraRect.y=cameraPosAttr.y.getValue();var trackingRect=this.trackingRect;trackingRect.width=this.trackingAreaWidth;trackingRect.height=this.trackingAreaHeight;var cameraCenterX=cameraRect.x+cameraRect.width*.5;var cameraCenterY=cameraRect.y+cameraRect.height*.5;trackingRect.x=cameraCenterX-this.trackingAreaWidth*.5;trackingRect.y=cameraCenterY-this.trackingAreaHeight*.5;if(!gs.Rect.pointInRect(targetX,targetY,trackingRect)){var temp=gs.Rect.nearestPointInRect(gs.g_tempVec2d,targetX,targetY,trackingRect);temp[0]=targetX-temp[0];temp[1]=targetY-temp[1];var newCameraX=cameraRect.x+temp[0];var newCameraY=cameraRect.y+temp[1];var finalCameraPos=gs.Rect.nearestPointInRect(gs.g_tempVec2d,newCameraX,newCameraY,this.sceneRect);cameraPosAttr.x.fastSetValue(finalCameraPos[0]);cameraPosAttr.y.fastSetValue(finalCameraPos[1])}};gs.CopyTableAction=gs.Behavior.subclass("CopyTableAction");gs.CopyTableAction.init=function(){gs.Behavior.init.call(this);this.attributes.addStringImmutableAttribute("tableID","");this.attributes.addStringImmutableAttribute("destinationTableID","");return this};gs.CopyTableAction.start=function(actor,timestamp){var sourceTable=this.attributes.tableID?this.resolveTableReferenceAttribute(this.attributes.tableID):null;var destTable=this.attributes.destinationTableID?this.resolveTableReferenceAttribute(this.attributes.destinationTableID):null;if(!sourceTable||!destTable){return}destTable.copyTable(sourceTable)};gs.DestroyAction=function(){gs.SingletonBehavior.call(this)};gs.DestroyAction.prototype={start:function(actor,timestamp){actor.hideActor();var scene=actor.scene;scene.markActorForDestruction(actor)}};gs.inherits(gs.DestroyAction,gs.SingletonBehavior);gs.singleton(gs.DestroyAction);gs.DisplayTextBehavior=gs.Behavior.subclass("DisplayTextBehavior");gs.DisplayTextBehavior.LEFT=0;gs.DisplayTextBehavior.CENTER=1;gs.DisplayTextBehavior.RIGHT=2;gs.DisplayTextBehavior.SPACE_ACTOR=0;gs.DisplayTextBehavior.SPACE_SCENE=1;gs.DisplayTextBehavior.init=function(){gs.Behavior.init.call(this);this.attributes.addStringExpressionAttribute("text","Hello world!");this.attributes.addStringImmutableAttribute("font","Arial");this.attributes.addRealImmutableAttribute("size",30);this.attributes.addBooleanImmutableAttribute("wrap",false);this.attributes.addIntegerImmutableAttribute("alignment",gs.DisplayTextBehavior.CENTER);this.attributes.addColorImmutableAttribute("color",1,1,1,1);this.attributes.addRealExpressionAttribute("offsetx",0);this.attributes.addRealExpressionAttribute("offsety",0);this.attributes.addIntegerImmutableAttribute("space",gs.DisplayTextBehavior.SPACE_ACTOR);this.attributes.addIntegerImmutableAttribute("directionSpace",gs.DisplayTextBehavior.SPACE_ACTOR);this.attributes.addRealExpressionAttribute("direction",0);return this};gs.DisplayTextBehavior.getRequiredAssets=function(imageSet,soundSet,fontSet,strategy){var fontName=this.attributes.font.getValue();if(fontName&amp;&amp;fontName.length&gt;0){fontSet[fontName]=true}};gs.DisplayTextBehavior.createNodesInSpace=function(parentSpace,nodeIndex){var textNode=parentSpace.createNode(gs.SGSpace.NodeType.SGText);this._textNode=textNode;var actorAttributes=this._entity.attributes;textNode.x=actorAttributes.position.x.getValue();textNode.y=actorAttributes.position.y.getValue();textNode.angleDeg=actorAttributes.rotation.getValue();textNode.width=actorAttributes.size.width.getValue();textNode.height=actorAttributes.size.height.getValue();this.updatePosition();var attributes=this.attributes;textNode.text=attributes.text.getValue();textNode.fontFamily=attributes.font.getValue();textNode.sizePx=attributes.size.getValue();textNode.alignment=attributes.alignment.getValue();textNode.wrap=attributes.wrap.getValue();textNode.colorR=attributes.color.red.getValue();textNode.colorG=attributes.color.green.getValue();textNode.colorB=attributes.color.blue.getValue();textNode.colorA=attributes.color.alpha.getValue();textNode.setLayer(nodeIndex);return 1};gs.DisplayTextBehavior.removeNodesFromSpace=function(parentSpace){parentSpace.removeNode(this._textNode);this._textNode=null};gs.DisplayTextBehavior.start=function(actor,timestamp){if(!this._entity.visible()){return}actor.addNodeSource(this);if(this._textNode){this._textNode.init()}this.attributes.text.addObserver(this);this.attributes.offsetx.addObserver(this);this.attributes.offsety.addObserver(this);this.attributes.direction.addObserver(this);actor.attributes.position.x.addObserver(this);actor.attributes.position.y.addObserver(this);actor.attributes.rotation.addObserver(this);actor.attributes.size.width.addObserver(this);actor.attributes.size.height.addObserver(this)};gs.DisplayTextBehavior.stop=function(actor,timestamp){if(!actor.visible()){return}actor.removeNodeSource(this);this.attributes.text.removeObserver(this);this.attributes.offsetx.removeObserver(this);this.attributes.offsety.removeObserver(this);this.attributes.direction.removeObserver(this);actor.attributes.position.x.removeObserver(this);actor.attributes.position.y.removeObserver(this);actor.attributes.rotation.removeObserver(this);actor.attributes.size.width.removeObserver(this);actor.attributes.size.height.removeObserver(this)};gs.DisplayTextBehavior.updatePosition=function(){var attributes=this.attributes;var actorAttributes=this._entity.attributes;var textNode=this._textNode;var x=attributes.offsetx.getValue();var y=attributes.offsety.getValue();if(attributes.space.getValue()===gs.DisplayTextBehavior.SPACE_ACTOR){if(x!==0||y!==0){var actorRotationDeg=actorAttributes.rotation.getValue();var actorRotationRad=actorRotationDeg*gsMath.DEG2RAD;var offsetAngleRad=Math.atan2(y,x);var offsetMagnitude=Math.sqrt(x*x+y*y);offsetAngleRad+=actorRotationRad;x=offsetMagnitude*Math.cos(offsetAngleRad);y=offsetMagnitude*Math.sin(offsetAngleRad)}x+=actorAttributes.position.x.getValue();y+=actorAttributes.position.y.getValue()}textNode.x=x;textNode.y=y;var rotationDeg=attributes.direction.getValue();if(attributes.directionSpace.getValue()===gs.DisplayTextBehavior.SPACE_ACTOR){rotationDeg+=actorAttributes.rotation.getValue()}textNode.angleDeg=rotationDeg;textNode.dirtyTransform=true};gs.DisplayTextBehavior.observeValueChange=function(attribute,newValue){var actorAttributes=this._entity.attributes;var textNode=this._textNode;if(!textNode){return}if(attribute===this.attributes.text){textNode.text=newValue;textNode.dirtyText=true}else if(attribute===actorAttributes.position.x){this.updatePosition()}else if(attribute===actorAttributes.position.y){this.updatePosition()}else if(attribute===actorAttributes.rotation){this.updatePosition()}else if(attribute===actorAttributes.size.width){textNode.width=newValue;textNode.dirtyTransform=true}else if(attribute===actorAttributes.size.height){textNode.height=newValue;textNode.dirtyTransform=true}else if(attribute===this.attributes.offsetx){this.updatePosition()}else if(attribute===this.attributes.offsety){this.updatePosition()}else if(attribute===this.attributes.direction){this.updatePosition()}};gs.EndGameAction=function(){gs.SingletonBehavior.call(this)};gs.EndGameAction.prototype={start:function(actor,timestamp){var game=gs.Game.instance;if("onEndGame"in gs.EngineContext.current.delegate){gs.EngineContext.current.delegate.onEndGame()}else{game.setNeedsToEndGame()}}};gs.inherits(gs.EndGameAction,gs.SingletonBehavior);gs.singleton(gs.EndGameAction);gs.GrowShrinkBehavior=gs.Behavior.subclass("GrowShrinkBehavior");gs.GrowShrinkBehavior.MINDIMENSION=1;gs.GrowShrinkBehavior.init=function(){gs.Behavior.init.call(this);this.attributes.addRealExpressionAttribute("growthRate",1);return this};gs.GrowShrinkBehavior.start=function(actor,timestamp){this._initialActorHeight=actor.attributes.size.height.getValue();this._initialActorWidth=actor.attributes.size.width.getValue();this.recalculateIncrementalChange();this._active=true;this._updatingSelf=false;this.attributes.growthRate.addObserver(this);this.registerForEveryFrame()};gs.GrowShrinkBehavior.recalculateIncrementalChange=function(){this._growthIncrementHeight=this.attributes.growthRate.getValue()/100*this._initialActorHeight;this._growthIncrementWidth=this.attributes.growthRate.getValue()/100*this._initialActorWidth};gs.GrowShrinkBehavior.observeValueChange=function(attribute,value){if(this._updatingSelf){return}this._updatingSelf=true;if(attribute===this.attributes.growthRate){this.recalculateIncrementalChange()}this._updatingSelf=false};gs.GrowShrinkBehavior.everyFrame=function(actor,timestamp){if(!this._active){return}var newHeight=actor.attributes.size.height.getValue()+this._growthIncrementHeight;var newWidth=actor.attributes.size.width.getValue()+this._growthIncrementWidth;var updateCollisionShape=false;if(newHeight&lt;=gs.GrowShrinkBehavior.MINDIMENSION||newWidth&lt;=gs.GrowShrinkBehavior.MINDIMENSION){if(this._initialActorHeight&lt;this._initialActorWidth){newHeight=gs.GrowShrinkBehavior.MINDIMENSION;newWidth=this._initialActorWidth/this._initialActorHeight}else{newWidth=gs.GrowShrinkBehavior.MINDIMENSION;newHeight=this._initialActorHeight/this._initialActorWidth}this._active=false;updateCollisionShape=true}actor.attributes.size.height.fastSetValue(newHeight);actor.attributes.size.width.fastSetValue(newWidth)};gs.GrowShrinkBehavior.stop=function(actor,timestamp){this.deregisterForEveryFrame();this._initialActorHeight=null;this._initialActorWidth=null;this._growthIncrementHeight=null;this._growthIncrementWidth=null;this._active=false;this.attributes.growthRate.removeObserver(this);this._updatingSelf=null};gs.InsertRowAction=gs.Behavior.subclass("InsertRowAction",{init:function(){gs.Behavior.init.call(this);this.attributes.addStringImmutableAttribute("table","");this.attributes.addIntegerImmutableAttribute("at",0);this.attributes.addIntegerImmutableAttribute("at_index",0);this.setObjectForKey(gs.PrototypicalArray.provide().init(),"tableColumns");this.tableColumns.addObjectAtIndex(gs.KeyValuePair.provide.init());return this},start:function(actor,timestamp){var target=this.resolveTableReferenceAttribute(this.attributes.table);if(!target){gs.Log.warn("Table does not exist:",this.attributes.table.getValue());return}var rowIndex=1;var position=this.attributes.at.getValue();switch(position){case 0:rowIndex=-1;break;case 1:rowIndex=1;break;case 2:rowIndex=this.attributes.at_index.getValue();break;default:return}var rowStr=String(rowIndex);target.addRow(rowStr);var columns=this.tableColumns;for(var i=0;i&lt;columns.array.length;i++){var column=columns.array[i];var colStr=String(column.attributes.key.getValue());var rValue=String(column.attributes.value.getValue());target.setCellSafe(rowStr,colStr,rValue)}},loadFromLite:function(node,initialState){debugger},loadFromTable:function(t,initialState){gs.Behavior.loadFromTable.call(this,t,initialState);if(this.tableColumns.array[0]!=null){this.tableColumns.removeObjectAtIndex(0)}var table=gs.JXON.children(t);if(!table){return}var itemCount=table.length;for(var i=0;i&lt;itemCount;++i){var node=table[i];var nodetype=gs.Project.nodeTypeNameMap[gs.JXON.tag(node)];if(nodetype==="tablecolumns"){this.tableColumns.loadFromTable(gs.JXON.children(node),initialState)}}}});gs.InterpolateBehavior=gs.CompletingBehavior.subclass("InterpolateBehavior");gs.InterpolateBehavior.init=function(){gs.CompletingBehavior.init.call(this);this.attributes.addReferenceImmutableAttribute("targetAttribute");this.attributes.addRealExpressionAttribute("finalValue",0);this.attributes.addRealExpressionAttribute("duration",1);this.attributes.addIntegerExpressionAttribute("easing",0);this.attributes.runToCompletion.changeDefaultValue(true);return this};gs.interpolateLinear=function(x){return x};gs.interpolateEaseIn=function(x){return x*x};gs.interpolateEaseOut=function(x){x=1-x;return 1-x*x};gs.interpolateEaseInOut=function(x){if(x&lt;.5){return gs.interpolateEaseIn(x*2)*.5}else{return.5+gs.interpolateEaseOut(x*2-1)*.5}};gs.InterpolateBehavior.start=function(actor,timestamp){this.startTime=timestamp.time;this.duration=this.attributes.duration.getValue();this.finalValue=this.attributes.finalValue.getValue();this.didSetFinalValue=false;var reference=this.attributes.targetAttribute.getValue();if(reference&amp;&amp;reference.keypath.indexOf("scene")&gt;-1){this.targetAttribute=null}if(!this.targetAttribute){if(!reference){return}this.targetAttribute=reference.resolveRelativeTo(this._entity)}this.initialValue=this.targetAttribute.getValue();gs.CompletingBehavior.start.call(this,actor,timestamp)};gs.InterpolateBehavior.completeStart=function(actor,timestamp){gs.CompletingBehavior.completeStart.call(this,actor,timestamp);var easing=this.attributes.easing.getValue();if(easing===0){this.easingFunction=gs.interpolateLinear}else if(easing===1){this.easingFunction=gs.interpolateEaseIn}else if(easing===2){this.easingFunction=gs.interpolateEaseOut}else{this.easingFunction=gs.interpolateEaseInOut}this.attributes.finalValue.addObserver(this);this.attributes.duration.addObserver(this)};gs.InterpolateBehavior.observeValueChange=function(attribute,value){if(!this._completed){if(attribute===this.attributes.finalValue){this.finalValue=value}else if(attribute===this.attributes.duration){this.duration=value}}};gs.InterpolateBehavior.completeEvaluate=function(actor,timestamp){gs.CompletingBehavior.completeEvaluate.call(this,actor,timestamp);var timeElapsed=timestamp.time-this.startTime;if(timeElapsed&gt;=this.duration){if(!this.didSetFinalValue){this.targetAttribute.fastSetValue(this.finalValue);this.didSetFinalValue=true}this.setCompleted(true)}else{var t=timeElapsed/this.duration;var progress=this.easingFunction(t);var distance=this.finalValue-this.initialValue;var currentValue=this.initialValue+distance*progress;this.targetAttribute.fastSetValue(currentValue)}};gs.InterpolateBehavior.completeStop=function(actor,timestamp){gs.CompletingBehavior.completeStop.call(this,actor,timestamp);this.attributes.finalValue.removeObserver(this);this.attributes.duration.removeObserver(this);if(!this.didSetFinalValue){this.targetAttribute.setValue(this.finalValue);this.didSetFinalValue=true}this.duration=null;this.finalValue=null;this.easingFunction=null;this.startTime=null};gs.KeyboardInputAction=gs.Behavior.subclass("KeyboardInputAction",{init:function(){gs.Behavior.init.call(this);this.attributes.addReferenceImmutableAttribute("targetAttribute");this.attributes.addStringExpressionAttribute("keyboardPrompt","");this.keyboardCaptureOn=false;return this},start:function(actor,timestamp){var game=gs.Game.current;if(game.isWaitingOnKeyboardInput){return}var reference=this.attributes.targetAttribute.getValue();if(!reference){return}var target=reference.resolveRelativeTo(this._entity);this.target=target;if(!target){return}var promptText=this.attributes.keyboardPrompt.getValue();var initialText=String(target.getValue());game.interceptKeyEvents=false;game.eventCenter.registerForEvent("keyboardInputEntered",this,"keyboardInputEntered");game.eventCenter.registerForEvent("keyboardInputCancelled",this,"keyboardInputCancelled");var eventCenter=gs.Game.current.eventCenter;if(promptText==="gs:captureKeyboard"){this.keyboardCaptureOn=true;var service=gs.platform.KeyboardCaptureService.instance();service.activateTextPrompt(this,initialText)}else{game.isWaitingOnKeyboardInput=true;var onTextServiceCompleted=function(userText){gs.clearTouchState(gs.Project.instance);if(userText===null){eventCenter.postEvent("keyboardInputCancelled")}else{eventCenter.postEvent("keyboardInputEntered",null,userText)}};var service=gs.platform.TextService.instance();service.openTextPrompt(promptText,initialText,onTextServiceCompleted)}},stop:function(timestamp){var game=gs.Game.current;if(this.keyboardCaptureOn&amp;&amp;this.attributes.keyboardPrompt.getValue()==="gs:captureKeyboard"){return}game.eventCenter.deregisterForEvent("keyboardInputEntered",this);game.eventCenter.deregisterForEvent("keyboardInputCancelled",this);game.interceptKeyEvents=true;game.isWaitingOnKeyboardInput=false},keyboardInputEntered:function(text){if(this.attributes.keyboardPrompt.getValue()!=="gs:captureKeyboard"){this.stop(0)}if(this.target instanceof gs.BooleanMutableAttribute){this.target.setValue(gs.parseBoolean(text))}else if(this.target instanceof gs.StringMutableAttribute){this.target.setValue(text)}else{this.target.setValue(parseFloat(text.trim()))}},keyboardInputCancelled:function(){this.keyboardCaptureOn=false;this.stop(0)}});gs.LaunchServiceAction=function(){gs.StatelessBehavior.call(this)};gs.LaunchServiceAction.prototype={declareAttributes:function(attributes){attributes.addIntegerImmutableAttribute("page",0)},start:function(actor,timestamp){gs.EngineContext.current.delegate.onLaunchService(this.attributes.page.getValue())}};gs.inherits(gs.LaunchServiceAction,gs.StatelessBehavior);gs.LoadAttributeAction=function(){gs.StatelessBehavior.call(this)};gs.LoadAttributeAction.prototype={declareAttributes:function(attributes){attributes.addReferenceImmutableAttribute("targetAttribute");attributes.addVariantExpressionAttribute("key","")},start:function(actor,timestamp){var reference=this.attributes.targetAttribute.getValue();if(!reference){return}var target=reference.resolveRelativeTo(actor);var key=this.attributes.key.getValueForEntityStateless(actor);if(target._type==="table"){gs.Log.warn("Ignored Load Attribute with table.")}else{var value=gs.EngineContext.current.delegate.onLoadAttribute(key,function(){return gs.LocalStorage.getString(key)});if(value!==null){target.setValue(value);if(!key||key===""){gs.Log.warn("Loaded attribute with empty name. value =",value)}else{}}else{}}}};gs.inherits(gs.LoadAttributeAction,gs.StatelessBehavior);gs.LogDebuggingStatementAction=gs.Behavior.subclass("LogDebuggingStatementAction");gs.LogDebuggingStatementAction.init=function(){gs.Behavior.init.call(this);this.attributes.addStringExpressionAttribute("text","");return this};gs.LogDebuggingStatementAction.start=function(actor,timestamp){var text=this.attributes.text.getValue();var entity=this._entity.attributes.name.getValue();gs.EngineContext.current.delegate.onLogDebuggingStatement(text,entity)};gs.LoopBehavior=gs.CompoundBehavior.subclass("LoopBehavior",{LOOP_WHILE:0,LOOP_UNTIL:1,MAX_LOOPS_PER_FRAME:1,init:function(){gs.CompoundBehavior.init.call(this);this.attributes.addIntegerImmutableAttribute("loopType",gs.LoopBehavior.LOOP_WHILE);this.attributes.addIntegerImmutableAttribute("compoundConditionKind",gs.LoopBehavior.CONDITION_ALL);this.attributes.addIntegerImmutableAttribute("maxLoopsPerFrame",gs.LoopBehavior.MAX_LOOPS_PER_FRAME);this.setObjectForKey(gs.PrototypicalKeylessArray.provide().init("condition"),"conditions");return this},testSingleCondition:function(){var conditions=this.conditions.array;var condition=conditions[0];condition.didEnter(this._entity,false,this,0);return condition.test()},testAllConditions:function(){var conditions=this.conditions.array;var conditionCount=this.conditions.length();for(var i=0;i&lt;conditionCount;i++){var condition=conditions[i];condition.didEnter(this._entity,false,this,i);var result=condition.test();if(!result){return false}}return true},testAnyConditions:function(){var conditions=this.conditions.array;var conditionCount=this.conditions.length();for(var i=0;i&lt;conditionCount;i++){var condition=conditions[i];condition.didEnter(this._entity,false,this,i);var result=condition.test();if(result){return true}}return false},start:function(actor,timestamp){this.isSequential=false;var conditions=this.conditions.array;var conditionCount=this.conditions.length();for(var i=0;i&lt;conditionCount;i++){var condition=conditions[i];condition.start(actor)}this.actorTime=timestamp;this._registeredForEveryFrame=true;this.registerForEveryFrame()},stop:function(actor,timestamp){var conditions=this.conditions.array;var conditionCount=this.conditions.length();for(var i=0;i&lt;conditionCount;i++){var condition=conditions[i];condition.stop(actor)}if(this._registeredForEveryFrame){this.deregisterForEveryFrame();this._registeredForEveryFrame=false}this._needsUpdate=false},didEnter:function(actor,isInitTime){gs.CompoundBehavior.didEnter.call(this,actor,isInitTime);var conditions=this.conditions.array;var conditionCount=this.conditions.length();for(var i=0;i&lt;conditionCount;i++){var condition=conditions[i];condition.didEnter(actor,isInitTime,this,i)}var compoundConditionKind=this.attributes.compoundConditionKind.getValue();if(conditionCount===1){this.testConditionsFunction=this.testSingleCondition}else if(compoundConditionKind===gs.RuleBehavior.CONDITION_ALL){this.testConditionsFunction=this.testAllConditions}else{this.testConditionsFunction=this.testAnyConditions}},willExit:function(actor){var conditions=this.conditions.array;var conditionCount=this.conditions.length();for(var i=0;i&lt;conditionCount;i++){var condition=conditions[i];condition.willExit(actor)}gs.CompoundBehavior.willExit.call(this,actor)},everyFrame:function(actor){var actor=this._entity;var timestamp=this.actorTime;var loopType=this.attributes.loopType.getValue();var loopsPerFrame=this.attributes.maxLoopsPerFrame.getValue();var done=false;for(var i=0;i&lt;loopsPerFrame;i++){done=this.testConditionsFunction();if(loopType===gs.LoopBehavior.LOOP_WHILE){done=!done}if(!done){this.behaviors.start(actor,timestamp);this.behaviors.stop(actor,timestamp)}else{if(this.isSequential){this.behaviors.stop(actor,timestamp)}else{this.deregisterForEveryFrame();this._registeredForEveryFrame=false}break}}},conditionChangedState:function(index,state){if(index!==null&amp;&amp;!this._registeredForEveryFrame){this._registeredForEveryFrame=true;this.registerForEveryFrame()}},loadFromLite:function(node,initialState){gs.CompoundBehavior.loadFromLite.call(this,node,initialState);var conditions=node["conditions"];if(conditions){this.conditions.loadFromLite(conditions,initialState)}}});gs.LoopTableBehavior=gs.CompoundBehavior.subclass("LoopTableBehavior",{LOOP_ROWS:0,LOOP_COLUMNS:1,CELL_START:0,CELL_END:1,CELL_AT:2,MAX_LOOPS_PER_FRAME:1,init:function(){gs.CompoundBehavior.init.call(this);var attributes=this.attributes;attributes.addReferenceImmutableAttribute("loopAttribute");attributes.addStringImmutableAttribute("tableID","");attributes.addIntegerImmutableAttribute("loopType",gs.LoopTableBehavior.LOOP_ROWS);attributes.addIntegerImmutableAttribute("maxLoopsPerFrame",gs.LoopTableBehavior.MAX_LOOPS_PER_FRAME);attributes.addIntegerImmutableAttribute("startCell",gs.LoopTableBehavior.CELL_START);attributes.addIntegerImmutableAttribute("endCell",gs.LoopTableBehavior.CELL_END);attributes.addIntegerExpressionAttribute("startCellExpression",0);attributes.addIntegerExpressionAttribute("endCellExpression",0);return this},start:function(actor,timestamp){this._registeredForEveryFrame=false;var loopTable=this.resolveTableReferenceAttribute(this.attributes.tableID);if(!loopTable){return}var count=0;var loopType=this.attributes.loopType.getValue();if(loopType===gs.LoopTableBehavior.LOOP_ROWS){count=loopTable.getRowCount()}else if(loopType===gs.LoopTableBehavior.LOOP_COLUMNS){count=loopTable.getColumnCount()}var temp=this.attributes.startCell.getValue();if(temp===gs.LoopTableBehavior.CELL_START){this._loopIndex=1}else if(temp==gs.LoopTableBehavior.CELL_END){this._loopIndex=count}else{this._loopIndex=gs.parseInteger(this.attributes.startCellExpression.getValue())}temp=this.attributes.endCell.getValue();if(temp===gs.LoopTableBehavior.CELL_START){this._endIndex=1}else if(temp==gs.LoopTableBehavior.CELL_END){this._endIndex=count}else{this._endIndex=gs.parseInteger(this.attributes.endCellExpression.getValue())}if(this._loopIndex&lt;=this._endIndex){this._delta=1;if(this._loopIndex&lt;1){this._loopIndex=1}if(this._endIndex&gt;count){this._endIndex=count}}else{this._delta=-1;if(this._loopIndex&gt;count){this._loopIndex=count}if(this._endIndex&lt;1){this._endIndex=1}}var attributeReference=this.attributes.loopAttribute.getValue();if(!attributeReference){return}var targetAttribute=attributeReference.resolveRelativeTo(actor);if(targetAttribute){targetAttribute.setValue(this._loopIndex)}this._registeredForEveryFrame=true;this.registerForEveryFrame()},stop:function(actor,timestamp){if(this._registeredForEveryFrame){this.deregisterForEveryFrame();this._registeredForEveryFrame=false}this._needsUpdate=false},everyFrame:function(actor,timestamp){var done=false;var loopTable=this.resolveTableReferenceAttribute(this.attributes.tableID);if(loopTable){var loopsPerFrame=this.attributes.maxLoopsPerFrame.getValue();for(var i=0;i&lt;loopsPerFrame;i++){if(this._delta===1&amp;&amp;this._loopIndex&lt;=this._endIndex||this._delta===-1&amp;&amp;this._loopIndex&gt;=this._endIndex){var attributeReference=this.attributes.loopAttribute.getValue();if(attributeReference){var targetAttribute=attributeReference.resolveRelativeTo(actor);if(targetAttribute){targetAttribute.setValue(this._loopIndex)}this.behaviors.start(actor,timestamp);this.behaviors.stop(actor,timestamp);this._loopIndex+=this._delta}else{done=true;break}}else{done=true;break}}}else{done=true}if(done){this.deregisterForEveryFrame()}}});gs.MoveBehavior=gs.Behavior.subclass("MoveBehavior");gs.MoveBehavior.SPACE_ACTOR=0;gs.MoveBehavior.SPACE_SCENE=1;gs.MoveBehavior.MOVETYPE_ADDITIVE=0;gs.MoveBehavior.MOVETYPE_STACKED=1;gs.MoveBehavior.init=function(){gs.Behavior.init.call(this);this.attributes.addRealExpressionAttribute("direction",0);this.attributes.addIntegerImmutableAttribute("space",gs.MoveBehavior.SPACE_ACTOR);this.attributes.addIntegerImmutableAttribute("moveType",gs.MoveBehavior.MOVETYPE_ADDITIVE);this.attributes.addRealExpressionAttribute("speed",300);this.attributes.addBooleanImmutableAttribute("haltWhenBehaviorStops",true);return this};gs.MoveBehavior.start=function(actor,timestamp){var space=this.attributes.space.getValue();if(space===gs.MoveBehavior.SPACE_ACTOR){this.calculateRotation=this.calculateRotationInActorSpace;actor.attributes.rotation.addObserver(this)}else if(space===gs.MoveBehavior.SPACE_SCENE){this.calculateRotation=this.calculateRotationInSceneSpace}if(this.attributes.moveType.getValue()===gs.MoveBehavior.MOVETYPE_ADDITIVE){this.modifyVelocity=this.modifyVelocityAdditive}else if(this.attributes.moveType.getValue()===gs.MoveBehavior.MOVETYPE_STACKED){this.modifyVelocity=this.modifyVelocityStacked}this.calculateVelocity();this._updatingSelf=false;this.attributes.speed.addObserver(this);this.attributes.direction.addObserver(this);this.registerForEveryFrame()};gs.MoveBehavior.everyFrame=function(actor,timestamp){if(this._updatingSelf){return}this._updatingSelf=true;this.calculateVelocity();this._updatingSelf=false};gs.MoveBehavior.observeValueChange=function(attribute,value){if(this._updatingSelf){return}var actor=this._entity;this._updatingSelf=true;if(attribute===this.attributes.speed||attribute===this.attributes.direction||attribute===actor.attributes.rotation){this.calculateVelocity()}this._updatingSelf=false};gs.MoveBehavior.calculateVelocity=function(){var velocity=this.calculateRotation();var speed=this.attributes.speed.getValue();velocity[0]=velocity[0]*speed;velocity[1]=velocity[1]*speed;this.modifyVelocity(velocity)};gs.MoveBehavior.calculateRotationInActorSpace=function(){var actor=this._entity;var actorRotation=actor.attributes.rotation.getValue();var newRotation=(this.attributes.direction.getValue()+actorRotation)%360;var radians=newRotation*(Math.PI/180);var velocity=gs.g_tempVec2d;velocity[0]=Math.cos(radians);velocity[1]=Math.sin(radians);return velocity};gs.MoveBehavior.calculateRotationInSceneSpace=function(){var direction=this.attributes.direction.getValue();var radians=direction*(Math.PI/180);var velocity=gs.g_tempVec2d;velocity[0]=Math.cos(radians);velocity[1]=Math.sin(radians);return velocity};gs.MoveBehavior.modifyVelocityAdditive=function(velocity){var motionAspect=this._entity.aspects.motion;motionAspect.modifyAdditiveVelocity(velocity,this.getUniqueKey())};gs.MoveBehavior.modifyVelocityStacked=function(velocity){var motionAspect=this._entity.aspects.motion;motionAspect.modifyStackedVelocity(velocity,this.getUniqueKey())};gs.MoveBehavior.stop=function(actor,timestamp){if(this.attributes.haltWhenBehaviorStops.getValue()){var motionAspect=this._entity.aspects.motion;if(this.attributes.moveType.getValue()===gs.MoveBehavior.MOVETYPE_ADDITIVE){motionAspect.removeAdditiveVelocity(this.getUniqueKey())}else if(this.attributes.moveType.getValue()===gs.MoveBehavior.MOVETYPE_STACKED){motionAspect.removeStackedVelocity(this.getUniqueKey())}this.attributes.speed.removeObserver(this);this.attributes.direction.removeObserver(this);this.deregisterForEveryFrame();if(this.attributes.space.getValue()===gs.MoveBehavior.SPACE_ACTOR){actor.attributes.rotation.removeObserver(this)}this._updatingSelf=null}};gs.MoveBehavior.willExit=function(actor){if(!this.attributes.haltWhenBehaviorStops.getValue()){this.attributes.speed.removeObserver(this);this.attributes.direction.removeObserver(this);this.deregisterForEveryFrame();if(this.attributes.space.getValue()===gs.MoveBehavior.SPACE_ACTOR){actor.attributes.rotation.removeObserver(this)}}gs.Behavior.willExit.call(this,actor)};gs.MoveToBehavior=gs.CompletingBehavior.subclass("MoveToBehavior");gs.MoveToBehavior.init=function(){gs.CompletingBehavior.init.call(this);this.attributes.addPointExpressionAttribute("position",0,0);this.attributes.addIntegerImmutableAttribute("space",gs.MoveBehavior.SPACE_SCENE);this.attributes.addRealExpressionAttribute("speed",300);return this};gs.MoveToBehavior.completeStart=function(actor,timestamp){var game=gs.Game.current;var motion=actor.aspects.motion;gs.CompletingBehavior.completeStart.call(this,actor,timestamp);var predicates=[gs.makeEqualityPredicate(actor),null];game.eventCenter.registerForEvent("wrap",this,"actorDidWrap",predicates);if(this.attributes.space.getValue()===gs.MoveBehavior.SPACE_ACTOR){this.calculateDestination=this.calculateDestinationFunctionActorSpace}else{this.calculateDestination=this.calculateDestinationFunctionSceneSpace}this._targetPosition=[0,0];this.calculateDestination();this.calculateVelocity();this._updatingSelf=false;this.attributes.position.x.addObserver(this);this.attributes.position.y.addObserver(this);this.attributes.speed.addObserver(this);motion.attributes.linearVelocity.x.addObserver(this);motion.attributes.linearVelocity.y.addObserver(this)};gs.MoveToBehavior.calculateDestinationFunctionActorSpace=function(){var targetPosition=this._targetPosition;var positionX=this.attributes.position.x.getValue();var positionY=this.attributes.position.y.getValue();targetPosition[0]=positionX;targetPosition[1]=positionY;var actor=this._entity;var actorPositionX=actor.attributes.position.x.getValue();var actorPositionY=actor.attributes.position.y.getValue();var rotation=actor.attributes.rotation.getValue()*(Math.PI/180);gs.Vector2.vectorRotate2D(targetPosition,targetPosition,rotation);targetPosition[0]+=actorPositionX;targetPosition[1]+=actorPositionY};gs.MoveToBehavior.calculateDestinationFunctionSceneSpace=function(){this._targetPosition[0]=this.attributes.position.x.getValue();this._targetPosition[1]=this.attributes.position.y.getValue()};gs.MoveToBehavior.calculateVelocity=function(){var actor=this._entity;var actorPositionX=actor.attributes.position.x.getValue();var actorPositionY=actor.attributes.position.y.getValue();var motion=actor.aspects.motion;var velocityVector=gs.g_tempVec2d;velocityVector[0]=0;velocityVector[1]=0;velocityVector[0]=this._targetPosition[0]-actorPositionX;velocityVector[1]=this._targetPosition[1]-actorPositionY;var length=Math.sqrt(velocityVector[0]*velocityVector[0]+velocityVector[1]*velocityVector[1]);if(length&gt;0){velocityVector[0]=velocityVector[0]/length;velocityVector[1]=velocityVector[1]/length}else{velocityVector[0]=0;velocityVector[1]=0}var speed=this.attributes.speed.getValue();velocityVector[0]=velocityVector[0]*speed;velocityVector[1]=velocityVector[1]*speed;motion.attributes.linearVelocity.x.fastSetValue(velocityVector[0]);motion.attributes.linearVelocity.y.fastSetValue(velocityVector[1])};gs.MoveToBehavior.observeValueChange=function(attribute,value){if(this._updatingSelf){return}this._updatingSelf=true;var position=this.attributes.position;if(attribute===position.x||attribute===position.y){this.calculateDestination()}this.calculateVelocity();this._updatingSelf=false};gs.MoveToBehavior.completeEvaluate=function(actor,timestamp){gs.CompletingBehavior.completeEvaluate.call(this,actor,timestamp);var actorPosition=gs.g_tempVec2d;actorPosition[0]=actor.attributes.position.x.getValue();actorPosition[1]=actor.attributes.position.y.getValue();if(gs.Vector2.equals(actorPosition,this._targetPosition,gs.Vector2.EPSILON)){this.setCompleted(true)}};gs.MoveToBehavior.completeStop=function(actor,timestamp){gs.CompletingBehavior.completeStop.call(this,actor,timestamp);var game=gs.Game.current;var motionAspect=actor.aspects.motion;this.attributes.position.x.removeObserver(this);this.attributes.position.y.removeObserver(this);this.attributes.speed.removeObserver(this);motionAspect.attributes.linearVelocity.x.removeObserver(this);motionAspect.attributes.linearVelocity.y.removeObserver(this);this._updatingSelf=null;if(this.completed()){actor.attributes.position.x.fastSetValue(this._targetPosition[0]);actor.attributes.position.y.fastSetValue(this._targetPosition[1])}motionAspect.attributes.linearVelocity.x.fastSetValue(0);motionAspect.attributes.linearVelocity.y.fastSetValue(0);game.eventCenter.deregisterForEvent("wrap",this)};gs.MoveToBehavior.actorDidWrap=function(actor,axis,maxDimension,wrapOffset){this._updatingSelf=true;if(axis===gs.Vector2.X_COMPONENT){this._targetPosition[0]=this._targetPosition[0]%maxDimension}else{this._targetPosition[1]=this._targetPosition[1]%maxDimension}this.calculateVelocity();this._updatingSelf=false};gs.NoteBehavior=function(){gs.SingletonBehavior.call(this)};gs.NoteBehavior.prototype={};gs.inherits(gs.NoteBehavior,gs.SingletonBehavior);gs.singleton(gs.NoteBehavior);gs.NetworkGetTableFromURLAction=function(){gs.StatelessBehavior.call(this)};gs.NetworkGetTableFromURLAction.prototype={declareAttributes:function(attributes){attributes.addReferenceImmutableAttribute("callbackAttribute");attributes.addStringExpressionAttribute("url","");attributes.addVariantExpressionAttribute("dataTable",null)},start:function(actor,timestamp){var tableAttribute;if(!tableAttribute){tableAttribute=this.attributes.dataTable.getValueForEntityStateless(actor)}var callbackAttribute;var callbackAttributeReference=this.attributes.callbackAttribute.getValue();if(callbackAttributeReference){callbackAttribute=callbackAttributeReference.resolveRelativeTo(actor)}var url=this.attributes.url.getValueForEntityStateless(actor);if(url&amp;&amp;tableAttribute){if(callbackAttribute){callbackAttribute.setValue(0)}var network=gs.Network.instance();var callbackStatus=-1;network.getJSON(url).then(function onSuccess(responseJSON){try{network.propertyToTable(responseJSON,tableAttribute);callbackStatus=1;tableAttribute.notifyObserversOfValueChange(tableAttribute)}catch(exception){gs.Log.debug(exception)}}).otherwise(function onFailure(){network.setLastError(network.ERROR_STRING_NETWORK_ERROR)}).always(function onComplete(){if(callbackAttribute){callbackAttribute.setValue(callbackStatus)}})}}};gs.inherits(gs.NetworkGetTableFromURLAction,gs.StatelessBehavior);gs.NetworkSendTableToURLAction=function(){gs.StatelessBehavior.call(this)};gs.NetworkSendTableToURLAction.prototype={declareAttributes:function(attributes){attributes.addReferenceImmutableAttribute("callbackAttribute");attributes.addStringExpressionAttribute("url","");attributes.addVariantExpressionAttribute("dataTable",null)},start:function(actor,timestamp){var tableAttribute;if(!tableAttribute){tableAttribute=this.attributes.dataTable.getValueForEntityStateless(actor)}var callbackAttribute;var callbackAttributeReference=this.attributes.callbackAttribute.getValue();if(callbackAttributeReference){callbackAttribute=callbackAttributeReference.resolveRelativeTo(actor)}var url=this.attributes.url.getValueForEntityStateless(actor);if(tableAttribute&amp;&amp;url){if(callbackAttribute){callbackAttribute.setValue(0)}var callbackStatus=-1;var network=gs.Network.instance();var tableJSON=network.tableToNetworkJSON(tableAttribute);network.postJSON(url,tableJSON).then(function onSuccess(responseJSON){try{if(responseJSON&amp;&amp;responseJSON.Status==="Success"){callbackStatus=1;if(responseJSON.updates){try{responseJSON.updates.forEach(function(update){var tableId=update.Children[1].Name;var tableAttribute=gs.Reference.lookup(`game.attributes.${tableId}`);network.propertyToTable(update,tableAttribute);tableAttribute.notifyObserversOfValueChange(tableAttribute)})}catch(e){console.log("Error updating on send table response.",e)}}}}catch(exception){gs.Log.debug(exception)}}).always(function onComplete(){if(callbackAttribute){callbackAttribute.setValue(callbackStatus)}})}}};gs.inherits(gs.NetworkSendTableToURLAction,gs.StatelessBehavior);gs.NullBehavior=function(){gs.SingletonBehavior.call(this)};gs.NullBehavior.prototype={};gs.inherits(gs.NullBehavior,gs.SingletonBehavior);gs.singleton(gs.NullBehavior);gs.OpenURLAction=function(){gs.StatelessBehavior.call(this)};gs.OpenURLAction.Protocol={MAILTO:0,HTTP:1,HTTPS:2};gs.OpenURLAction.protocolMap={0:"mailto:",1:"http://",2:"https://"};gs.OpenURLAction.externalWhitelist=["www.google.com","facebook.com","itunes.com/apps"];gs.OpenURLAction.prototype={declareAttributes:function(attributes){attributes.addStringExpressionAttribute("URL","");attributes.addBooleanImmutableAttribute("useExternalBrowser",true);attributes.addIntegerImmutableAttribute("protocol",gs.OpenURLAction.Protocol.HTTP)},start:function(actor,timestamp){var URLString=this.attributes.URL.getValueForEntityStateless(actor);var externalBrowser=this.attributes.useExternalBrowser.getValue();var protocol=this.attributes.protocol.getValue();var prefix=gs.OpenURLAction.protocolMap[protocol];if(protocol===gs.OpenURLAction.Protocol.MAILTO){externalBrowser=true}var whitelist=gs.OpenURLAction.externalWhitelist;if(whitelist){for(var i=0;i&lt;whitelist.length;i++){if(URLString.indexOf(whitelist[i])!==-1){externalBrowser=true;prefix="https://"}}}if(URLString.indexOf(prefix)!==0){URLString=prefix+URLString}if(URLString!==null&amp;&amp;URLString.length&gt;0){var service=gs.platform.BrowserService.instance();service.openBrowser(URLString,!externalBrowser)}}};gs.inherits(gs.OpenURLAction,gs.StatelessBehavior);gs.PathFindAction=gs.Behavior.subclass("PathFindAction",{TOPOLOGY:0,init:function(){gs.Behavior.init.call(this);var attributes=this.attributes;attributes.addVariantExpressionAttribute("mapTable","");attributes.addVariantExpressionAttribute("pathTable","");attributes.addVariantExpressionAttribute("startRow",0);attributes.addVariantExpressionAttribute("startColumn",0);attributes.addVariantExpressionAttribute("destRow",0);attributes.addVariantExpressionAttribute("destColumn",0);attributes.addIntegerImmutableAttribute("topology",gs.PathFindAction.TOPOLOGY);return this},normalizeTableKey:function(value){var index=parseInt(value);if(isNaN(index)||index&lt;0){return value}return index},clearTable:function(table){while(table.getRowCount()&gt;0){table.removeRow(-1)}},start:function(actor,timestamp){var pathTable=null;if(this.attributes.pathTable){pathTable=this.attributes.pathTable.getValue()}else{this.stop(actor,timestamp);return}var mapTable=null;if(this.attributes.mapTable){mapTable=this.attributes.mapTable.getValue()}else{this.stop(actor,timestamp);return}if(mapTable&amp;&amp;pathTable){var attribs=this.attributes;var mapTableData=mapTable.getTableData();var startRowIndex=mapTableData.lookupRow(attribs.startRow.getValueForEntity(actor))-1;var startColumnIndex=mapTableData.lookupColumn(attribs.startColumn.getValueForEntity(actor))-1;var destRowIndex=mapTableData.lookupRow(attribs.destRow.getValueForEntity(actor))-1;var destColumn=mapTableData.lookupColumn(attribs.destColumn.getValueForEntity(actor))-1;var topology=attribs.topology.getValue();var path=gsFindPath(mapTableData.data,startRowIndex,startColumnIndex,destRowIndex,destColumn,topology);if(path){var rowCount=pathTable.getRowCount();if(rowCount&gt;path.length){for(var i=0;i&lt;rowCount-path.length;i++){pathTable.removeRow(-1)}}else if(rowCount&lt;path.length){for(var i=0;i&lt;path.length-rowCount;i++){pathTable.addRow(-1)}}for(var i=0;i&lt;path.length;i++){var node=path[i];pathTable.setCell(i+1,1,node[0]+1);pathTable.setCell(i+1,2,node[1]+1)}}else if(pathTable){this.clearTable(pathTable)}this.stop(actor,timestamp)}},stop:function(actor,timestamp){},observeValueChange:function(attribute,newValue){}});gs.ParticlesBehavior=gs.Behavior.subclass("ParticlesBehavior");gs.ParticlesBehavior.SYSTEM_LIFETIME_INFINITE=1;gs.ParticlesBehavior.SYSTEM_LIFETIME_FINITE=0;gs.ParticlesBehavior.RELATIVE_TO_ACTOR=0;gs.ParticlesBehavior.RELATIVE_TO_SCENE=1;gs.ParticlesBehavior.init=function(){gs.Behavior.init.call(this);var attributes=this.attributes;attributes.addIntegerExpressionAttribute("numParticles",20);attributes.addRealExpressionAttribute("size",15);attributes.addRealExpressionAttribute("lifetime",2);attributes.addRealExpressionAttribute("startupTime",2);attributes.addRealExpressionAttribute("direction",0);attributes.addRealExpressionAttribute("speed",10);attributes.addStringImmutableAttribute("image","");attributes.addRealExpressionAttribute("rotation",0);attributes.addRealExpressionAttribute("angularVelocity",0);attributes.addIntegerImmutableAttribute("directionRelativity",gs.ParticlesBehavior.RELATIVE_TO_ACTOR);attributes.addRealExpressionAttribute("emitterOffsetX",0);attributes.addRealExpressionAttribute("emitterOffsetY",0);attributes.addBooleanImmutableAttribute("colorChange",0);attributes.addBooleanImmutableAttribute("sizeChange",0);attributes.addRealExpressionAttribute("colorTransitionTime",1);attributes.addRealExpressionAttribute("sizeTarget",5);attributes.addRealExpressionAttribute("sizeTransitionTime",0);attributes.addColorImmutableAttribute("color",1,1,1,1);attributes.addColorImmutableAttribute("colorTarget",1,1,1,1);attributes.addBooleanImmutableAttribute("affectedByGravity",false);attributes.addIntegerImmutableAttribute("blendingMode",0);return this};gs.ParticlesBehavior.everyFrame=function(actor,timestamp){var particleSystem=this._particleSystem;particleSystem.time+=timestamp.dt;if(this._endTime){if(particleSystem.time&gt;this._endTime){this._entity.removeNodeSource(this);this.deregisterForEveryFrame()}}};gs.ParticlesBehavior.start=function(actor,timestamp){if(!actor.visible()){return}this._endTime=null;var particleSystem=this._particleSystem;if(!particleSystem){this.createNode();particleSystem=this._particleSystem}this.bindNodeAttributes();this.updateInitialValues();particleSystem.init();particleSystem.spawnParticles=true;particleSystem.time=0;actor.addNodeSource(this);actor.attributes.position.x.addObserver(this);actor.attributes.position.y.addObserver(this);var directionRelativity=this.attributes.directionRelativity.getValue();if(directionRelativity===gs.ParticlesBehavior.RELATIVE_TO_ACTOR){actor.attributes.rotation.addObserver(this)}this.registerForEveryFrame()};gs.ParticlesBehavior.stop=function(actor,timestamp){if(!actor.visible()){return}actor.attributes.position.x.removeObserver(this);actor.attributes.position.y.removeObserver(this);var directionRelativity=this.attributes.directionRelativity.getValue();if(directionRelativity===gs.ParticlesBehavior.RELATIVE_TO_ACTOR){actor.attributes.rotation.removeObserver(this)}var particleSystem=this._particleSystem;if(!timestamp){particleSystem.spawnParticles=false;actor.removeNodeSource(this);this.deregisterForEveryFrame()}else{this._endTime=particleSystem.time+this.attributes.lifetime.getValue();particleSystem.stopSpawning=true}};gs.ParticlesBehavior.didEnter=function(actor,isInitTime){gs.Behavior.didEnter.call(this,actor,isInitTime);if(isInitTime){this.createNode()}};gs.ParticlesBehavior.willExit=function(actor){this._entity.removeNodeSource(this);this.deregisterForEveryFrame();if(this._particleSystem){this._particleSystem.recycle();this._particleSystem=null}if(this._attributesWithExpressions){gs.array.recycle(this._attributesWithExpressions);this._attributesWithExpressions=null}gs.Behavior.willExit.call(this,actor)};gs.ParticlesBehavior.createNode=function(){this._particleSystem=gs.SGParticleSystemNode.provide()};gs.ParticlesBehavior.bindNodeAttributes=function(){this.updateConstantValues();var ps=this._particleSystem;var attributes=this.attributes;var attributesWithExpressions=gs.array.provide();this._attributesWithExpressions=attributesWithExpressions;this.bindDynamicValue(attributes.size,ps,"sizeBegin","dirtySettings");this.bindDynamicValue(attributes.sizeTarget,ps,"sizeEnd","dirtySettings");this.bindDynamicValue(attributes.sizeTransitionTime,ps,"sizeTime","dirtySettings");this.bindDynamicValue(attributes.colorTransitionTime,ps,"colorTime","dirtySettings");this.bindDynamicValue(attributes.emitterOffsetX,ps,"offsetX","dirtyOffset");this.bindDynamicValue(attributes.emitterOffsetY,ps,"offsetY","dirtyOffset");this.bindDynamicValue(attributes.direction,ps,"offsetAngleDeg","dirtyOffset");this.bindDynamicValue(attributes.speed,ps,"speed","dirtySettings");this.bindDynamicValue(attributes.rotation,ps,"particleAngleDeg","dirtySettings");this.bindDynamicValue(attributes.angularVelocity,ps,"particleAngularVelocityDeg","dirtySettings");if(attributesWithExpressions.length&gt;0){ps.attributesWithExpressions=this._attributesWithExpressions}};gs.ParticlesBehavior.bindDynamicValue=function(attribute,particleSystem,valueKey,dirtyKey){attribute.connectToSprite(particleSystem,valueKey,dirtyKey);if(attribute.hasExpression()){this._attributesWithExpressions.push(attribute)}};gs.ParticlesBehavior.createNodesInSpace=function(parentSpace,nodeIndex){parentSpace.addNode(this._particleSystem);this._particleSystem.setLayer(nodeIndex);return 1};gs.ParticlesBehavior.removeNodesFromSpace=function(parentSpace){var attributes=this.attributes;attributes.size.disconnectFromSprite();attributes.sizeTarget.disconnectFromSprite();attributes.sizeTransitionTime.disconnectFromSprite();attributes.colorTransitionTime.disconnectFromSprite();attributes.emitterOffsetX.disconnectFromSprite();attributes.emitterOffsetY.disconnectFromSprite();attributes.direction.disconnectFromSprite();attributes.speed.disconnectFromSprite();attributes.rotation.disconnectFromSprite();attributes.angularVelocity.disconnectFromSprite();var ps=this._particleSystem;if(ps){ps.attributesWithExpressions=null;parentSpace.removeNode(ps)}};gs.ParticlesBehavior.observeValueChange=function(attribute,newValue){var actor=this._entity;var ps=this._particleSystem;if(attribute===actor.attributes.position.x){ps.originX=newValue}else if(attribute===actor.attributes.position.y){ps.originY=newValue}else{ps.originAngleDeg=newValue}ps.dirtyOrigin=true};gs.ParticlesBehavior.updateConstantValues=function(){var attributes=this.attributes;var ps=this._particleSystem;ps.imageID=attributes.image.getValue();ps.blendMode=attributes.blendingMode.getValue();ps.sizeChanges=attributes.sizeChange.getValue();ps.colorBegin[0]=attributes.color.red.getValue();ps.colorBegin[1]=attributes.color.green.getValue();ps.colorBegin[2]=attributes.color.blue.getValue();ps.colorBegin[3]=attributes.color.alpha.getValue();var colorChange=attributes.colorChange.getValue();ps.colorChanges=colorChange;if(colorChange){ps.colorEnd[0]=attributes.colorTarget.red.getValue();ps.colorEnd[1]=attributes.colorTarget.green.getValue();ps.colorEnd[2]=attributes.colorTarget.blue.getValue();ps.colorEnd[3]=attributes.colorTarget.alpha.getValue()}else{ps.colorEnd[0]=ps.colorBegin[0];ps.colorEnd[1]=ps.colorBegin[1];ps.colorEnd[2]=ps.colorBegin[2];ps.colorEnd[3]=ps.colorBegin[3]}};gs.ParticlesBehavior.updateInitialValues=function(){var actor=this._entity;var attributes=this.attributes;var ps=this._particleSystem;ps.particleCount=attributes.numParticles.getValue();ps.lifeTime=attributes.lifetime.getValue();ps.lifeStart=attributes.startupTime.getValue();if(attributes.affectedByGravity.getValue()){var sceneGravity=actor.scene.attributes.gravity;ps.gravityX=-sceneGravity.x.getValue();ps.gravityY=-sceneGravity.y.getValue()}else{ps.gravityX=0;ps.gravityY=0}ps.originX=actor.attributes.position.x.getValue();ps.originY=actor.attributes.position.y.getValue();var directionRelativity=attributes.directionRelativity.getValue();if(directionRelativity===gs.ParticlesBehavior.RELATIVE_TO_ACTOR){ps.originAngleDeg=actor.attributes.rotation.getValue()}};gs.ParticlesBehavior.getRequiredAssets=function(imageSet,soundSet,fontSet,strategy){var imageName=this.attributes.image.getValue();if(imageName&amp;&amp;imageName.length&gt;0){imageSet[imageName]=true}};gs.PauseGameAction=function(){gs.StatelessBehavior.call(this)};gs.PauseGameAction.SOCIAL_CONSOLE_SCENE_KEY="socialConsoleID";gs.PauseGameAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("sceneKey",gs.PauseGameAction.SOCIAL_CONSOLE_SCENE_KEY);attributes.addBooleanImmutableAttribute("enableAdvertisement",false)},pauseGame:function(actor,timestamp){var newSceneKey=this.attributes.sceneKey.getValue();var enableAdvertisement=this.attributes.enableAdvertisement.getValue();if(newSceneKey===gs.PauseGameAction.SOCIAL_CONSOLE_SCENE_KEY){gs.callSocialConsole(gs.Game.current.project,"show")}gs.Game.current.eventCenter.postEvent("startPauseScene",null,newSceneKey,enableAdvertisement)},start:function(actor,timestamp){var game=gs.Game.current;if(!game.loadingFlag){this.pauseGame(actor,timestamp)}else{this.registerForEveryFrame(actor)}},everyFrame:function(actor,timestamp){var game=gs.Game.current;if(!game.loadingFlag){this.deregisterForEveryFrame(actor);this.pauseGame(actor,timestamp)}},getRequiredAssets:function(imageSet,soundSet,fontSet,strategy){if(strategy===gs.LoadStrategyOption.SCENE){var sceneKey=this.attributes.sceneKey.getValue();gs.Game.current.scenes.fetchSceneByKey(sceneKey)}}};gs.inherits(gs.PauseGameAction,gs.StatelessBehavior);gs.PauseMusicAction=function(){gs.SingletonBehavior.call(this)};gs.PauseMusicAction.prototype={start:function(actor,timestamp){gs.AudioManager.current.pauseMusic()}};gs.inherits(gs.PauseMusicAction,gs.SingletonBehavior);gs.singleton(gs.PauseMusicAction);gs.PostEventAction=function(){gs.StatelessBehavior.call(this)};gs.PostEventAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("event","")},start:function(actor,timestamp){var eventName=this.attributes.event.getValue();var game=gs.Game.current;game.eventCenter.postEvent(eventName)}};gs.inherits(gs.PostEventAction,gs.StatelessBehavior);gs.PlayMusicAction=function(){gs.StatelessBehavior.call(this)};gs.PlayMusicAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("musicName","");attributes.addBooleanImmutableAttribute("loop",false)},start:function(actor,timestamp){if(!gs.debug.audio){return}var assetID=this.attributes.musicName.getValue();var loop=this.attributes.loop.getValue();if(assetID){gs.AudioManager.current.playMusic(assetID,loop)}else{gs.AudioManager.current.unpauseMusic()}}};gs.inherits(gs.PlayMusicAction,gs.StatelessBehavior);gs.PlaySoundAction=gs.Behavior.subclass("PlaySoundAction",{init:function(){gs.Behavior.init.call(this);var attributes=this.attributes;attributes.addStringImmutableAttribute("soundName","");attributes.addBooleanImmutableAttribute("loop",false);attributes.addBooleanImmutableAttribute("runToCompletion",true);attributes.addBooleanImmutableAttribute("positional",false);attributes.addBooleanImmutableAttribute("dopplerShift",false);attributes.addRealExpressionAttribute("volume",1);attributes.addRealExpressionAttribute("pitch",1);return this},start:function(actor,timestamp){if(!gs.debug.audio){return}var assetID=this.attributes.soundName.getValue();if(!assetID){return}var loop=this.attributes.loop.getValue();var volume=gsMath.clampf(this.attributes.volume.getValue(),0,1);var pitch=Math.max(0,this.attributes.pitch.getValue());var positional=this.attributes.positional.getValue();this.audioInstance=gs.AudioManager.current.playSound(assetID,volume,loop,pitch,positional);this.attributes.volume.addObserver(this);this.attributes.pitch.addObserver(this);if(gs.AudioManager.current.setInstanceX&amp;&amp;this.attributes.positional.getValue()){actor.attributes.position.x.addObserver(this);actor.attributes.position.y.addObserver(this);gs.AudioManager.current.setInstanceX(this.audioInstance,actor.attributes.position.x.getValue());gs.AudioManager.current.setInstanceX(this.audioInstance,actor.attributes.position.y.getValue())}},stop:function(actor,timestamp){if(!gs.debug.audio){return}if(this.audioInstance){if(this.attributes.loop.getValue()||!this.attributes.runToCompletion.getValue()){gs.AudioManager.current.stopInstance(this.audioInstance)}this.audioInstance=null}this.attributes.volume.removeObserver(this);this.attributes.pitch.removeObserver(this);if(gs.AudioManager.current.setInstanceX&amp;&amp;this.attributes.positional.getValue()){actor.attributes.position.x.removeObserver(this);actor.attributes.position.y.removeObserver(this)}if(gs.AudioManager.current.setInstanceDx&amp;&amp;this.attributes.dopplerShift.getValue()){var motion=actor.aspects.motion;motion.attributes.linearVelocity.x.removeObserver(this);motion.attributes.linearVelocity.y.removeObserver(this)}},observeValueChange:function(attribute,newValue){if(attribute===this.attributes.volume){gs.AudioManager.current.setInstanceVolume(this.audioInstance,newValue)}else if(attribute===this.attributes.pitch){gs.AudioManager.current.setInstancePitch(this.audioInstance,newValue)}else if(attribute.spriteValueKey&amp;&amp;attribute.spriteValueKey==="x"){gs.AudioManager.current.setInstanceX(this.audioInstance,newValue)}else if(attribute.spriteValueKey&amp;&amp;attribute.spriteValueKey==="y"){gs.AudioManager.current.setInstanceY(this.audioInstance,newValue)}else{console.log("PlaySoundAction observer: ",attribute)}},getRequiredAssets:function(imageSet,soundSet,fontSet,strategy){var soundName=this.attributes.soundName.getValue();if(soundName&amp;&amp;soundName.length&gt;0){soundSet[soundName]=true}}});gs.PurchaseItemAction=function(){gs.StatelessBehavior.call(this)};gs.PurchaseItemAction.prototype={declareAttributes:function(attributes){attributes.addIntegerImmutableAttribute("item",0);attributes.addStringImmutableAttribute("table","")},start:function(actor,timestamp){var game=gs.Game.current;game.eventCenter.registerForEvent("purchaseItemSuccess",this,"purchaseItemSuccess");game.eventCenter.registerForEvent("purchaseItemFailure",this,"purchaseItemFailure");game.eventCenter.registerForEvent("purchaseItemCancel",this,"purchaseItemCancel");var item=this.attributes.item.getValue();var args={item:item,success:function(){game.eventCenter.postEvent("purchaseItemSuccess",null,item)},failure:function(){game.eventCenter.postEvent("purchaseItemFailure",null,item)},cancel:function(){game.eventCenter.postEvent("purchaseItemCancel",null,item)}};this.doStub("purchaseItem","purchaseItem",args)},stop:function(actor,timestamp){var game=gs.Game.current;game.eventCenter.deregisterForEvent("purchaseItemSuccess",this,"purchaseItemSuccess");game.eventCenter.deregisterForEvent("purchaseItemFailure",this,"purchaseItemFailure");game.eventCenter.deregisterForEvent("purchaseItemCancel",this,"purchaseItemCancel")},purchaseItemSuccess:function(item){item=parseInt(item,10);if(item===this.attributes.item.getValue()){this.updateGameServiceStatus(item,gs.PurchasePredicate.EVENT.SUCCESS)}},purchaseItemFailure:function(item){item=parseInt(item,10);if(item===this.attributes.item.getValue()){this.updateGameServiceStatus(item,gs.PurchasePredicate.EVENT.FAILURE)}},purchaseItemCancel:function(item){item=parseInt(item,10);if(item===this.attributes.item.getValue()){this.updateGameServiceStatus(item,gs.PurchasePredicate.EVENT.CANCEL)}},updateGameServiceStatus:function(item,status){var game=gs.Game.current;game.services.purchases.item.setValue(item);game.services.purchases.status.setValue(status)}};gs.inherits(gs.PurchaseItemAction,gs.StatelessBehavior);gs.ReplicateBehavior=function(){gs.MutableBehavior.call(this)};gs.ReplicateBehavior.prototype={declareAttributes:function(attributes){attributes.addRealExpressionAttribute("angle",0);attributes.addRealExpressionAttribute("spacing",50);attributes.addIntegerExpressionAttribute("copies",5)},start:function(actor,timestamp){if(!actor.visible()){return}actor.addSpaceSource(this)},stop:function(actor,timestamp){if(!actor.visible()){return}actor.removeSpaceSource(this)},createSpace:function(parentSpace){var replicatorSpace=parentSpace.createNode(gs.SGSpace.NodeType.SGReplicator);this.attributes.spacing.connectToSprite(replicatorSpace,"spacing","dirty");this.attributes.copies.connectToSprite(replicatorSpace,"copies","dirty");this.attributes.angle.connectToSprite(replicatorSpace,"angle","dirty");this._replicatorSpace=replicatorSpace;return replicatorSpace},getSpace:function(){return this._replicatorSpace},removeSpace:function(parentSpace){this.attributes.spacing.disconnectFromSprite();this.attributes.copies.disconnectFromSprite();this.attributes.angle.disconnectFromSprite();parentSpace.removeNode(this._replicatorSpace);this._replicatorSpace=null}};gs.inherits(gs.ReplicateBehavior,gs.MutableBehavior);gs.ResetGameAction=function(){gs.StatelessBehavior.call(this)};gs.ResetGameAction.prototype={declareAttributes:function(attributes){attributes.addBooleanImmutableAttribute("enableAdvertisement",false)},start:function(actor,timestamp){var enableAdvertisement=this.attributes.enableAdvertisement.getValue();gs.Game.current.eventCenter.postEvent("resetGame",null,enableAdvertisement)}};gs.inherits(gs.ResetGameAction,gs.StatelessBehavior);gs.ResetSceneAction=function(){gs.StatelessBehavior.call(this)};gs.ResetSceneAction.prototype={declareAttributes:function(attributes){attributes.addBooleanImmutableAttribute("enableAdvertisement",false)},start:function(actor,timestamp){var enableAdvertisement=this.attributes.enableAdvertisement.getValue();gs.Game.current.eventCenter.postEvent("resetScene",null,enableAdvertisement)}};gs.inherits(gs.ResetSceneAction,gs.StatelessBehavior);gs.RotateBehavior=gs.Behavior.subclass("RotateBehavior");gs.RotateBehavior.CLOCKWISE=0;gs.RotateBehavior.COUNTERCLOCKWISE=1;gs.RotateBehavior.init=function(){gs.Behavior.init.call(this);this.attributes.addRealExpressionAttribute("angularVelocity",90);this.attributes.addIntegerImmutableAttribute("direction",gs.RotateBehavior.COUNTERCLOCKWISE);this.attributes.addBooleanImmutableAttribute("haltWhenBehaviorStops",true);return this};gs.RotateBehavior.start=function(actor,timestamp){this.setAngularVelocity(this.attributes.angularVelocity.getValue());this._updatingSelf=false;this.attributes.angularVelocity.addObserver(this)};gs.RotateBehavior.observeValueChange=function(attribute,value){if(this._updatingSelf){return}this._updatingSelf=true;this.setAngularVelocity();this._updatingSelf=false};gs.RotateBehavior.setAngularVelocity=function(){var actor=this._entity;var degrees=this.attributes.angularVelocity.getValue();if(this.attributes.direction.getValue()==gs.RotateBehavior.CLOCKWISE){degrees=-degrees}actor.aspects.motion.attributes.angularVelocity.setValue(degrees)};gs.RotateBehavior.stop=function(actor,timestamp){if(this.attributes.haltWhenBehaviorStops.getValue()){var motionAspect=this._entity.aspects.motion;motionAspect.attributes.angularVelocity.setValue(0);this.attributes.angularVelocity.removeObserver(this);this._updatingSelf=null}};gs.RotateBehavior.willExit=function(actor){if(!this.attributes.haltWhenBehaviorStops.getValue()){this.attributes.angularVelocity.removeObserver(this)}gs.Behavior.willExit.call(this,actor)};gs.RotateToAngleBehavior=gs.CompletingBehavior.subclass("RotateToAngleBehavior");gs.RotateToAngleBehavior.init=function(){gs.CompletingBehavior.init.call(this);this.attributes.addRealExpressionAttribute("angle",0);this.attributes.addIntegerImmutableAttribute("space",gs.MoveBehavior.SPACE_ACTOR);this.attributes.addRealExpressionAttribute("angularVelocity",90);this.attributes.addBooleanImmutableAttribute("continuousMovement",false);return this};gs.RotateToAngleBehavior.standardAngle=function(angle){return angle%360};gs.RotateToAngleBehavior.angleEqual=function(angle1,angle2,angVel,timestamp){var distanceTraveled=angVel*timestamp;var distanceToTarget=this.standardAngle(angle2-angle1);if(distanceToTarget&gt;180){distanceToTarget=distanceToTarget-360}else if(distanceToTarget&lt;-180){distanceToTarget=distanceToTarget+360}return Math.abs(distanceToTarget)&lt;Math.abs(distanceTraveled)};gs.RotateToAngleBehavior.completeStart=function(actor,timestamp){gs.CompletingBehavior.completeStart.call(this,actor,timestamp);this._initialActorRotation=0;if(this.attributes.space.getValue()==gs.MoveBehavior.SPACE_ACTOR){var actor=this._entity;this._initialActorRotation=actor.attributes.rotation.getValue()}if(!this._isRotateToPosition){this._targetAngle=this.attributes.angle.getValue()}this.calculateTargetAngle();this.calculateAngularVelocity();this._updatingSelf=false;this.attributes.angle.addObserver(this);this.attributes.angularVelocity.addObserver(this)};gs.RotateToAngleBehavior.calculateTargetAngle=function(){if(this.attributes.space.getValue()==gs.MoveBehavior.SPACE_ACTOR){this._targetAngle=this._targetAngle+this._initialActorRotation}this._targetAngle=this.standardAngle(this._targetAngle)};gs.RotateToAngleBehavior.calculateAngularVelocity=function(){var actor=this._entity;var actorRotation=actor.attributes.rotation.getValue();actorRotation=this.standardAngle(actorRotation);var angleDifference=this._targetAngle-actorRotation;var degrees=this.attributes.angularVelocity.getValue();if(angleDifference&gt;180||angleDifference&lt;0&amp;&amp;angleDifference&gt;-180){degrees=-degrees}actor.aspects.motion.attributes.angularVelocity.setValue(degrees)};gs.RotateToAngleBehavior.observeValueChange=function(attribute,value){if(this._updatingSelf){return}this._updatingSelf=true;if(attribute===this.attributes.angle){this._targetAngle=value;this.calculateTargetAngle()}this._updateAngularVelocity=true;this._updatingSelf=false};gs.RotateToAngleBehavior.completeEvaluate=function(actor,timestamp){gs.CompletingBehavior.completeEvaluate.call(this,actor,timestamp);var actorRotation=actor.attributes.rotation.getValue();if(actorRotation&lt;0||actorRotation&gt;=360){actorRotation=this.standardAngle(actorRotation);actor.attributes.rotation.setValue(actorRotation)}if(this._updateAngularVelocity){this.calculateAngularVelocity();this._updateAngularVelocity=false}this._updatingSelf=true;var angVel=this.attributes.angularVelocity.getValue();this._updatingSelf=false;if(this.angleEqual(this._targetAngle,actorRotation,angVel,timestamp.dt)){actor.attributes.rotation.fastSetValue(this._targetAngle);actor.aspects.motion.attributes.angularVelocity.fastSetValue(0);if(!this.attributes.continuousMovement.getValue()){this.setCompleted(true)}}};gs.RotateToAngleBehavior.completeStop=function(actor,timestamp){gs.CompletingBehavior.completeStop.call(this,actor,timestamp);this.attributes.angle.removeObserver(this);this.attributes.angularVelocity.removeObserver(this);this._updatingSelf=null;actor.aspects.motion.attributes.angularVelocity.fastSetValue(0)};gs.RotateToPositionBehavior=gs.RotateToAngleBehavior.subclass("RotateToPositionBehavior");gs.RotateToPositionBehavior.init=function(){gs.RotateToAngleBehavior.init.call(this);this.attributes.addPointExpressionAttribute("position");this.attributes.addRealExpressionAttribute("offsetAngle",0);this.attributes.space.changeDefaultValue(gs.MoveBehavior.SPACE_SCENE);return this};gs.RotateToPositionBehavior.completeStart=function(actor,timestamp){this._isRotateToPosition=true;this.updatePositionAngle();this.attributes.position.x.addObserver(this);this.attributes.position.y.addObserver(this);this.attributes.offsetAngle.addObserver(this);if(this.attributes.space.getValue()==gs.MoveBehavior.SPACE_SCENE){actor.attributes.position.x.addObserver(this);actor.attributes.position.y.addObserver(this)}this._updatingSelf=false;gs.RotateToAngleBehavior.completeStart.call(this,actor,timestamp)};gs.RotateToPositionBehavior.updatePositionAngle=function(){var offsetAngle=this.standardAngle(this.attributes.offsetAngle.getValue());var adjustedPosition=gs.g_tempVec2d;adjustedPosition[0]=this.attributes.position.x.getValue();adjustedPosition[1]=this.attributes.position.y.getValue();var actor=this._entity;if(this.attributes.space.getValue()==gs.MoveBehavior.SPACE_SCENE){adjustedPosition[0]=adjustedPosition[0]-actor.attributes.position.x.getValue();adjustedPosition[1]=adjustedPosition[1]-actor.attributes.position.y.getValue()}var length=Math.sqrt(adjustedPosition[0]*adjustedPosition[0]+adjustedPosition[1]*adjustedPosition[1]);if(length&gt;0){adjustedPosition[0]=adjustedPosition[0]/length;adjustedPosition[1]=adjustedPosition[1]/length}else{adjustedPosition[0]=0;adjustedPosition[1]=0}var positionAngle=180/Math.PI*Math.atan2(adjustedPosition[1],adjustedPosition[0]);this._targetAngle=positionAngle+offsetAngle};gs.RotateToPositionBehavior.observeValueChange=function(attribute,value){if(this._updatingSelf){return}this._updatingSelf=true;this.updatePositionAngle();this._updatingSelf=false;gs.RotateToAngleBehavior.observeValueChange.call(this,this.attributes.angle,this._targetAngle)};gs.RotateToPositionBehavior.completeStop=function(actor,timestamp){gs.RotateToAngleBehavior.completeStop.call(this,actor,timestamp);this.attributes.position.x.removeObserver(this);this.attributes.position.y.removeObserver(this);this.attributes.offsetAngle.removeObserver(this);if(this.attributes.space.getValue()==gs.MoveBehavior.SPACE_SCENE){actor.attributes.position.x.removeObserver(this);actor.attributes.position.y.removeObserver(this)}this._updatingSelf=null};gs.RuleBehavior=gs.Behavior.subclass("RuleBehavior");gs.RuleBehavior.CONDITION_ALL=0;gs.RuleBehavior.CONDITION_ANY=1;gs.RuleBehavior._sharedAttributeCollection=new gs.ImmutableAttributeCollection;gs.RuleBehavior._sharedAttributeCollection.addIntegerImmutableAttribute("compoundConditionKind",0);gs.RuleBehavior.init=function(){this.compoundConditionKind=gs.RuleBehavior.CONDITION_ALL;this.behaviors=new gs.BehaviorList;this.behaviors._parent=this;return this};gs.RuleBehavior.initPrime=function(){this.behaviors=null;this.elseBehaviors=null;this.conditionStates=gs.array.provide();this.thenDidEnter=false;this.elseDidEnter=false;this.thenIsStarted=false;this.elseIsStarted=false;this._needsUpdate=false;this._registeredForEveryFrame=false;this.lastTest=false;this.actorTime=null;return this};gs.RuleBehavior.clone=function(){var other=gs.Behavior.clone.call(this);other.compoundConditionKind=this.compoundConditionKind;other.behaviors=this.behaviors.clone();other.behaviors._parent=other;if(this.elseBehaviors){other.elseBehaviors=this.elseBehaviors.clone();other.elseBehaviors._parent=other}return other};gs.RuleBehavior.testSingleCondition=function(){return this.conditionState};gs.RuleBehavior.testAllConditions=function(){var states=this.conditionStates;for(var i=0,iend=states.length;i&lt;iend;i++){if(!states[i]){return false}}return true};gs.RuleBehavior.testAnyConditions=function(){var states=this.conditionStates;for(var i=0,iend=states.length;i&lt;iend;i++){if(states[i]){return true}}return false};gs.RuleBehavior.start=function(actor,timestamp){this._needsUpdate=false;this._registeredForEveryFrame=false;if(this.condition){this.condition.start(actor,this);this.conditionState=this.condition.test()}else{var conditions=this.conditions.array;var conditionStates=this.conditionStates;for(var i=0,iend=conditions.length;i&lt;iend;i++){var condition=conditions[i];condition.start(actor,this);conditionStates[i]=condition.test()}}var currentTest=this.testConditionsFunction();if(currentTest){if(!this.thenDidEnter){this.behaviors.didEnter(actor,false);this.thenDidEnter=true}this.behaviors.start(actor,timestamp);this.thenIsStarted=true}else{if(!this.elseDidEnter){this.elseBehaviors&amp;&amp;this.elseBehaviors.didEnter(actor,false);this.elseDidEnter=true}this.elseBehaviors&amp;&amp;this.elseBehaviors.start(actor,timestamp);this.elseIsStarted=true}this.lastTest=currentTest;this.actorTime=timestamp};gs.RuleBehavior.stop=function(actor,timestamp){if(this.condition){this.condition.stop(actor)}else{var conditions=this.conditions.array;for(var i=0,iend=conditions.length;i&lt;iend;i++){conditions[i].stop(actor)}}if(this.lastTest){if(this.thenIsStarted){this.behaviors.stop(actor,timestamp);this.thenIsStarted=false}}else{if(this.elseIsStarted){this.elseBehaviors&amp;&amp;this.elseBehaviors.stop(actor,timestamp);this.elseIsStarted=false}}this.lastTest=null;this.actorTime=null;if(this._registeredForEveryFrame){this.deregisterForEveryFrame();this._registeredForEveryFrame=false}this._needsUpdate=false};gs.RuleBehavior.didEnter=function(actor,isInitTime){gs.Behavior.didEnter.call(this,actor,isInitTime);this.thenDidEnter=false;this.elseDidEnter=false;this.thenIsStarted=false;this.elseIsStarted=false;if(this.condition){this.conditionState=false;this.condition.didEnter(actor,isInitTime,this,0);this.testConditionsFunction=this.testSingleCondition}else{var conditions=this.conditions.array;var conditionCount=conditions.length;var conditionStates=this.conditionStates;if(!conditionStates){conditionStates=gs.array.provide();this.conditionStates=conditionStates}for(var i=0;i&lt;conditionCount;++i){conditionStates[i]=false;conditions[i].didEnter(actor,isInitTime,this,i)}if(this.compoundConditionKind===gs.RuleBehavior.CONDITION_ANY){this.testConditionsFunction=this.testAnyConditions}else{this.testConditionsFunction=this.testAllConditions}}this.behaviors.didEnter(actor,isInitTime);this.thenDidEnter=true;this.elseBehaviors&amp;&amp;this.elseBehaviors.didEnter(actor,isInitTime);this.elseDidEnter=true};gs.RuleBehavior.willExit=function(actor){if(this.thenDidEnter){this.behaviors.willExit(actor);this.thenDidEnter=false}if(this.elseDidEnter){this.elseBehaviors&amp;&amp;this.elseBehaviors.willExit(actor);this.elseDidEnter=false}if(this.condition){this.condition.willExit(actor)}else{var conditions=this.conditions.array;for(var i=0,iend=conditions.length;i&lt;iend;++i){conditions[i].willExit(actor)}}gs.Behavior.willExit.call(this,actor)};gs.RuleBehavior.conditionChangedState=function(index,state){if(!this.actorTime||typeof index!=="number"||!this.condition&amp;&amp;!this.conditionStates){return false}var beforeState=this.testConditionsFunction();if(this.condition){this.conditionState=state}else{this.conditionStates[index]=state}var afterState=this.testConditionsFunction();if(!this._needsUpdate){this._needsUpdate=true;if(!this._registeredForEveryFrame){this.registerForEveryFrame();this._registeredForEveryFrame=true}}return afterState!==beforeState};gs.RuleBehavior.everyFrame=function(actor,timestamp){this._needsUpdate=false;var currentTest=this.testConditionsFunction();if(this.lastTest!==currentTest){this.lastTest=currentTest;if(currentTest){if(this.elseIsStarted){this.elseBehaviors&amp;&amp;this.elseBehaviors.stop(actor,timestamp);this.elseIsStarted=false}if(!this.thenDidEnter){this.behaviors.didEnter(actor,false);this.thenDidEnter=true}this.behaviors.start(actor,timestamp);this.thenIsStarted=true}else{if(this.thenIsStarted){this.behaviors.stop(actor,timestamp);this.thenIsStarted=false}if(!this.elseDidEnter){this.elseBehaviors&amp;&amp;this.elseBehaviors.didEnter(actor,false);this.elseDidEnter=true}this.elseBehaviors&amp;&amp;this.elseBehaviors.start(actor,timestamp);this.elseIsStarted=true}}if(!this._needsUpdate){this.deregisterForEveryFrame();this._registeredForEveryFrame=false}};gs.RuleBehavior.loadFromLite=function(node,initialState){var attributes=node["attributes"];var conditions=node["conditions"];var behaviors=node["behaviors"];var elseBehaviors=node["elseBehaviors"];if(attributes){var tempAttributes=gs.RuleBehavior._sharedAttributeCollection;var compoundConditionKind=tempAttributes.compoundConditionKind;compoundConditionKind.changeDefaultValue(0);tempAttributes.loadFromLite(attributes,initialState);this.compoundConditionKind=compoundConditionKind.getValue()}if(conditions){if(!Array.isArray(conditions)){var condition=gs.Parser.parseCondition(conditions,initialState);this.setObjectForKey(condition,"condition")}else if(conditions.length===1){var condition=gs.Parser.parseCondition(conditions[0],initialState);this.setObjectForKey(condition,"condition")}else{this.setObjectForKey(gs.PrototypicalKeylessArray.provide().init("condition"),"conditions");this.conditions.loadFromLite(conditions,initialState)}}else{this.setObjectForKey(gs.PrototypicalKeylessArray.provide().init("condition"),"conditions")}if(behaviors){this.behaviors.loadFromLite(behaviors,initialState)}if(elseBehaviors&amp;&amp;(!Array.isArray(elseBehaviors)||elseBehaviors.length&gt;0)){this.elseBehaviors=new gs.BehaviorList;this.elseBehaviors._parent=this;this.elseBehaviors.loadFromLite(elseBehaviors,initialState)}};gs.RuleBehavior.loadFromTable=function(t,initialState){var gs_JXON=gs.JXON;var gs_JXON__type=gs_JXON._type;var gs_JXON__children=gs_JXON._children;var gs_Project_nodeTypeNameMap=gs.Project.nodeTypeNameMap;var children=t[gs_JXON__children];if(children){for(var i=0,iend=children.length;i&lt;iend;i++){var child=children[i];var grandchildren=child[gs_JXON__children];if(grandchildren&amp;&amp;grandchildren.length&gt;0){var tag=gs_Project_nodeTypeNameMap[child[gs_JXON__type]];if(tag==="conditions"){if(grandchildren.length===1){var condition=gs.Parser.parseCondition(grandchildren[0],initialState);this.setObjectForKey(condition,"condition")}else{this.setObjectForKey(gs.PrototypicalKeylessArray.provide().init(),"conditions");this.conditions.loadFromTable(grandchildren,initialState)}}else if(tag==="behaviors"){this.behaviors.loadFromTable(grandchildren,initialState)}else if(tag==="elseBehaviors"){this.setObjectForKey(gs.BehaviorList.provide().init(),"elseBehaviors");this.elseBehaviors.loadFromTable(grandchildren,initialState)}else if(tag==="attributes"){var attributes=gs.RuleBehavior._sharedAttributeCollection;var compoundConditionKind=attributes.compoundConditionKind;compoundConditionKind.changeDefaultValue(0);attributes.loadFromTable(grandchildren);this.compoundConditionKind=compoundConditionKind.getValue()}}}}};gs.RuleBehavior.getRequiredAssets=function(imageSet,soundSet,fontSet,strategy){this.behaviors.getRequiredAssets(imageSet,soundSet,fontSet,strategy);this.elseBehaviors&amp;&amp;this.elseBehaviors.getRequiredAssets(imageSet,soundSet,fontSet,strategy)};gs.RuleBehavior.getRequiredActors=function(actorSet,spawnableActorsOnly){this.behaviors.getRequiredActors(actorSet,spawnableActorsOnly);this.elseBehaviors&amp;&amp;this.elseBehaviors.getRequiredActors(actorSet,spawnableActorsOnly)};gs.SaveAttributeAction=gs.Behavior.subclass("SaveAttributeAction");gs.SaveAttributeAction.init=function(){gs.Behavior.init.call(this);this.attributes.addReferenceImmutableAttribute("targetAttribute");this.attributes.addVariantExpressionAttribute("key","");return this};gs.SaveAttributeAction.start=function(actor,timestamp){var reference=this.attributes.targetAttribute.getValue();if(!reference){return}var targetAttribute=reference.resolveRelativeTo(actor);if(!targetAttribute){return}var value=targetAttribute.getValue();var key=this.attributes.key.getValue();if(!key||key===""){gs.Log.warn("Saved attribute with empty name. value =",value)}else{}if(targetAttribute._type==="table"){var table=targetAttribute.getTableData();var data=gs.TableParser.serializeTableToFileFormat(table);gs.EngineContext.current.delegate.onSaveAttribute(key,data,function(){gs.LocalStorage.setObject(key,data)})}else{var data=value.toString();gs.EngineContext.current.delegate.onSaveAttribute(key,data,function(){gs.LocalStorage.setString(key,data)})}};gs.SaveTableAction=function(){gs.StatelessBehavior.call(this)};gs.SaveTableAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("tableID","")},start:function(actor,timestamp){var target=this.resolveTableReferenceAttribute(this.attributes.tableID);if(!target){return}var table=target.getTableData();var key=this.attributes.tableID.getValue();gs.EngineContext.current.delegate.onSaveTable(key,table,function(){gs.tables.saveToPersistence(table,key)})}};gs.inherits(gs.SaveTableAction,gs.StatelessBehavior);gs.ShowBannerBehavior=gs.Behavior.subclass("ShowBannerBehavior",{positionIntToString:{0:"top",1:"bottom"},init:function(){gs.Behavior.init.call(this);this.attributes.addIntegerExpressionAttribute("position",0);return this},showBanner:function(positionEnum){var positionString=gs.ShowBannerBehavior.positionIntToString[positionEnum];gs.EngineContext.current.delegate.onShowBannerShow(positionString)},hideBanner:function(){gs.EngineContext.current.delegate.onShowBannerHide()},start:function(actor,timestamp){var position=this.attributes.position.getValue();this.showBanner(position)},stop:function(actor,timestamp){this.hideBanner()}});gs.ShowMoreGamesAction=gs.Behavior.subclass("ShowMoreGamesAction");gs.ShowMoreGamesAction.start=function(actor,timestamp){this.doStub("showMoreGames","show")};gs.SpawnAction=function(){gs.StatelessBehavior.call(this)};gs.SpawnAction.SPACE_ACTOR=0;gs.SpawnAction.SPACE_SCENE=1;gs.SpawnAction.ORDER_FRONT_ACTOR=0;gs.SpawnAction.ORDER_BACK_ACTOR=1;gs.SpawnAction.ORDER_FRONT_LAYER=2;gs.SpawnAction.ORDER_BACK_LAYER=3;gs.SpawnAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("prototypeKey","");attributes.addRealExpressionAttribute("direction",0);attributes.addIntegerImmutableAttribute("directionSpace",gs.SpawnAction.SPACE_ACTOR);attributes.addRealExpressionAttribute("x",0);attributes.addRealExpressionAttribute("y",0);attributes.addIntegerImmutableAttribute("positionSpace",gs.SpawnAction.SPACE_ACTOR);attributes.addIntegerImmutableAttribute("layerOrder",gs.SpawnAction.ORDER_FRONT_ACTOR)},start:function(actor,timestamp){var scene=actor.scene;var x=this.attributes.x.getValueForEntityStateless(actor);var y=this.attributes.y.getValueForEntityStateless(actor);var direction=this.attributes.direction.getValueForEntityStateless(actor);if(this.attributes.positionSpace.getValue()===gs.SpawnAction.SPACE_ACTOR){var spawnVector=gs.g_tempVec2d;spawnVector[0]=x;spawnVector[1]=y;gs.Vector2.vectorRotate2D(spawnVector,spawnVector,actor.attributes.rotation.getValue()*gsMath.DEG2RAD);x=actor.attributes.position.x.getValue()+spawnVector[0];y=actor.attributes.position.y.getValue()+spawnVector[1]}if(!scene.isInBounds(x,y)){return}var prototypeID=this.attributes.prototypeKey.getValue();var spawn=gs.ActorFactory.current.spawnActorInstance(prototypeID);if(!spawn){return}if(this.attributes.directionSpace.getValue()==gs.SpawnAction.SPACE_SCENE){spawn.attributes.rotation.setValue(direction)}else{spawn.attributes.rotation.setValue(actor.attributes.rotation.getValue()+direction)}var layerOrder=this.attributes.layerOrder.getValue();var layerIndex=null;var layer=actor.layer;if(layerOrder==gs.SpawnAction.ORDER_FRONT_LAYER){layerIndex=layer.countActors()}else if(layerOrder==gs.SpawnAction.ORDER_BACK_LAYER){layerIndex=0}else if(layerOrder==gs.SpawnAction.ORDER_FRONT_ACTOR){layerIndex=layer.indexOfActor(actor)+1}else if(layerOrder==gs.SpawnAction.ORDER_BACK_ACTOR){layerIndex=layer.indexOfActor(actor)}spawn.attributes.position.x.setValue(x);spawn.attributes.position.y.setValue(y);scene.addActor(spawn,layer,layerIndex);spawn.start(scene.timebase.currentTimeStamp,scene.firstFrame)},getRequiredActors:function(actorSet,spawnableActorsOnly){var prototypeID=this.attributes.prototypeKey.getValue();var prototype=gs.ActorFactory.current.getActorPrototype(prototypeID);if(!prototype){gs.Log.warn("SpawnAction: invalid actor id:",prototypeID);return}if(actorSet[prototypeID]){actorSet[prototypeID]++;return}actorSet[prototypeID]=1;prototype.getRequiredActors(actorSet,spawnableActorsOnly)}};gs.inherits(gs.SpawnAction,gs.StatelessBehavior);gs.SpecialAction=function(){gs.StatelessBehavior.call(this)};gs.SpecialAction.prototype={declareAttributes:function(attributes){attributes.addStringImmutableAttribute("text","")},start:function(actor,timestamp){var data=this.attributes.text.getValue();gs.EngineContext.current.delegate.onSpecial(data)}};gs.inherits(gs.SpecialAction,gs.StatelessBehavior);gs.StopMusicAction=function(){gs.SingletonBehavior.call(this)};gs.StopMusicAction.prototype={start:function(actor,timestamp){gs.AudioManager.current.stopMusic()}};gs.inherits(gs.StopMusicAction,gs.SingletonBehavior);gs.singleton(gs.StopMusicAction);gs.TimerBehavior=gs.CompoundBehavior.subclass("TimerBehavior",{TYPE_REPEATING:0,TYPE_DELAY:1,TYPE_DURATION:2,init:function(){gs.CompoundBehavior.init.call(this);this.attributes.addIntegerImmutableAttribute("timerType",gs.TimerBehavior.TYPE_REPEATING);this.attributes.addRealExpressionAttribute("interval",5);this.attributes.addBooleanImmutableAttribute("runToCompletion",false);this._running=false;this._lastTest=false;this.type=0;this.interval=0;this.alreadyFired=false;this.firedCount=0;return this},initPrime:function(){this.attributes=null;this.behaviors=null;this._running=false;this._lastTest=false;this.type=0;this.interval=0;this.alreadyFired=false;this.firedCount=0;return this},start:function(actor,timestamp){if(this._running&amp;&amp;this.type===gs.TimerBehavior.TYPE_DELAY){this.finished(actor,timestamp);this.deregisterForEveryFrame()}if(!this._running){var timerType=this.attributes.timerType.getValue();var interval=Math.max(0,this.attributes.interval.getValue());this.initTimer(timerType,interval);this.startAtTime(timestamp.time);this._lastTest=false;this._running=true;this.registerForEveryFrame()}},finished:function(actor,timestamp){if(this._lastTest){gs.CompoundBehavior.stop.call(this,actor,timestamp)}this._lastTest=null;this._running=false},stop:function(actor,timestamp){if(!this._running){return}if(!this.attributes.runToCompletion.getValue()||this.type===gs.TimerBehavior.TYPE_REPEATING){this.finished(actor,timestamp);this.deregisterForEveryFrame()}},everyFrame:function(actor,timestamp){if(!this._running){return}var currentTest=this.stateForTime(timestamp.time);if(this._lastTest!==currentTest){if(currentTest){this._lastTest=true;gs.CompoundBehavior.start.call(this,actor,timestamp)}else{if(this.type===gs.TimerBehavior.TYPE_REPEATING){gs.CompoundBehavior.stop.call(this,actor,timestamp)}else{this.finished(actor,timestamp);this.deregisterForEveryFrame()}this._lastTest=false}}},willExit:function(actor){this.finished(actor,null);this.deregisterForEveryFrame();gs.CompoundBehavior.willExit.call(this,actor)},initTimer:function(type,interval){this.type=type;this.interval=interval;this.alreadyFired=false;this.firedCount=0},setInterval:function(interval){this.interval=interval},startAtTime:function(time){this.startTime=time;this.alreadyFired=false},stateForTime:function(time){var dt=time-this.startTime;switch(this.type){case gs.TimerBehavior.TYPE_REPEATING:if(this.alreadyFired){this.alreadyFired=false}else{var state=dt&gt;this.interval*(this.firedCount+1);if(state){this.alreadyFired=true;this.firedCount++}return state}return false;case gs.TimerBehavior.TYPE_DELAY:return dt&gt;this.interval;case gs.TimerBehavior.TYPE_DURATION:return dt&lt;=this.interval;default:return false}}});gs.UnpauseGameAction=function(){gs.SingletonBehavior.call(this)};gs.UnpauseGameAction.prototype={start:function(actor,timestamp){gs.Game.current.eventCenter.postEvent("endPauseScene")}};gs.inherits(gs.UnpauseGameAction,gs.SingletonBehavior);gs.singleton(gs.UnpauseGameAction);gs.ShowAdAction=gs.ShowBannerBehavior.subclass("ShowAdAction",{init:function(){gs.ShowBannerBehavior.init.call(this);this.attributes.addIntegerExpressionAttribute("location",0);return this},start:function(actor,timestamp){var position=this.attributes.location.getValue();this.showBanner(position)}});gs.ShowiAdBehavior=gs.ShowBannerBehavior.subclass("ShowiAdBehavior");gs.GameCenterLoginAction=gs.Behavior.subclass("GameCenterLoginAction",{init:function(){gs.Behavior.init.call(this);return this},onGCGameCenterLogin:function(){var game=gs.Game.current;game.attributes.platformConnected.setValue(true);game.eventCenter.deregisterForEvent("GCGameCenterLogin",this)},start:function(actor,timestamp){var game=gs.Game.current;var eventCenter=game.eventCenter;eventCenter.registerForEvent("GCGameCenterLogin",this,"onGCGameCenterLogin");var promise=gs.EngineContext.current.delegate.onGameCenterLogin();if(promise){promise.then(function(){eventCenter.postEvent("GCGameCenterLogin",null)})}}});gs.GameCenterPostScoreAction=gs.Behavior.subclass("GameCenterPostScoreAction",{init:function(){gs.Behavior.init.call(this);this.attributes.addReferenceImmutableAttribute("targetAttribute");this.attributes.addVariantExpressionAttribute("leaderboardCategory");return this},start:function(actor,timestamp){var score;var targetAttributeReference=this.attributes.targetAttribute.getValue();if(targetAttributeReference){var targetAttribute=targetAttributeReference.resolveRelativeTo(actor);if(targetAttribute){score=targetAttribute.getValue()}}var leaderboard=this.attributes.leaderboardCategory.getValueForEntity(actor);gs.EngineContext.current.delegate.onGameCenterPostScore(score,leaderboard)}});gs.GameCenterShowLeaderboardAction=gs.Behavior.subclass("GameCenterShowLeaderboardAction",{init:function(){gs.Behavior.init.call(this);this.attributes.addVariantExpressionAttribute("leaderboardCategory");return this},start:function(actor,timestamp){var leaderboard=this.attributes.leaderboardCategory.getValueForEntity(actor);gs.EngineContext.current.delegate.onGameCenterShowLeaderboard(leaderboard)}});gs.GameCenterShowAchievementsAction=gs.Behavior.subclass("GameCenterShowAchievementsAction",{init:function(){gs.Behavior.init.call(this);return this},start:function(actor,timestamp){gs.EngineContext.current.delegate.onGameCenterShowAchievements()}});gs.GameCenterResetAchievementsAction=gs.Behavior.subclass("GameCenterResetAchievementsAction",{init:function(){gs.Behavior.init.call(this);return this},start:function(actor,timestamp){gs.EngineContext.current.delegate.onGameCenterResetAchievements()}});gs.GameCenterUpdateAchievement=gs.Behavior.subclass("GameCenterUpdateAchievement",{init:function(){gs.Behavior.init.call(this);this.attributes.addStringExpressionAttribute("identifier","");this.attributes.addRealExpressionAttribute("percentageComplete",0);return this},start:function(actor,timestamp){var identifier=this.attributes.identifier.getValue();var percentageComplete=this.attributes.percentageComplete.getValue();gs.EngineContext.current.delegate.onGameCenterUpdateAchievement(identifier,percentageComplete)}});gs.InAppPurchaseItemAction=gs.Behavior.subclass("InAppPurchaseItemAction");gs.InAppPurchaseItemAction.init=function(){gs.Behavior.init.call(this);this.attributes.addVariantExpressionAttribute("itemIdentifier","");this.attributes.addReferenceImmutableAttribute("targetAttribute");this.attributes.addBooleanImmutableAttribute("consumable",false);this.attributes.addVariantExpressionAttribute("RHS","");this.attributes.addStringImmutableAttribute("successSceneKey","");this.attributes.addStringImmutableAttribute("cancelSceneKey","");this.attributes.addStringImmutableAttribute("errorSceneKey","");return this};gs.InAppPurchaseItemAction.start=function(actor,timestamp){if(gs.globalOptions.useBehaviorStubs){this.doStub("InAppPurchase","purchaseItem");return}var game=gs.Game.current;var eventCenter=game.eventCenter;if(game.isWaitingOnIAP){return}game.isWaitingOnIAP=true;gs.EngineContext.current.pause();eventCenter.registerForEvent("InAppSuccess",this,"InAppSuccess");eventCenter.registerForEvent("InAppCancelled",this,"InAppCancelled");eventCenter.registerForEvent("InAppFailure",this,"InAppFailure");this._actor=actor;var targetAttributeReference=this.attributes.targetAttribute.getValue();if(!targetAttributeReference){this.InAppFailure();return}var targetAttribute=targetAttributeReference.resolveRelativeTo(actor);if(!targetAttribute){this.InAppFailure();return}var itemId=this.attributes.itemIdentifier.getValueForEntity(actor);try{var service=gs.platform.PurchaseService.instance();service.purchaseItem(itemId)}catch(exception){gs.Log.error(exception);this.InAppFailure()}};gs.InAppPurchaseItemAction.InAppSuccess=function(){var game=gs.Game.current;var eventCenter=game.eventCenter;game.isWaitingOnIAP=false;gs.EngineContext.current.unpause();eventCenter.deregisterForEvent("InAppSuccess",this);eventCenter.deregisterForEvent("InAppCancelled",this);eventCenter.deregisterForEvent("InAppFailure",this);this.saveItemAttribute();var sceneKey=this.attributes.successSceneKey.getValue();if(sceneKey){eventCenter.postEvent("startPauseScene",null,sceneKey)}};gs.InAppPurchaseItemAction.InAppCancelled=function(){var game=gs.Game.current;var eventCenter=game.eventCenter;game.isWaitingOnIAP=false;gs.EngineContext.current.unpause();eventCenter.deregisterForEvent("InAppSuccess",this);eventCenter.deregisterForEvent("InAppCancelled",this);eventCenter.deregisterForEvent("InAppFailure",this);var sceneKey=this.attributes.cancelSceneKey.getValue();if(sceneKey){eventCenter.postEvent("startPauseScene",null,sceneKey)}};gs.InAppPurchaseItemAction.InAppFailure=function(){var game=gs.Game.current;var eventCenter=game.eventCenter;game.isWaitingOnIAP=false;gs.EngineContext.current.unpause();eventCenter.deregisterForEvent("InAppSuccess",this);eventCenter.deregisterForEvent("InAppCancelled",this);eventCenter.deregisterForEvent("InAppFailure",this);var sceneKey=this.attributes.errorSceneKey.getValue();if(sceneKey){eventCenter.postEvent("startPauseScene",null,sceneKey)}};gs.InAppPurchaseItemAction.saveItemAttribute=function(){var targetAttributeReference=this.attributes.targetAttribute.getValue();if(!targetAttributeReference){return}var targetAttribute=targetAttributeReference.resolveRelativeTo(this._actor);if(!targetAttribute){return}var consumable=this.attributes.consumable.getValue();if(consumable){targetAttribute.setValue(this.attributes.RHS.getValueForEntity(this._actor))}else{targetAttribute.setValue(true)}var value=targetAttribute.getValue();var key=this.attributes.itemIdentifier.getValue();gs.LocalStorage.setString(key,value.toString())};gs.InAppPurchaseRestoreItem=gs.Behavior.subclass("InAppPurchaseRestoreItem");gs.InAppPurchaseRestoreItem.init=function(){gs.Behavior.init.call(this);this.attributes.addReservedCompoundAttribute("iapitems","array",null,true);return this};gs.InAppPurchaseRestoreItem.start=function(actor,timestamp){if(gs.globalOptions.useBehaviorStubs){this.doStub("InAppPurchase","restoreItem");return}var game=gs.Game.current;var eventCenter=game.eventCenter;if(game.isWaitingOnIAP){return}var itemCount=this.attributes.iapitems.size();if(itemCount&lt;=0){return}var itemIds=gs.array.provide();for(var i=1;i&lt;=itemCount;i++){var iapitem=this.attributes.iapitems.at(i);itemIds.push(iapitem.first.getValueForEntity(actor))}this._actor=actor;game.isWaitingOnIAP=true;eventCenter.registerForEvent("InAppRestore",this,"InAppRestore");eventCenter.registerForEvent("InAppFailure",this,"InAppFailure");try{var service=gs.platform.PurchaseService.instance();service.restoreItems(itemIds)}catch(exception){gs.Log.error(exception);this.InAppFailure()}};gs.InAppPurchaseRestoreItem.InAppFailure=function(){var game=gs.Game.current;var eventCenter=game.eventCenter;game.isWaitingOnIAP=false;eventCenter.deregisterForEvent("InAppRestore",this);eventCenter.deregisterForEvent("InAppFailure",this)};gs.InAppPurchaseRestoreItem.InAppRestore=function(itemIds){var game=gs.Game.current;var eventCenter=game.eventCenter;game.isWaitingOnIAP=false;eventCenter.deregisterForEvent("InAppRestore",this);eventCenter.deregisterForEvent("InAppFailure",this);var itemCount=this.attributes.iapitems.size();for(var i=1;i&lt;=itemCount;i++){var iapitem=this.attributes.iapitems.at(i);var itemId=iapitem.first.getValueForEntity(this._actor);if(itemIds.indexOf(itemId)!==-1){var targetAttributeReference=gs.Reference.lookup(iapitem.second.getValue());if(targetAttributeReference){var targetAttribute=targetAttributeReference.resolveRelativeTo(this._actor);if(targetAttribute){targetAttribute.setValue(true);var value=targetAttribute.getValue();var key=itemId;gs.LocalStorage.setString(key,value.toString())}}}}};gs.IAPAction=gs.Behavior.subclass("IAPAction");gs.IAPAction.ROW_IDX_ID=1;gs.IAPAction.ROW_IDX_CONSUMABLE=2;gs.IAPAction.ROW_IDX_NAME=3;gs.IAPAction.ROW_IDX_PRICE=4;gs.IAPAction.ROW_IDX_STATE=5;gs.IAPAction.IAP_STATUS_PURCHASED="purchased";gs.IAPAction.IAP_STATUS_UNPURCHASED="unpurchased";gs.IAPAction.IAP_STATUS_PENDING="pending";gs.IAPAction.init=function(){gs.Behavior.init.call(this);this.attributes.addVariantExpressionAttribute("itemIdentifier",null);return this};gs.IAPAction.getPurchaseTable=function(){if(this.purchaseTable){return this.purchaseTable}else{var currentGame=gs.Game.current;var gameAttribs=currentGame.attributes;var purchaseTableIds=Object.keys(gameAttribs).filter(function(a){return a.match(/id.*/)}).filter(function(a){return"getName"in gameAttribs[a]&amp;&amp;gameAttribs[a].getName()==="PurchaseTable"});if(purchaseTableIds&amp;&amp;purchaseTableIds.length&gt;0){this.purchaseTable=currentGame.getTableAttribute(purchaseTableIds[0])}}return this.purchaseTable};gs.IAPAction.updateItemState=function(stateValue,itemID){itemID=itemID||this.attributes.itemIdentifier.getValueForEntity(this._actor);if(itemID){var purchaseTable=this.getPurchaseTable();var rowIndex=purchaseTable.searchColumn(itemID,1,1,purchaseTable.getRowCount(),"exact");purchaseTable.setCellSafe(rowIndex,gs.IAPAction.ROW_IDX_STATE,stateValue)}};gs.IAPAction.getItemInfo=function(itemID){itemID=itemID||this.attributes.itemIdentifier.getValueForEntity(this._actor);if(itemID){var purchaseTable=this.getPurchaseTable();var rowIndex=purchaseTable.searchColumn(itemID,1,1,purchaseTable.getRowCount(),"exact");return{itemID:itemID,consumable:purchaseTable.getCellSafe(rowIndex,gs.IAPAction.ROW_IDX_CONSUMABLE),name:purchaseTable.getCellSafe(rowIndex,gs.IAPAction.ROW_IDX_NAME),price:purchaseTable.getCellSafe(rowIndex,gs.IAPAction.ROW_IDX_PRICE),state:purchaseTable.getCellSafe(rowIndex,gs.IAPAction.ROW_IDX_STATE)}}return null};gs.IAPBuyItemAction=gs.IAPAction.subclass("IAPBuyItemAction");gs.IAPBuyItemAction.init=function(){gs.IAPAction.init.call(this);return this};gs.IAPBuyItemAction.start=function(actor,timestamp){var game=gs.Game.current;var eventCenter=game.eventCenter;if(game.isWaitingOnIAP){return}game.isWaitingOnIAP=true;eventCenter.registerForEvent("IAPSuccess",this,"InAppSuccess");eventCenter.registerForEvent("IAPCancelled",this,"InAppCancelled");eventCenter.registerForEvent("IAPFailure",this,"InAppFailure");this._actor=actor;try{var itemInfo=this.getItemInfo();this.updateItemState(gs.IAPAction.IAP_STATUS_PENDING);var service=gs.platform.PurchaseService.instance();service.purchaseItem(itemInfo)}catch(exception){gs.Log.error(exception);this.InAppFailure()}};gs.IAPBuyItemAction.InAppSuccess=function(){var game=gs.Game.current;var eventCenter=game.eventCenter;game.isWaitingOnIAP=false;eventCenter.deregisterForEvent("IAPSuccess",this);eventCenter.deregisterForEvent("IAPCancelled",this);eventCenter.deregisterForEvent("IAPFailure",this);this.updateItemState(gs.IAPAction.IAP_STATUS_PURCHASED)};gs.IAPBuyItemAction.InAppCancelled=function(){var game=gs.Game.current;var eventCenter=game.eventCenter;game.isWaitingOnIAP=false;eventCenter.deregisterForEvent("IAPSuccess",this);eventCenter.deregisterForEvent("IAPCancelled",this);eventCenter.deregisterForEvent("IAPFailure",this);this.updateItemState(gs.IAPAction.IAP_STATUS_UNPURCHASED)};gs.IAPBuyItemAction.InAppFailure=function(){var game=gs.Game.current;var eventCenter=game.eventCenter;game.isWaitingOnIAP=false;gs.EngineContext.current.unpause();eventCenter.deregisterForEvent("IAPSuccess",this);eventCenter.deregisterForEvent("IAPCancelled",this);eventCenter.deregisterForEvent("IAPFailure",this);this.updateItemState(gs.IAPAction.IAP_STATUS_UNPURCHASED)};gs.IAPConsumeItemAction=gs.IAPAction.subclass("IAPConsumeItemAction");gs.IAPConsumeItemAction.init=function(){gs.IAPAction.init.call(this);return this};gs.IAPConsumeItemAction.start=function(actor,timestamp){try{var game=gs.Game.current;var service=gs.platform.PurchaseService.instance();if("consumeItem"in service){var itemInfo=this.getItemInfo();var eventCenter=game.eventCenter;eventCenter.registerForEvent("IAPConsumeItemSuccess",this,"IAPConsumeItemSuccess");eventCenter.registerForEvent("IAPConsumeItemFailure",this,"IAPConsumeItemFailure");service.consumeItem(itemInfo)}else{this.IAPConsumeItemSuccess()}}catch(exception){gs.Log.error(exception)}};gs.IAPConsumeItemAction.IAPConsumeItemSuccess=function(){this.updateItemState(gs.IAPAction.IAP_STATUS_UNPURCHASED);gs.Log.debug("IAP Item cosumed ["+this.attributes.itemIdentifier.getValueForEntity(this._actor)+"]")};gs.IAPConsumeItemAction.IAPRestoreFailure=function(){gs.Log.debug("Failed to consume IAP Item ["+this.attributes.itemIdentifier.getValueForEntity(this._actor)+"]")};gs.IAPRequestPurchaseDataAction=gs.IAPAction.subclass("IAPRequestPurchaseDataAction");gs.IAPRequestPurchaseDataAction.init=function(){gs.IAPAction.init.call(this);this.attributes.addVariantExpressionAttribute("startIndex",1);this.attributes.addVariantExpressionAttribute("endIndex",1);this.attributes.addReferenceImmutableAttribute("callbackAttribute");return this};gs.IAPRequestPurchaseDataAction.start=function(actor,timestamp){try{var game=gs.Game.current;var eventCenter=game.eventCenter;this._actor=actor;eventCenter.registerForEvent("IAPPurchaseDataRequestSuccess",this,"IAPPurchaseDataRequestSuccess");eventCenter.registerForEvent("IAPPurchaseDataRequestFailure",this,"IAPPurchaseDataRequestFailure");var service=gs.platform.PurchaseService.instance();service.requestPurchaseData();var callbackAttributeRef=this.attributes.callbackAttribute.getValue();if(callbackAttributeRef){callbackAttributeRef.resolveRelativeTo(this._actor).setValue(0)}}catch(exception){gs.Log.error(exception)}};gs.IAPRequestPurchaseDataAction.IAPPurchaseDataRequestSuccess=function(info){if(!info){gs.Log.error("No IAP Item Info returned");return}var purchaseTable=this.getPurchaseTable();var startIndex=this.attributes.startIndex.getValueForEntity(this._actor);var endIndex=parseInt(this.attributes.endIndex.getValueForEntity(this._actor));if(endIndex&lt;0){endIndex=parseInt(purchaseTable.getRowCount())+endIndex+1}var rowIdMap={};for(var i=startIndex;i&lt;=endIndex;i++){var rowID=purchaseTable.getCellSafe(i,gs.IAPAction.ROW_IDX_ID);rowIdMap[rowID]=i}for(var i=0;i&lt;info.length;i++){var itemInfo=info[i];var itemRowIndex=rowIdMap[itemInfo.itemID];if(itemRowIndex&amp;&amp;itemRowIndex!==0){purchaseTable.setCellSafe(itemRowIndex,gs.IAPAction.ROW_IDX_NAME,itemInfo.name);purchaseTable.setCellSafe(itemRowIndex,gs.IAPAction.ROW_IDX_PRICE,itemInfo.price)}else{gs.Log.error("IAP Item Info was not found for ["+itemInfo.itemID+"]")}}var callbackAttributeRef=this.attributes.callbackAttribute.getValue();if(callbackAttributeRef){callbackAttributeRef.resolveRelativeTo(this._actor).setValue(1)}gs.Log.debug("IAP Item Info Updated.")};gs.IAPRequestPurchaseDataAction.IAPPurchaseDataRequestFailure=function(msg){gs.Log.error("Error retreiving IAP Item Info.");var callbackAttributeRef=this.attributes.callbackAttribute.getValue();if(callbackAttributeRef){callbackAttributeRef.resolveRelativeTo(this._actor).setValue(-1)}};gs.IAPRestoreItemsAction=gs.IAPAction.subclass("IAPRestoreItemsAction");gs.IAPRestoreItemsAction.init=function(){gs.IAPAction.init.call(this);return this};gs.IAPRestoreItemsAction.start=function(actor,timestamp){try{var game=gs.Game.current;var eventCenter=game.eventCenter;eventCenter.registerForEvent("IAPRestoreSuccess",this,"IAPRestoreSuccess");eventCenter.registerForEvent("IAPRestoreFailure",this,"IAPRestoreFailure");var service=gs.platform.PurchaseService.instance();service.restoreItems()}catch(exception){gs.Log.error(exception)}};gs.IAPRestoreItemsAction.IAPRestoreSuccess=function(purchases){if(purchases){var purchaseTable=this.getPurchaseTable();purchases.forEach(function(purchase){var itemID=purchase.itemID;this.updateItemState(gs.IAPAction.IAP_STATUS_PURCHASED,itemID)});gs.Log.debug("Purchases restored.")}};gs.IAPRestoreItemsAction.IAPRestoreFailure=function(){gs.Log.error("Failed to restore purchase.")};gs.TweetSheetAction=gs.Behavior.subclass("TweetSheetAction",{init:function(){gs.Behavior.init.call(this);this.attributes.addStringExpressionAttribute("message","");this.attributes.addBooleanImmutableAttribute("editable",true);this.attributes.addStringExpressionAttribute("image","");this.playSoundBehavior=null;this.playMusicBehavior=null;return this},start:function(actor,timestamp){var message=this.attributes.message.getValue();var editable=this.attributes.editable.getValue();var image=this.attributes.image.getValue();if(this.playAudio(timestamp,message)){return}if(this.playVideoUrl(timestamp,message)){return}gs.EngineContext.current.delegate.onTweetSheet(message,image,editable);this.stop()},stop:function(){var message=this.attributes.message.getValue();if(this.playSoundBehavior&amp;&amp;message.indexOf("gs:playSound")===0){this.playSoundBehavior.stop()}},willExit(){var message=this.attributes.message.getValue();if(self.playSoundBehavior&amp;&amp;message.indexOf("gs:playSound")===0){this.playSoundBehavior.willExit()}},playAudio:function(timestamp,message){var msgStr=message||this.attributes.message.getValue();if(msgStr.indexOf("gs:playSound")===0){if(this.playSoundBehavior===null){this.playSoundBehavior=gs.PlaySoundAction.provide().init();this.playSoundBehavior._parent=this._parent}else{this.playSoundBehavior.stop()}var soundName=this.attributes.image.getValue();this.playSoundBehavior.attributes.soundName.loadFromLite(soundName);var loopSound=msgStr.indexOf("Loop",12)===12;var playComplete=msgStr.indexOf("Complete",12)===12;this.playSoundBehavior.attributes.loop.loadFromLite(loopSound);this.playSoundBehavior.attributes.runToCompletion.loadFromLite(playComplete);this.playSoundBehavior.start(timestamp);return true}else if(msgStr.indexOf("gs:playMusic")===1){if(this.playMusicBehavior===null){this.playMusicBehavior=gs.PlayMusicAction.provide().init();this.playMusicBehavior._parent=this._parent}var musicName=this.attributes.image.getValue();this.playMusicBehavior.attributes.musicName.loadFromLite(musicName);var loopMusic=msgStr.indexOf("Loop",12)===12;this.playMusicBehavior.attributes.loop.loadFromLite(loopMusic);this.playMusicBehavior.start(timestamp);return true}return false},playVideoUrl:function(timestamp,message){var msgStr=message||this.attributes.message.getValue();if(msgStr.indexOf("gs:playVideoURL")!==0){return false}var viewPort=gs.EngineContext.current.renderContext.viewport;var videoEl=document.createElement("video");videoEl.width=viewPort.frameWidth;videoEl.height=viewPort.frameHeight;videoEl.crossorigin="anonymous";videoEl.style.width=`${viewPort.frameWidth}px`;videoEl.style.height=`${viewPort.frameHeight}px`;videoEl.style.position="absolute";videoEl.style.top=0;videoEl.style.left=0;videoEl.removeAttribute("controls");var currentScene=gs.Game.current.getCurrentScene();currentScene.pause(timestamp);function closeVideo(evt){viewPort.frame.removeChild(videoEl);videoEl=null;currentScene.resume(timestamp)}videoEl.addEventListener("error",closeVideo);videoEl.addEventListener("ended",closeVideo);videoEl.src=this.attributes.image.getValue();videoEl.autoplay=true;viewPort.frame.appendChild(videoEl);return true}});gs.EntityList=gs.PrototypicalArray.subclass("EntityList",{init:function(entityType){gs.PrototypicalArray.init.call(this);this.entityType=entityType;return this},loadFromLite:function(node,initialState){var parseFunction=null;switch(this.entityType){case"actor":parseFunction=gs.Parser.parseActor;break;case"layer":parseFunction=gs.Parser.parseLayer;break;case"condition":parseFunction=gs.Parser.parseCondition;break}if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){var entity=parseFunction(node[i],initialState);this.addObjectAtIndex(entity,i,node[i]["id"])}}else{var entity=parseFunction(node,initialState);this.addObjectAtIndex(entity,0,node["id"])}}});gs.LazySceneList=gs.PrototypicalArray.subclass("LazySceneList");gs.LazySceneList.init=function(){gs.PrototypicalArray.init.call(this);this.declaredScenes=gs.array.provide();return this};gs.LazySceneList.getScene=function(sceneKey,game){var scene=this[sceneKey];if(!scene){scene=this.loadScene(sceneKey,game)}return scene};gs.LazySceneList.numberOfScenes=function(){return this.declaredScenes.length};gs.LazySceneList.keyForScene=function(index){return this.declaredScenes[index]};gs.LazySceneList.sceneExists=function(sceneKey){var index=this.indexAndKey(sceneKey);return!!this.declaredScenes[index]};gs.LazySceneList.indexAndKey=function(keyOrIndex){if(typeof keyOrIndex==="number"){return keyOrIndex}else{var index=this.declaredScenes.indexOf(keyOrIndex);return index}};gs.LazySceneList.indexByKey=function(key){return 1+this.declaredScenes.indexOf(key)};gs.LazySceneList.unloadAllScenes=function(){var index;var count=this.declaredScenes.length;for(index=0;index&lt;count;++index){var sceneKey=this.declaredScenes[index];if(this[sceneKey]){this.unloadScene(sceneKey)}}};gs.LazySceneList.unloadScene=function(sceneKey){var scene=this[sceneKey];this.removeObjectForKey(sceneKey)};gs.LazySceneList.isSceneLoaded=function(sceneKey){return!!this[sceneKey]};gs.LazySceneList.inflateScene=function(sceneKey,sceneJXON){var that=this;return gs._yield(function(){gs.Game.profiler.sceneLoadProfiler.parse.enter();var scene=gs.Parser.parseScene(sceneJXON);gs.Game.profiler.sceneLoadProfiler.parse.exit();that.addObjectAtIndex(scene,null,sceneKey)})};gs.LazySceneList.loadScene=function(sceneKey,game){var sceneIndex=this.indexAndKey(sceneKey);if(sceneIndex&gt;=0){game.project.loadScene(sceneIndex,sceneKey)}};gs.LazySceneList.fetchSceneByIndex=function(index){if(index&lt;=this.declaredScenes.length){gs.file.VirtualFileCache.current.fetchSceneByIndex(index)}};gs.LazySceneList.fetchSceneByKey=function(key){var index=this.indexByKey(key);this.fetchSceneByIndex(index)};gs.LazySceneList.loadFromLite=function(node,initialState){if(Array.isArray(node)){for(var i=0;i&lt;node.length;i++){this.declaredScenes[i]=node[i]["id"]}}else{this.declaredScenes[0]=node["id"]}};gs.LazySceneList.loadFromTable=function(t){var declaredScenes=this.declaredScenes;var count=t.length;for(var i=0;i&lt;count;++i){var v=t[i];declaredScenes[i]=v.id}};gs.Layer=function(){gs.ObjectWithImmutableAttributes.call(this);this.scene=null;if(!this.actors){this.actors=gs.array.provide()}};gs.Layer.prototype={declareAttributes:function(attributes){if(!attributes.scrollable){attributes.addBooleanImmutableAttribute("scrollable",true)}},getScene:function(){return this.scene},game:function(){return gs.Game.instance},scrollable:function(){return this.attributes.scrollable.getValue()},countActors:function(){return this.actors.length},actorAtIndex:function(index){return this.actors[index]},indexOfActor:function(actor){return this.actors.indexOf(actor)},startAspects:function(sceneTime){var actors=this.actors;for(var i=0,iend=actors.length;i&lt;iend;i++){actors[i].startAspects(sceneTime)}},startBehaviors:function(sceneTime){var actors=this.actors;var actorsCopy=gs.array.provide();var i,count=actors.length;for(i=0;i&lt;count;i++){actorsCopy[i]=actors[i]}for(i=0;i&lt;count;++i){actorsCopy[i].startBehaviors(sceneTime,true)}gs.array.recycle(actorsCopy)},stop:function(sceneTime){var actors=this.actors;var i,count=actors.length;for(i=0;i&lt;count;i++){actors[i].stop(sceneTime)}for(i=0;i&lt;count;i++){actors[i].hideActor()}},evaluate:function(sceneTime){var actors=this.actors;var i,count=actors.length;for(i=0;i&lt;count;i++){actors[i].evaluate(sceneTime)}this.game().entityCounter.actors.add(count)},addActor:function(actor,index){this.actors.splice(index,0,actor);actor.layer=this;actor.scene=this.scene},removeActor:function(actor){var index=this.actors.indexOf(actor);if(index!==-1){this.actors.splice(index,1);actor.layer=null;actor.scene=null}},removeFromScene:function(){this.scene.layers.removeObject(this)},getRequiredActors:function(actorSet,spawnableActorsOnly){var actors=this.actors;for(var i=0,iend=actors.length;i&lt;iend;i++){var actor=actors[i];if(!spawnableActorsOnly){var prototypeID=actor._prototypeID;var prototype=gs.ActorFactory.current.getActorPrototype(prototypeID);actorSet[prototypeID]=1}actor.getRequiredActors(actorSet,spawnableActorsOnly)}},getActorInstances:function(actorSet){var actors=this.actors;for(var i=0,iend=actors.length;i&lt;iend;i++){var actor=actors[i];actorSet[actor._objectKey]=actor}},loadFromLite:function(node){gs.Entity.loadFromLite.call(this,node);var actors=node["actors"];if(actors){gs.ObjectListWithKeys.prototype.loadFromLite.call(this.actors,gs.Parser.parseActor,actors,false)}for(var i=0,iend=this.actors.length;i&lt;iend;i++){this.actors[i].layer=this}},recycleThis:function(){this.attributes.scrollable.changeDefaultValue(true);gs.ObjectListWithKeys.prototype.clear.call(this.actors);this.scene=null;gs.Layer.recycle(this)}};gs.inherits(gs.Layer,gs.ObjectWithImmutableAttributes);gs.Pool.init(gs.Layer);gs.Entity=gs.PrototypicalDictionary.subclass("Entity");gs.Entity.init=function(){gs.PrototypicalDictionary.init.call(this);this.setObjectForKey(new gs.MutableAttributeCollection,"attributes");this.attributes.addRealMutableAttribute("time",0);return this};gs.Entity.start=function(timestamp){this.attributes.time.fastSetValue(timestamp.time)};gs.Entity.stop=function(timestamp){};gs.Entity.game=function(){return gs.Game.instance};gs.Entity.resolveReference=function(reference){return reference.resolveRelativeTo(this)};gs.Entity.resolveKeypath=function(keypath){var reference=gs.Reference.lookup(keypath);return this.resolveReference(reference)};gs.Entity.loadFromLite=function(node,initialState){var id=node["id"];var attributes=node["attributes"];if(id){this._objectKey=id}if(attributes){this.attributes.loadFromLite(attributes,initialState)}};gs.Actor=gs.Entity.subclass("Actor");gs.Actor.defaultSize={width:100,height:100};gs.Actor.sharedTestPoint=[0,0];gs.Actor.init=function(){gs.Entity.init.call(this);this.initialBehaviors=new gs.BehaviorList;this.behaviors=this.initialBehaviors;this.behaviors._parent=this;this.setObjectForKey(gs.AspectList.provide().init(),"aspects");this.attributes.addStringMutableAttribute("name","New Name");this.attributes.addPointMutableAttribute("position",0,0);this.attributes.addImmutableAttributeCollection("size");var size=this.attributes.size;size.addRealPositiveMutableAttribute("width",gs.Actor.defaultSize.width);size.addRealPositiveMutableAttribute("height",gs.Actor.defaultSize.height);this.attributes.addRealAngleMutableAttribute("rotation",0);this.attributes.rotation._isRotationAttribute=true;this.attributes.addColorMutableAttribute("color",1,1,1,1);this.attributes.addStringMutableAttribute("image","");this.attributes.addStringMutableAttribute("tags",null);this.attributes.addBooleanMutableAttribute("preloadArt",true);this.aspects.addAspect("graphics");this.aspects.addAspect("motion");this.aspects.addAspect("physics");this._prototype=this;this._entity=this;return this};gs.Actor.clone=function(){var other=gs.Entity.clone.call(this);other._prototypeID=this._prototypeID;other._prototype=this;other.cachedTagString=this.cachedTagString;other.cachedTagList=this.cachedTagList;other.initialBehaviors=this.initialBehaviors.clone();other.initialBehaviors._parent=other;other.behaviors=other.initialBehaviors;other._entity=other;return other};gs.Actor.visible=function(){return this.aspects.graphics.attributes.visible.getValue()};gs.Actor.start=function(timestamp,isInitTime){this.startAspects(timestamp);this.startBehaviors(timestamp,isInitTime)};gs.Actor.checkReceivedCollisions=function(){var collisionController=this.scene._collisionController;var receivedSensors=collisionController.sensorRegistrationCountForCategory(this._prototypeID);var receivedCollisions=collisionController.collisionRegistrationCountForCategory(this._prototypeID);var tags=this.tags();var tagCount=tags.length;for(var i=0;i&lt;tagCount;++i){receivedSensors=receivedSensors+collisionController.sensorRegistrationCountForCategory(tags[i]);receivedCollisions=receivedCollisions+collisionController.collisionRegistrationCountForCategory(tags[i])}if(receivedCollisions&gt;0){this.receivedCollisions=receivedCollisions;this.aspects.addAspect("collisionShape");this.aspects.motion._body.setAwake(true)}if(receivedSensors&gt;0){this.receivedSensors=receivedSensors;this.aspects.addAspect("collisionSensor")}};gs.Actor.startAspects=function(timestamp){if(this.visible()){this.game().eventCenter.registerForEvent("startedWrap",this,"startWrap",null,this);this.game().eventCenter.registerForEvent("finishedWrap",this,"stopWrap",null,this)}this.receivedCollisions=0;this.receivedSensors=0;this.everyFrameBehaviors=gs.array.provide();this._currentEFIndex=0;this.timebase=gs.Timebase.provide().initWithTime(timestamp);this.timebase.convertTimeStamp(timestamp);this.actorTime=this.timebase.getTimeStamp();this.aspects.start(this,this.actorTime);this.checkReceivedCollisions()};gs.Actor.startBehaviors=function(timestamp,isInitTime){gs.Entity.start.call(this,this.actorTime);this.behaviors.didEnter(this,isInitTime);this.behaviors.start(this,this.actorTime)};gs.Actor.stop=function(timestamp){this.game().eventCenter.deregisterForEvent("startedWrap",this,this);this.game().eventCenter.deregisterForEvent("finishedWrap",this,this);if(this.timebase){this.timebase.convertTimeStamp(timestamp)}else{console.log("No Timebase Stopping behavior",actor)}gs.Entity.stop.call(this,this.actorTime);this.behaviors.stop(this,this.actorTime);this.behaviors.willExit(this);this.aspects.stop(this,this.actorTime);this.actorTime=null;if(this.timebase){gs.Timebase.recycle(this.timebase);this.timebase=null}if(this.everyFrameBehaviors){gs.array.recycle(this.everyFrameBehaviors);this.everyFrameBehaviors=null}this._currentEFIndex=0;this.restoreInitialState()};gs.Actor.evaluate=function(timestamp){if(this.timebase){this.timebase.convertTimeStamp(timestamp)}else{console.log("No timebase when evaluating: ",timestamp,"\n",this)}var actorTime=this.actorTime||0;this.attributes.time.fastSetValue(actorTime.time);this.aspects.motion.evaluate(this,actorTime);this.everyFrame(actorTime)};gs.Actor.everyFrame=gs.NOOP_FUNCTION;gs.Actor.everyFrameMethod=function(timestamp){var everyFrameBehaviors=this.everyFrameBehaviors;this._currentEFIndex=0;while(this._currentEFIndex&lt;everyFrameBehaviors.length){var behavior=everyFrameBehaviors[this._currentEFIndex];behavior.everyFrame(this,timestamp);this._currentEFIndex++}this._currentEFIndex=0};gs.Actor.registerForEveryFrame=function(behavior){this.everyFrameBehaviors.push(behavior);if(this.everyFrameBehaviors.length===1){this.everyFrame=gs.Actor.everyFrameMethod}};gs.Actor.deregisterForEveryFrame=function(behavior){var everyFrameBehaviors=this.everyFrameBehaviors;var index=everyFrameBehaviors.indexOf(behavior);if(index&gt;-1){if(index&lt;=this._currentEFIndex){this._currentEFIndex=this._currentEFIndex-1}everyFrameBehaviors.splice(index,1);if(everyFrameBehaviors.length===0){this.everyFrame=gs.NOOP_FUNCTION}}};gs.Actor.testPoint=function(point){var shapeAspect=this.aspects.collisionShape||this.aspects.collisionSensor;if(shapeAspect&amp;&amp;shapeAspect.fixtures&amp;&amp;shapeAspect.fixtures.length&gt;0){return shapeAspect.testPoint(point)}else{var halfWidth=this.attributes.size.width.getValue()*.5;var halfHeight=this.attributes.size.height.getValue()*.5;var cx=this.attributes.position.x.getValue();var cy=this.attributes.position.y.getValue();var pt=gs.Actor.sharedTestPoint;pt[0]=point[0]-cx;pt[1]=point[1]-cy;var shape=this.aspects.physics.attributes.collisionShape.getValue();if(shape===gs.PhysicsAspect.CIRCLE_SHAPE){var r=Math.min(halfWidth,halfHeight);return pt[0]*pt[0]+pt[1]*pt[1]&lt;=r*r}else{var angle=this.attributes.rotation.getValue();if(angle!==0){gs.Vector2.vectorRotate2D(pt,pt,angle*-gsMath.DEG2RAD)}return pt[0]&gt;=-halfWidth&amp;&amp;pt[0]&lt;=halfWidth&amp;&amp;pt[1]&gt;=-halfHeight&amp;&amp;pt[1]&lt;=halfHeight}}};gs.Actor.sharedEmptyTags=[];gs.Actor.tags=function(){var tagString=this.attributes.tags.getValue();if(!this.cachedTagList||this.cachedTagString!==tagString){this.cachedTagString=tagString;if(!tagString||tagString===""){this.cachedTagList=gs.Actor.sharedEmptyTags}else{this.cachedTagList=tagString.split("\t")}}return this.cachedTagList};gs.Actor.hasTag=function(tag){var tags=this.tags();return tags.indexOf(tag)!==-1};gs.Actor.loadFromLite=function(node,initialState){gs.Entity.loadFromLite.call(this,node,initialState);var prototype=node["prototype"];var aspects=node["aspects"];var behaviors=node["behaviors"];if(prototype){this._prototypeID=prototype}if(aspects){this.aspects.loadFromLite(aspects,initialState)}if(behaviors){if(initialState){this.initialBehaviors=this.behaviors}else{this.behaviors=new gs.BehaviorList;this.behaviors._parent=this}this.behaviors.loadFromLite(behaviors,initialState)}if(!initialState){var thisImage=this.attributes.image._value;var graphics=this.aspects.graphics.attributes;var prototypeImage=this.attributes.image._initialValue;if(thisImage!==prototypeImage){if(graphics.tileWidth._value===graphics.tileWidth._initialValue){graphics.tileWidth.setValue(0)}if(graphics.tileHeight._value===graphics.tileHeight._initialValue){graphics.tileHeight.setValue(0)}}}var tags=this.tags()};gs.Actor.loadFromTable=function(t,initialState){gs.Entity.loadFromTable.call(this,t,initialState);var prototypeID=t["prototype"];if(prototypeID){this._prototypeID=prototypeID}var table=t[gs.JXON._children];if(!table){return}var itemCount=table.length;for(var i=0;i&lt;itemCount;++i){var node=table[i];var nodetype=gs.Project.nodeTypeNameMap[node[gs.JXON._type]];switch(nodetype){case"behaviors":this.behaviors.loadFromTable(node[gs.JXON._children],initialState);break;case"aspects":this.aspects.loadFromTable(node[gs.JXON._children],initialState);break}}if(!initialState){var thisImage=this.attributes.image._value;var graphics=this.aspects.graphics.attributes;var prototypeImage=this.attributes.image._initialValue;if(thisImage!==prototypeImage){if(graphics.tileWidth._value===graphics.tileWidth._initialValue){graphics.tileWidth.setValue(0)}if(graphics.tileHeight._value===graphics.tileHeight._initialValue){graphics.tileHeight.setValue(0)}}}var tags=this.tags()};gs.Actor.restoreInitialState=function(){this.attributes.restoreInitialState();this.aspects.restoreInitialState();this.behaviors=this.initialBehaviors};gs.Actor.getRequiredAssets=function(imageSet,soundSet,fontSet,strategy,spawn){var preloadArt=this.attributes.preloadArt.getValue();var imageName=this.attributes.image.getValue();var hasInitialImage=imageName&amp;&amp;imageName.length&gt;0;var loadInitialImage;var recurseIntoBehaviors;switch(strategy){case gs.LoadStrategyOption.NONE:loadInitialImage=false;recurseIntoBehaviors=false;break;case gs.LoadStrategyOption.INITIAL:loadInitialImage=!spawn;recurseIntoBehaviors=false;break;case gs.LoadStrategyOption.LATENCY:loadInitialImage=!spawn;recurseIntoBehaviors=preloadArt&amp;&amp;!hasInitialImage;break;case gs.LoadStrategyOption.SAFE:loadInitialImage=!spawn;recurseIntoBehaviors=preloadArt;break;case gs.LoadStrategyOption.SCENE:case gs.LoadStrategyOption.GAME:loadInitialImage=true;recurseIntoBehaviors=true;break;case gs.LoadStrategyOption.STRICT:default:loadInitialImage=preloadArt;recurseIntoBehaviors=preloadArt;break}if(hasInitialImage&amp;&amp;loadInitialImage){imageSet[imageName]=true;var wrapS=this.aspects.graphics.attributes.horizontalWrap.getValue();var wrapT=this.aspects.graphics.attributes.verticalWrap.getValue();if(wrapS===gs.SGWrapMode.SGWrapTile||wrapT===gs.SGWrapMode.SGWrapTile){gs.AssetManager.current.imageForNamePow2(imageName)}}if(recurseIntoBehaviors){this.behaviors.getRequiredAssets(imageSet,soundSet,fontSet,strategy)}};gs.Actor.getRequiredActors=function(actorSet,spawnableActorsOnly){this.behaviors.getRequiredActors(actorSet,spawnableActorsOnly)};gs.Actor.fileExtension=function(){return"actor"};gs.Actor.matchesCategory=function(categoryString){if(this._prototypeID===categoryString){return true}return this.hasTag(categoryString)};gs.Game=gs.Entity.subclass("Game");gs.Game.instance=null;gs.Game.current=null;gs.Game.IPHONE_SCREEN_WIDTH=480;gs.Game.IPHONE_SCREEN_HEIGHT=320;gs.Game.addAccessors(["currentSceneKey"],["getCurrentSceneKey"]);gs.Game.addMutators(["currentSceneKey"],["setCurrentSceneKey"]);gs.Game.isWaitingOnKeyboardInput=false;gs.Game.init=function(){gs.Game.instance=this;gs.Game.current=this;gs.Entity.init.call(this);this.actorFactory=gs.ActorFactory.instance();this.primeInitialPools();this.primeBox2D();this.setObjectForKey(gs.LazySceneList.provide().init(),"scenes");this.collisionCategoryManager=new gs.CollisionCategoryManager;this.attributes.addSizeMutableAttribute("displaySize",gs.Game.IPHONE_SCREEN_WIDTH,gs.Game.IPHONE_SCREEN_HEIGHT);this.attributes.addStringImmutableAttribute("actorTags","");this.attributes.addReservedCompoundAttribute("manifests","compound");this.attributes.addBooleanMutableAttribute("platformConnected",false);this.attributes.addImmutableAttributeCollection("adReward");this.attributes.adReward.addIntegerMutableAttribute("value",0);this.attributes.adReward.addStringMutableAttribute("name","");this.attributes.addIntegerMutableAttribute("playerType",1);var _this=this;for(var i=1;i&lt;9;i++){var keymapKey="player"+i+" Keymap";this.attributes.addImmutableAttributeCollection(keymapKey);["buttonA","buttonB","buttonX","buttonY","leftShoulder1","rightShoulder1","leftShoulder2","rightShoulder2","select","start","leftStickClick","rightStickClick","dpadUp","dpadDown","dpadLeft","dpadRight"].forEach(function(btn){_this.attributes[keymapKey].addStringMutableAttribute(btn)})}this.resolution=0;this.resolutionIndependence=0;this.isWaitingOnPurchaseItem=false;this.setupDevices();this.setupServices();this.setupNetworking();this.sceneChangeEnabled=true;this.resetSceneEnabled=true;this.resetGameEnabled=true;this.currentSceneStack=gs.array.provide();this.sceneChangeMethod=gs.NOOP_FUNCTION;this.sceneLoadedMethod=null;this.deferredOpenURL=null;this.externalBrowser=false;this.tableLookupCache={};this.viewScaleX=1;this.viewScaleY=1;this.loadingFlag=false;this.firstFrameAfterLoading=false;this.texturePrimeFrames=0;this.prototypeCount=0;this.prototypeProgress=0;this.prototypeBatchSize=gs.globalOptions.actorPrototypeBatchSize;this.promiseGameParsed=new gs.Promise;this.inputEventTarget=null;this.inputEventTargetDetected=false;this.accelerometer=gs.platform.AccelerometerService.instance();this.accelerometer.init(this);this.joysticks=gs.platform.JoystickService.instance();this.joysticks.init(this);this.frameProfiler=new gs.FrameProfiler;this.entityCounter=new gs.EntityCounter;this.sceneLoadProfiler=new gs.LoadProfiler;gs.Game.profiler={frameProfiler:this.frameProfiler,entityCounter:this.entityCounter,sceneLoadProfiler:this.sceneLoadProfiler};this.openURLView=false;this.openURLViewID=null;this.purchaseItemView=false;this.purchaseItemViewID=null;this.gameCenterView=false;this.gameCenterViewID=null;this.postScoreView=false;this.postScoreViewID=null;this.achivementView=false;this.achivementViewID=null;this.adView=false;this.adViewID=null;return this};function getBrowserName(){var sUsrAg=navigator.userAgent;var sBrowser="unknown";if(sUsrAg.indexOf("Firefox")&gt;-1){sBrowser="Mozilla Firefox"}else if(sUsrAg.indexOf("SamsungBrowser")&gt;-1){sBrowser="Samsung Internet"}else if(sUsrAg.indexOf("Opera")&gt;-1||sUsrAg.indexOf("OPR")&gt;-1){sBrowser="Opera"}else if(sUsrAg.indexOf("Trident")&gt;-1){sBrowser="Microsoft Internet Explorer"}else if(sUsrAg.indexOf("Edge")&gt;-1){sBrowser="Microsoft Edge"}else if(sUsrAg.indexOf("Chrome")&gt;-1){sBrowser="Google Chrome or Chromium"}else if(sUsrAg.indexOf("Safari")&gt;-1){sBrowser="Apple Safari"}return sBrowser}gs.Game.setupDevices=function(){this.setObjectForKey(new gs.ImmutableAttributeCollection,"devices");this.devices.addImmutableAttributeCollection("mouse");this.devices.mouse.addPointMutableAttribute("position",0,0);this.devices.mouse.addBooleanMutableAttribute("button",false);this.devices.addImmutableAttributeCollection("touches");this.devices.touches.addIntegerMutableAttribute("count",0);this.devices.touches.addImmutableAttributeCollection("active");this.devices.touches.active.addBooleanMutableAttribute("touch1",false);this.devices.touches.active.addBooleanMutableAttribute("touch2",false);this.devices.touches.active.addBooleanMutableAttribute("touch3",false);this.devices.touches.active.addBooleanMutableAttribute("touch4",false);this.devices.touches.active.addBooleanMutableAttribute("touch5",false);this.devices.touches.active.addBooleanMutableAttribute("touch6",false);this.devices.touches.active.addBooleanMutableAttribute("touch7",false);this.devices.touches.active.addBooleanMutableAttribute("touch8",false);this.devices.touches.active.addBooleanMutableAttribute("touch9",false);this.devices.touches.active.addBooleanMutableAttribute("touch10",false);this.devices.touches.active.addBooleanMutableAttribute("touch11",false);this.devices.touches.addPointMutableAttribute("touch1",0,0);this.devices.touches.addPointMutableAttribute("touch2",0,0);this.devices.touches.addPointMutableAttribute("touch3",0,0);this.devices.touches.addPointMutableAttribute("touch4",0,0);this.devices.touches.addPointMutableAttribute("touch5",0,0);this.devices.touches.addPointMutableAttribute("touch6",0,0);this.devices.touches.addPointMutableAttribute("touch7",0,0);this.devices.touches.addPointMutableAttribute("touch8",0,0);this.devices.touches.addPointMutableAttribute("touch9",0,0);this.devices.touches.addPointMutableAttribute("touch10",0,0);this.devices.touches.addPointMutableAttribute("touch11",0,0);this.devices.addImmutableAttributeCollection("accelerometer");this.devices.accelerometer.addRealMutableAttribute("x",0);this.devices.accelerometer.addRealMutableAttribute("y",0);this.devices.accelerometer.addRealMutableAttribute("z",0);this.devices.addImmutableAttributeCollection("screen");this.devices.screen.addSizeMutableAttribute("size",gs.Game.IPHONE_SCREEN_WIDTH,gs.Game.IPHONE_SCREEN_HEIGHT);this.devices.screen.addIntegerMutableAttribute("deviceOrientation",0);this.devices.screen.addIntegerMutableAttribute("interfaceOrientation",6);this.devices.screen.addRealAngleMutableAttribute("deviceRotation",0);this.devices.addImmutableAttributeCollection("audio");this.devices.audio.addRealNormalizedMutableAttribute("soundVolume",1);this.devices.audio.addRealNormalizedMutableAttribute("musicVolume",1);this.devices.addImmutableAttributeCollection("clock");this.devices.clock.addIntegerMutableAttribute("year",0);this.devices.clock.addIntegerMutableAttribute("month",0);this.devices.clock.addIntegerMutableAttribute("day",0);this.devices.clock.addIntegerMutableAttribute("hour",0);this.devices.clock.addIntegerMutableAttribute("minute",0);this.devices.clock.addIntegerMutableAttribute("second",0);this.devices.clock.addIntegerMutableAttribute("millisecond",0);this.devices.clock.addIntegerMutableAttribute("epochTime",0);var locale=navigator.language.split("-");this.devices.addImmutableAttributeCollection("platform");this.devices.platform.addStringMutableAttribute("region",locale.length&gt;1?locale[1]:"us");this.devices.platform.addStringMutableAttribute("language",locale[0]);this.devices.platform.addStringImmutableAttribute("name","browser");this.devices.platform.addStringImmutableAttribute("deviceModel",getBrowserName());this.devices.platform.addStringImmutableAttribute("version",navigator.appVersion);this.devices.addImmutableAttributeCollection("players");for(var i=1;i&lt;8;i++){var playerKey="player"+i;this.devices.players.addImmutableAttributeCollection(playerKey);var player=this.devices.players[playerKey];player.addImmutableAttributeCollection("joystick");player.joystick.addBooleanMutableAttribute("connected",false);player.joystick.addStringMutableAttribute("name","unknown");player.joystick.addIntegerMutableAttribute("vendorID",-1);player.joystick.addIntegerMutableAttribute("productID",-1);Object.keys(gs.Game.DEFAULT_JOYSTICK_INPUT_VALUES).forEach(function(input){switch(input){case"leftStickX":case"leftStickY":case"rightStickX":case"rightStickY":player.addRealMutableAttribute(input,0);break;case"leftTrigger":case"rightTrigger":player.addRealMutableAttribute(input,-1);default:player.addBooleanMutableAttribute(input,false)}})}};gs.Game.setupServices=function(){this.setObjectForKey(new gs.ImmutableAttributeCollection,"services");this.services.addImmutableAttributeCollection("purchases");this.services.purchases.addIntegerMutableAttribute("status",0);this.services.purchases.addIntegerMutableAttribute("item",0)};gs.Game.setupNetworking=function(){this.attributes.addImmutableAttributeCollection("networking");this.attributes.networking.addBooleanMutableAttribute("connected",false);this.attributes.networking.addIntegerMutableAttribute("lastError",0)};gs.Game.setupCollisionCategories=function(){this.collisionCategoryManager.resetCollisionCategories();var prototypeIDs=this.actorFactory.getPrototypeIDs();for(var i=0,iend=prototypeIDs.length;i&lt;iend;i++){this.collisionCategoryManager.addCollisionCategory(prototypeIDs[i])}var tags=this.actorTags();for(i=0,iend=tags.length;i&lt;iend;i++){this.collisionCategoryManager.addCollisionCategory(tags[i])}};gs.Game.getCurrentSceneKey=function(){return this._currentSceneKey};gs.Game.setCurrentSceneKey=function(sceneKey){this._currentSceneKey=sceneKey;this.currentScene=this.getCurrentScene()};gs.Game.getCurrentScene=function(){var currSceneKey=this._currentSceneKey;var scene=this.safeGetScene(currSceneKey);return scene};gs.Game.safeGetScene=function(sceneKey){if(sceneKey===undefined||sceneKey===null){return null}else{return this.scenes.getScene(sceneKey,this)}};gs.Game.pushScene=function(sceneKey,timestamp){var currentScene=this.getCurrentScene();if(currentScene&amp;&amp;currentScene.hasStarted()){currentScene.pause(timestamp)}this.setValueForKey(sceneKey,"currentSceneKey");this.deviceOrientationChanged(this.devices.screen.deviceOrientation.getValue(),false);if(sceneKey!==null){var newCurrentScene=this.getCurrentScene();this.currentSceneStack.push(newCurrentScene);var renderingOverExistingScenes=this.currentSceneStack.length&gt;1;newCurrentScene.showScene(!renderingOverExistingScenes);if(!newCurrentScene.hasStarted()){newCurrentScene.start(timestamp)}if(typeof sceneKey==="number"){this.setCurrentSceneKey(newCurrentScene._objectKey)}}};gs.Game.popScene=function(timestamp){var currentScene=this.getCurrentScene();this.tearDownScene(currentScene,timestamp);this.currentSceneStack.pop();var newCurrentScene=this.currentSceneStack[this.currentSceneStack.length-1];if(newCurrentScene){var newCurrentSceneKey=newCurrentScene._objectKey;this.setValueForKey(newCurrentSceneKey,"currentSceneKey");if(true){this.deviceOrientationChanged(this.devices.screen.deviceOrientation.getValue(),false)}this.getCurrentScene().resume(timestamp)}else{this.setValueForKey(null,"currentSceneKey")}};gs.Game.flushSceneStack=function(timestamp){while(this.currentSceneStack.length&gt;0){var scene=this.currentSceneStack.pop();this.tearDownScene(scene,timestamp)}this.setValueForKey(null,"currentSceneKey")};gs.Game.tearDownScene=function(scene,timestamp){if(scene&amp;&amp;scene.hasStarted()){scene.stop(timestamp)}scene.hideScene();this.scenes.unloadScene(scene._objectKey)};gs.Game.switchToScene=function(sceneKey,timestamp){this.flushSceneStack(timestamp);this.pushScene(sceneKey,timestamp);var currentScene=this.getCurrentScene();var spawnablePrototypeSet=gs.Map.provide();currentScene.getRequiredActors(spawnablePrototypeSet,true);gs.ActorFactory.current.managePools(sceneKey,spawnablePrototypeSet)};gs.Game.setNeedsToChangeScene=function(sceneKey){if(this._currentSceneKey&amp;&amp;sceneKey===this.currentSceneStack[0]._objectKey){this.resetSceneViaChangeScene=true;this.setNeedsToResetScene();return}if(this.sceneChangeEnabled&amp;&amp;this.scenes.sceneExists(sceneKey)&amp;&amp;this.sceneChangeMethod===gs.NOOP_FUNCTION){this._sceneKeyToChangeTo=sceneKey;this.sceneChangeMethod=gs.Game.loadScene}};gs.Game.forceNeedsToChangeScene=function(sceneKey){this._sceneKeyToChangeTo=sceneKey;this.sceneChangeMethod=gs.Game.loadScene};gs.Game.setNeedsToResetScene=function(){if(this.resetSceneEnabled&amp;&amp;this.sceneChangeMethod===gs.NOOP_FUNCTION){this.sceneChangeMethod=this.resetScene}};gs.Game.setNeedsToResetGame=function(){if(this.resetGameEnabled&amp;&amp;this.sceneChangeMethod===gs.NOOP_FUNCTION){this.sceneChangeMethod=this.resetGame}};gs.Game.setNeedsToEndGame=function(){this.sceneChangeMethod=this.endGame};gs.Game.setNeedsToPauseGame=function(sceneKey){if(this.sceneChangeEnabled&amp;&amp;this.scenes.sceneExists(sceneKey)&amp;&amp;this.sceneChangeMethod===gs.NOOP_FUNCTION){this._sceneKeyToChangeTo=sceneKey;this.sceneChangeMethod=this.pauseGame;var sceneIndex=this.scenes.indexAndKey(sceneKey);sceneIndex++;this.project.virtualFileCache.retainSceneByIndex(sceneIndex)}};gs.Game.setNeedsToUnpauseGame=function(){if(this.sceneChangeEnabled&amp;&amp;this.currentSceneStack.length&gt;1&amp;&amp;this.sceneChangeMethod===gs.NOOP_FUNCTION){this.sceneChangeMethod=this.resumeGame}};gs.Game.start=function(timestamp){this.setupCollisionCategories();gs.Entity.start.call(this,timestamp);var eventCenter=this.eventCenter;eventCenter.registerForEvent("changeToScene",this,"setNeedsToChangeScene",null);eventCenter.registerForEvent("resetScene",this,"setNeedsToResetScene",null);eventCenter.registerForEvent("resetGame",this,"setNeedsToResetGame",null);eventCenter.registerForEvent("startPauseScene",this,"setNeedsToPauseGame",null);eventCenter.registerForEvent("endPauseScene",this,"setNeedsToUnpauseGame",null);eventCenter.registerForEvent("systemPause",this,"systemPause",null);eventCenter.registerForEvent("giveAdReward",this,"giveAdReward",null);eventCenter.registerForEvent("localeDetected",this,"localeDetected",null);eventCenter.registerForEvent("externalWriteGameAttribute",this,"externalWriteGameAttribute",null);eventCenter.registerForEvent("loadExternalImage",this,"loadExternalImage",null);var randomSeed=this.attributes.randomSeed;var randomSeedValue=parseInt(randomSeed.getValue(),10);if(randomSeedValue!==-1){gs.Random=new Math.seedrandom(randomSeedValue)}else{gs.Random=Math.random}randomSeed.addObserver(this);this.devices.audio.musicVolume.addObserver(this);this.devices.audio.soundVolume.addObserver(this);gs.AudioManager.current.initWithGame(this);gs.AudioManager.current.setSoundVolume(this.devices.audio.soundVolume.getValue());gs.AudioManager.current.setMusicVolume(this.devices.audio.musicVolume.getValue())};gs.Game.stop=function(timestamp){gs.Entity.stop.call(this,timestamp);this.devices.audio.soundVolume.removeObserver(this);this.devices.audio.musicVolume.removeObserver(this);this.attributes.randomSeed.removeObserver(this);this.eventCenter.deregisterForEvent("changeToScene",this);this.eventCenter.deregisterForEvent("resetScene",this);this.eventCenter.deregisterForEvent("resetGame",this);this.eventCenter.deregisterForEvent("startPauseScene",this);this.eventCenter.deregisterForEvent("endPauseScene",this);this.flushSceneStack(timestamp);gs.AudioManager.current.stopMusic()};gs.Game.teardown=function(){};gs.Game.reset=function(){this.setNeedsToChangeScene(this.scenes.declaredScenes[0])};gs.Game.observeValueChange=function(attribute,value){if(attribute===this.devices.audio.musicVolume){gs.AudioManager.current.setMusicVolume(value)}else if(attribute===this.devices.audio.soundVolume){gs.AudioManager.current.setSoundVolume(value)}else if(attribute===this.attributes.randomSeed){var randomSeed=this.attributes.randomSeed.getValue();gs.Random=new Math.seedrandom(randomSeed)}};gs.Game.evaluate=function(timestamp){this.attributes.time.fastSetValue(timestamp.time);this.updateClock();if(!this.inputEventTargetDetected){this.redetectInputCoordinates()}if(this.currentScene){this.currentScene.evaluate(timestamp)}this.joysticks.update();this.sceneChangeMethod(timestamp);this.eventCenter.checkEventQueue();this.project.dispatchDeferredActions();this.firstFrameAfterLoading=false};gs.Game.loadScene=function(timestamp){this.sceneLoadProfiler.reset();this.sceneLoadProfiler.time.enter();this.setLoadingFlag(true);var currentScene=this.getCurrentScene();var currentSceneName=null;if(currentScene&amp;&amp;currentScene.hasStarted()){currentScene.stop(timestamp);currentSceneName=currentScene.attributes.name.getValue()}gs.platform.AnalyticsService.instance().beginSceneChange(currentSceneName);this.preloadAssetsForScene(this._sceneKeyToChangeTo,true);this.scenes.getScene(this._sceneKeyToChangeTo,this);this.sceneLoadedMethod=gs.Game.changeScene;this.sceneChangeMethod=gs.Game.isSceneLoaded};gs.Game.isSceneLoaded=function(timestamp){var isSceneLoaded=this.scenes.isSceneLoaded(this._sceneKeyToChangeTo);if(isSceneLoaded){this.sceneChangeMethod=this.sceneLoadedMethod}};gs.Game.changeScene=function(timestamp){if(this._sceneKeyToChangeTo!==null){this.sceneChangeMethod=gs.NOOP_FUNCTION;this.switchToScene(this._sceneKeyToChangeTo,timestamp);this._sceneKeyToChangeTo=null}};gs.Game.resetScene=function(timestamp){var sceneKey=this._currentSceneKey;if(this.resetSceneViaChangeScene){while(this.currentSceneStack.length&gt;0){sceneKey=this._currentSceneKey;this.popScene(timestamp)}this.resetSceneViaChangeScene=false}else{this.popScene(timestamp)}this.sceneChangeMethod=gs.NOOP_FUNCTION;this.setNeedsToChangeScene(sceneKey)};gs.Game.resetGame=function(timestamp){this.stop(timestamp);this.scenes.unloadAllScenes();this.sceneChangeMethod=gs.NOOP_FUNCTION;this.reset();var closureThis=this;this.project.getObjectJSON(function(gameTable){gs.Entity.loadFromLite.call(closureThis,gameTable);closureThis.start(timestamp)})};gs.Game.pauseGame=function(timestamp){this.setLoadingFlag(true);var currentScene=this.getCurrentScene();if(currentScene&amp;&amp;currentScene.hasStarted()){currentScene.pause(timestamp)}this.preloadAssetsForScene(this._sceneKeyToChangeTo,false);this.scenes.getScene(this._sceneKeyToChangeTo,this);this.sceneLoadedMethod=gs.Game.pushPauseScene;this.sceneChangeMethod=gs.Game.isSceneLoaded};gs.Game.pushPauseScene=function(timestamp){this.sceneChangeMethod=gs.NOOP_FUNCTION;this.pushScene(this._sceneKeyToChangeTo,timestamp);this._sceneKeyToChangeTo=null};gs.Game.resumeGame=function(timestamp){this.sceneChangeMethod=gs.NOOP_FUNCTION;this.popScene(timestamp);this._sceneKeyToChangeTo=null};gs.Game.endGame=function(timestamp){};gs.Game.actorTags=function(){if(!this.cachedTags){var tags=this.attributes.actorTags.getValue();this.cachedTags=tags.split("\t")}return this.cachedTags};gs.Game.setActorTags=function(tagArray){var delim="\t";this.attributes.actorTags.setValue(table.concat(tagArray,delim))};gs.Game.addActorTag=function(name){var tagName=name||"New Tag";if(!this.validateTagName(tagName)){var count=0;var numberedTagName=tagName+" "+count;while(!this.validateTagName(numberedTagName)){count=count+1;numberedTagName=tagName+" "+count}tagName=numberedTagName}if(this.actorTags().length===0){this.attributes.actorTags.setValue(tagName)}else{var tagString=this.attributes.actorTags.getValue();tagString=tagString+"\t"+tagName;this.attributes.actorTags.setValue(tagString)}return tagName};gs.Game.validateTagName=function(tagName){var tags=this.actorTags();var tagSet=set.arrayToSet(tags);return tagSet[tagName]==null};gs.Game.bestInterfaceOrientationForScene=function(deviceOrientation){var supported=this.getCurrentScene().supportedOrientations();if(supported[deviceOrientation]){return deviceOrientation}else{var bestOrientation=0;if(supported[3]){bestOrientation=3}if(supported[1]){bestOrientation=1}if(supported[2]){bestOrientation=2}if(supported[0]){bestOrientation=0}return bestOrientation}};gs.Game.updateInterfaceOrientation=function(newInterfaceOrientation){this.devices.screen.interfaceOrientation.setValue(newInterfaceOrientation)};gs.Game.deviceOrientationChanged=function(newDeviceOrientation,animate){this.devices.screen.deviceOrientation.setValue(newDeviceOrientation);if(newDeviceOrientation&gt;3){return}var newInterfaceOrientation=this.bestInterfaceOrientationForScene(newDeviceOrientation);if(newDeviceOrientation===1&amp;&amp;newInterfaceOrientation===0){newInterfaceOrientation=0;this.accelerometer.setFlipAxes(true)}else{this.accelerometer.setFlipAxes(false)}this.devices.screen.interfaceOrientation.setValue(newInterfaceOrientation)};gs.Game.updateScreenSize=function(){var dimensions=gs.sizeAndOrientationForResolution(this.resolution);var width=dimensions[0];var height=dimensions[1];var orientation=dimensions[2];var screen=this.devices.screen;screen.deviceOrientation.setValue(orientation);this.updateInterfaceOrientation(orientation);screen.size.width.setValue(width);screen.size.height.setValue(height);this.accelerometer.setOrientation(orientation===2?"portrait":"landscape")};gs.Game.updateGraphicsDimensions=function(){this.renderer.updateSize();var viewport=gs.EngineContext.current.renderContext.viewport;var width=viewport.reportWidth;var height=viewport.reportHeight;var aspect=viewport.reportAspect;if(gs.globalOptions.spoofIOSScreenSize){var iOS=false;switch(this.resolution){case gs.Resolution.IPHONE_LANDSCAPE:case gs.Resolution.IPHONE_PORTRAIT:case gs.Resolution.IPAD_LANDSCAPE:case gs.Resolution.IPAD_PORTRAIT:case gs.Resolution.LEGACY_IPHONE_LANDSCAPE:case gs.Resolution.LEGACY_IPHONE_PORTRAIT:iOS=true;break}if(iOS){var spoofSize=null;var isPortrait=height&gt;width;switch(aspect){case gs.AspectRatio.ASPECT_16_9:spoofSize=gs.sizeAndOrientationForResolution(isPortrait?gs.Resolution.IPHONE_PORTRAIT:gs.Resolution.IPHONE_LANDSCAPE);break;case gs.AspectRatio.ASPECT_4_3:spoofSize=gs.sizeAndOrientationForResolution(isPortrait?gs.Resolution.IPAD_PORTRAIT:gs.Resolution.IPAD_LANDSCAPE);break;case gs.AspectRatio.ASPECT_3_2:spoofSize=gs.sizeAndOrientationForResolution(isPortrait?gs.Resolution.LEGACY_IPHONE_PORTRAIT:gs.Resolution.LEGACY_IPHONE_LANDSCAPE);break;default:break}if(spoofSize){width=spoofSize[0];height=spoofSize[1]}}}this.devices.screen.size.width.setValue(width);this.devices.screen.size.height.setValue(height)};gs.Game.loadFromLite=function(node){gs.Entity.loadFromLite.call(this,node);this.title=node["title"];this.resolution=Number(node["resolution"]);this.resolutionIndependence=Number(node["resolutionIndependence"]);var prototypes=node["prototypes"];var scenes=node["scenes"];if(prototypes){if(Array.isArray(prototypes)){this.prototypeCount=prototypes.length}else{this.prototypeCount=1}}if(scenes){this.scenes.loadFromLite(scenes)}this.updateScreenSize();this.loadNextBatchOfActorPrototypes()};gs.Game.loadFromTable=function(t){this.title=t["title"];this.UID=t["UID"];gs.Entity.loadFromTable.call(this,t);var table=t[gs.JXON._children];if(!table){return}var itemCount=table.length;for(var i=0;i&lt;itemCount;++i){var node=table[i];var nodetype=gs.Project.nodeTypeNameMap[node[gs.JXON._type]];switch(nodetype){case"attributes":break;case"prototypes":this.prototypeCount=node[gs.JXON._children].length;break;case"scenes":this.scenes.loadFromTable(node[gs.JXON._children]);break;case"resolution":this.resolution=Number(node[gs.JXON._text]);this.updateScreenSize();break;case"resolutionIndependence":this.resolutionIndependence=Number(node[gs.JXON._text]);break;default:this[nodetype]=node[gs.JXON._text]}}this.loadNextBatchOfActorPrototypes()};gs.Game.loadNextBatchOfActorPrototypes=function(){var that=this;var i=this.prototypeProgress;var iend=this.prototypeCount;if(this.prototypeBatchSize&gt;0){iend=Math.min(this.prototypeCount,i+this.prototypeBatchSize)}for(;i&lt;iend;i++){var index=i+1;this.actorFactory.preloadActorPrototypeByIndex(index);this.prototypeProgress++}if(this.prototypeProgress&lt;this.prototypeCount){gs._yield().then(function(){that.loadNextBatchOfActorPrototypes()})}else{this.promiseGameParsed.resolve()}};gs.Game.loadTableData=function(virtualFileCache){for(var key in this.attributes){var attribute=this.attributes[key];if(attribute._type==="table"){attribute.loadTableData(virtualFileCache)}}};gs.Game.fileExtension=function(){return"game"};gs.Game.DEFAULT_JOYSTICK_INPUT_VALUES={dpadUp:false,dpadDown:false,dpadLeft:false,dpadRight:false,start:false,select:false,buttonX:false,buttonY:false,buttonA:false,buttonB:false,rightShoulder1:false,leftShoulder1:false,rightShoulder2:false,leftShoulder2:false,leftStickClick:false,rightStickClick:false,leftStickX:0,leftStickY:0,rightStickX:0,rightStickY:0,leftTrigger:-1,rightTrigger:-1};gs.Game.initEngine=function(displayAnchor){this.eventCenter=new gs.EventCenter;this.actorFactory=gs.ActorFactory.instance();this.isPlaying=false;var gameWidth=this.attributes.displaySize.width.getValue();var gameHeight=this.attributes.displaySize.height.getValue();var userAgent=window.navigator.userAgent;var rendererConstructor=null;var renderContext=gs.EngineContext.current.getRenderContext();var rendererOption=renderContext.getRenderer();switch(rendererOption){case gs.RendererOption.WEBGL:rendererConstructor=gs.SGWebGLRenderer;break;case gs.RendererOption.CANVAS:rendererConstructor=gs.SGCanvasRenderer;break;default:if(gs.webgl.isSupported()){rendererConstructor=gs.SGWebGLRenderer}else{rendererConstructor=gs.SGCanvasRenderer}break}this.renderer=new rendererConstructor(displayAnchor);var keyboardEventTarget=window;this.inputEventTarget=displayAnchor.input;var inputEventElement=displayAnchor.input;if(gs.globalOptions.forceInputEventsOnCanvas){inputEventElement=displayAnchor.canvas}gs.ENABLE_COLOR_MULTIPLY=!/Android.*?WebKit/.test(userAgent);this.domElement=this.renderer.getRoot();this.sharedHandleManager=this.renderer.getHandleManager();var game=this;this.interceptKeyEvents=false;this.redetectInputCoordinates();var keysDown={};game.eventCenter.registerForEvent("keyboardInputEntered",this,"keyboardInputEntered");this.keyboardInputEntered=function(){Object.keys(keysDown).map(function(keyString){delete keysDown[keyString];game.eventCenter.postEvent("keyUp",null,keyString)})};var keyDownFunction=function(event){if(!game.interceptKeyEvents){return}game.frameProfiler.input.enter();event.preventDefault();var keyString=gs.mapKeyInput(event);keysDown[keyString]=true;game.eventCenter.postEvent("keyDown",null,keyString);game.frameProfiler.input.exit()};var keyUpFunction=function(event){if(!game.interceptKeyEvents){return}game.frameProfiler.input.enter();event.preventDefault();var keyString=gs.mapKeyInput(event);delete keysDown[keyString];game.eventCenter.postEvent("keyUp",null,keyString);game.frameProfiler.input.exit()};keyboardEventTarget.addEventListener("keydown",keyDownFunction,false);keyboardEventTarget.addEventListener("keyup",keyUpFunction,false);window.addEventListener("scroll",function(event){game.redetectInputCoordinates()});var convertScreenToViewVector=[0,0];var convertScreenToView=function(event){var cameraX="offsetX"in event?event.offsetX:event.clientX+game.documentScrollX-game.domElementX;var cameraY="offsetY"in event?event.offsetY:event.clientY+game.documentScrollY-game.domElementY;cameraY=game.viewportPhysicalHeight-cameraY;cameraX*=gameWidth/game.viewportBufferWidth/game.viewportStretchX;cameraY*=gameHeight/game.viewportBufferHeight/game.viewportStretchY;var virtualDisplayWidth=game.attributes.displaySize.width.getValue();var virtualDisplayHeight=game.attributes.displaySize.height.getValue();var scene=game.getCurrentScene();if(scene){virtualDisplayWidth=scene.attributes.camera.size.width.getValue();virtualDisplayHeight=scene.attributes.camera.size.height.getValue()}convertScreenToViewVector[0]=cameraX*virtualDisplayWidth/gameWidth;convertScreenToViewVector[1]=cameraY*virtualDisplayHeight/gameHeight;return convertScreenToViewVector};var touchList=gs.array.provide();var pointerTouches=gs.array.provide();var eventDown=function(event,touchIndex){window.focus();var xy=convertScreenToView(event);var x=xy[0];var y=xy[1];var currentTouchCount=game.devices.touches.count.getValue();game.devices.touches.count.fastSetValue(currentTouchCount+1);game.eventCenter.postEvent("touchDown",null,touchIndex,x,y);if(touchIndex===1){game.eventCenter.postEvent("mouseDown",null,x,y)}};var eventMove=function(event,touchIndex,isTouch){if(event.preventDefault){event.preventDefault()}var xy=convertScreenToView(event);var x=xy[0];var y=xy[1];var mouseDown=game.devices.mouse.button.getValue();if(isTouch||mouseDown){game.eventCenter.postEvent("touchMoved",null,touchIndex,x,y)}if(touchIndex===1){game.eventCenter.postEvent("mouseMoved",null,x,y)}};var eventUp=function(event,touchIndex){if(game.deferredOpenURL){window.open(game.deferredOpenURL);game.deferredOpenURL=null}var xy=convertScreenToView(event);var x=xy[0];var y=xy[1];var currentTouchCount=game.devices.touches.count.getValue()-1;currentTouchCount=Math.max(currentTouchCount,0);game.devices.touches.count.fastSetValue(currentTouchCount);game.eventCenter.postEvent("touchUp",null,touchIndex,x,y);if(touchIndex===1){game.eventCenter.postEvent("mouseUp",null,x,y)}};function touchstart(event){if(event.preventDefault){event.preventDefault()}var touches=event.changedTouches;if(!touches){pointerTouches[0]=event;event.identifier=event.pointerId;touches=pointerTouches}for(var i=0,iend=touches.length;i&lt;iend;i++){var touch=touches[i];var id=touch.identifier;var touchOffset=touchList.indexOf(id);if(touchOffset===-1){touchOffset=0;while(touchList[touchOffset]!==undefined){touchOffset++}touchList[touchOffset]=id;var touchIndex=touchOffset+1;eventDown(touch,touchIndex)}else{gs.Log.debug("unexpected touchstart",id)}}}function touchmove(event){if(event.preventDefault){event.preventDefault()}var touches=event.changedTouches;if(!touches){pointerTouches[0]=event;event.identifier=event.pointerId;touches=pointerTouches}for(var i=0,iend=touches.length;i&lt;iend;i++){var touch=touches[i];var id=touch.identifier;var touchOffset=touchList.indexOf(id);if(touchOffset===-1){eventMove(touch,1,false)}else{var touchIndex=touchOffset+1;eventMove(touch,touchIndex,true)}}}function touchend(event){if(event.preventDefault){event.preventDefault()}var touches=event.changedTouches;if(!touches){pointerTouches[0]=event;event.identifier=event.pointerId;touches=pointerTouches}for(var i=0,iend=touches.length;i&lt;iend;i++){var touch=touches[i];var id=touch.identifier;var touchOffset=touchList.indexOf(id);if(touchOffset===-1){gs.Log.debug("unexpected touch",id)}else{var touchIndex=touchOffset+1;eventUp(touch,touchIndex);touchList[touchOffset]=undefined}}}function touchcancel(event){if(event.preventDefault){event.preventDefault()}var touches=event.changedTouches;if(!touches){pointerTouches[0]=event;event.identifier=event.pointerId;touches=pointerTouches}for(var i=0,iend=touches.length;i&lt;iend;i++){var touch=touches[i];var id=touch.identifier;var touchOffset=touchList.indexOf(id);if(touchOffset===-1){gs.Log.debug("unexpected touch",id)}else{var touchIndex=touchOffset+1;eventUp(touch,touchIndex);touchList[touchOffset]=undefined}}}function touchleave(event){if(event.preventDefault){event.preventDefault()}var touches=event.changedTouches;if(!touches){pointerTouches[0]=event;event.identifier=event.pointerId;touches=pointerTouches}for(var i=0,iend=touches.length;i&lt;iend;i++){var touch=touches[i];var id=touch.identifier;var touchOffset=touchList.indexOf(id);if(touchOffset===-1){gs.Log.debug("unexpected touch",id)}else{var touchIndex=touchOffset+1;eventUp(touch,touchIndex);touchList[touchOffset]=undefined}}}if(gs.globalOptions.forcePointerEvents){if(typeof MSPointerEvent!=="undefined"){inputEventElement.addEventListener("MSPointerDown",touchstart,false);inputEventElement.addEventListener("MSPointerMove",touchmove,false);inputEventElement.addEventListener("MSPointerUp",touchend,false);inputEventElement.addEventListener("MSPointerCancel",touchcancel,false);inputEventElement.addEventListener("MSPointerLeave",touchleave,false)}else{inputEventElement.addEventListener("pointerdown",touchstart,false);inputEventElement.addEventListener("pointermove",touchmove,false);inputEventElement.addEventListener("pointerup",touchend,false);inputEventElement.addEventListener("pointercancel",touchcancel,false);inputEventElement.addEventListener("pointerleave",touchleave,false)}}else{inputEventElement.addEventListener("touchstart",touchstart,false);inputEventElement.addEventListener("touchmove",touchmove,false);inputEventElement.addEventListener("touchend",touchend,false);inputEventElement.addEventListener("touchcancel",touchcancel,false);inputEventElement.addEventListener("touchleave",touchleave,false);inputEventElement.addEventListener("mousedown",function mousedown(event){eventDown(event,1)},false);inputEventElement.addEventListener("mousemove",function mousemove(event){eventMove(event,1,false)},false);inputEventElement.addEventListener("mouseup",function mouseup(event){eventUp(event,1)},false)}document.addEventListener("visibilitychange",gs.Game.onVisibilityChange)};gs.Game.onVisibilityChange=function(){if(gs.globalOptions.pauseOnVisibilityChange){if(document.visibilityState==="hidden"){gs.EngineContext.current.suspend()}else{gs.EngineContext.current.unsuspend()}}};gs.Game.setLoadingFlag=function(isLoading){var wasLoading=this.loadingFlag;this.loadingFlag=isLoading;if(!wasLoading&amp;&amp;isLoading){this.loaderProgress.beginTransition();gs.EngineContext.current.delegate.onLoadingBegin()}if(wasLoading&amp;&amp;!isLoading){gs.EngineContext.current.delegate.onLoadingEnd();this.loaderProgress.endTransition();this.firstFrameAfterLoading=true}};gs.Game.deferOpenURL=function(theURL){this.deferredOpenURL=theURL};gs.Game.externalWriteGameAttribute=function(keypath,value){var reference=gs.Reference.lookup(keypath);var attribute=reference.resolveRelativeTo(this);if(attribute){if(attribute._type==="table"){var network=gs.Network.instance();network.propertyToTable(value,attribute);attribute.notifyObserversOfValueChange(attribute)}else{attribute.setValue(value)}}};gs.Game.loadExternalImage=function(imageId,imageUri){var imageAssets=this.project.getImages();var imageAsset=imageAssets.assetForName(imageId);if(!imageAsset){var newImageAsset=gs.ImageAsset.neuw();newImageAsset.name=imageId;newImageAsset.representations.uri={uri:imageUri,size:null};imageAssets.add(newImageAsset);return}if(imageUri){imageAsset.representations.uri={uri:imageUri,size:null}}else{delete imageAsset.representations.uri}var assetManager=gs.AssetManager.current;assetManager.eraseImage(imageId);var currentScene=this.getCurrentScene();var instanceSet=gs.Map.provide();currentScene.getActorInstances(instanceSet);for(var key in instanceSet){var actorInstance=instanceSet[key];if(actorInstance.attributes.image.getValue()===imageId){actorInstance.attributes.image.sprite.recycle();actorInstance.attributes.image.notifyObserversOfValueChange(imageId)}}};gs.Game.systemPause=function(){this.gameTimebase.pause();this.systemPaused=true;var currentScene=this.getCurrentScene();if(currentScene){currentScene.pause(this.gameTimebase.currentTimeStamp)}gs.AudioManager.current.pauseAll()};gs.Game.giveAdReward=function(name,reward){this.attributes.adReward.name.setValue(name);this.attributes.adReward.value.setValue(reward)};gs.Game.localeDetected=function(region,lang){this.devices.platform.region.setValue(region);this.devices.platform.language.setValue(lang)};gs.Game.systemResume=function(){this.gameTimebase.resume();gs.EngineContext.current.resetFrameTime();this.systemPaused=false;var currentScene=this.getCurrentScene();if(currentScene){currentScene.resume(this.gameTimebase.currentTimeStamp)}gs.AudioManager.current.unpauseAll()};gs.Game.getRequiredImages=function(sceneID,strategy){var list=null;if(strategy===gs.LoadStrategyOption.GAME){var allImageAssets=this.project.getImages();list=allImageAssets.toArray()}return list};gs.Game.getRequiredSounds=function(sceneID,strategy){var list=null;if(strategy===gs.LoadStrategyOption.GAME){var allImageAssets=this.project.getSounds();list=allImageAssets.toArray()}return list};gs.Game.preloadAssetsForScene=function(sceneID,strategy,cleanup){var assetManager=gs.AssetManager.current;assetManager.beginPreloading();var images=this.getRequiredImages(sceneID,strategy);var sounds=this.getRequiredSounds(sceneID,strategy);if(cleanup){images&amp;&amp;assetManager.cleanupAndLoadImages(images,null);sounds&amp;&amp;assetManager.cleanupAndLoadSounds(sounds,null)}else{images&amp;&amp;assetManager.loadImages(images,null);sounds&amp;&amp;assetManager.loadSounds(sounds,null)}};gs.Game.clearTouchState=function(){if(this.devices.touches.count.getValue()&gt;0){this.devices.touches.count.fastSetValue(0);this.eventCenter.postEvent("mouseUp",null,0,0);this.eventCenter.postEvent("touchUp",null,1,0,0)}};gs.Game.getTableAttribute=function(keypath){var table=this.tableLookupCache[keypath];if(!table){var tableKeypath=gs.tables.getKeypath(keypath);table=this.resolveKeypath(tableKeypath);this.tableLookupCache[keypath]=table}return table};gs.Game.redetectInputCoordinates=function(){var inputEventTarget=this.inputEventTarget;this.documentScrollX=document.body.scrollLeft+document.documentElement.scrollLeft;this.documentScrollY=document.body.scrollTop+document.documentElement.scrollTop;var domPosition=gs.dom.getElementPosition(inputEventTarget);this.domElementX=domPosition[0];this.domElementY=domPosition[1];this.viewportBufferWidth=inputEventTarget.clientWidth;this.viewportBufferHeight=inputEventTarget.clientHeight;this.viewportPhysicalWidth=inputEventTarget.clientWidth;this.viewportPhysicalHeight=inputEventTarget.clientHeight;this.viewportStretchX=this.viewportPhysicalWidth/this.viewportBufferWidth;this.viewportStretchY=this.viewportPhysicalHeight/this.viewportBufferHeight;this.inputEventTargetDetected=this.viewportPhysicalWidth&amp;&amp;this.viewportPhysicalHeight};gs.Scene=gs.Entity.subclass("Scene");gs.Scene.init=function(){gs.Entity.init.call(this);this.attributes.addStringMutableAttribute("name","New Scene");this.layers=gs.array.provide();var defaultWidth=gs.Game.IPHONE_SCREEN_WIDTH;var defaultHeight=gs.Game.IPHONE_SCREEN_HEIGHT;var game=gs.Game.instance;if(game){defaultWidth=game.attributes.displaySize.width.getValue();defaultHeight=game.attributes.displaySize.height.getValue()}this.attributes.addSizeMutableAttribute("size",defaultWidth,defaultHeight);this.attributes.addBooleanMutableAttribute("wrapX",false);this.attributes.addBooleanMutableAttribute("wrapY",false);this.attributes.addPointMutableAttribute("gravity",0,0);this.attributes.addColorMutableAttribute("color",0,0,0,1);this.attributes.addImmutableAttributeCollection("camera");var camera=this.attributes.camera;camera.addPointMutableAttribute("origin",0,0);camera.addSizeMutableAttribute("size",defaultWidth,defaultHeight);camera.addSizeMutableAttribute("trackingArea",defaultWidth-80,defaultHeight-80);camera.addRealMutableAttribute("rotation",0);this.attributes.addImmutableAttributeCollection("autorotate");var autorotate=this.attributes.autorotate;autorotate.addBooleanMutableAttribute("landscapeLeft",true);autorotate.addBooleanMutableAttribute("landscapeRight",false);autorotate.addBooleanMutableAttribute("portrait",false);autorotate.addBooleanMutableAttribute("portraitUpsideDown",false);if(!this._actorsMarkedForDestruction){this._actorsMarkedForDestruction=gs.Map.provide()}return this};gs.Scene.startPhysics=function(){this._world=new gs.physicsLib.World(-this.attributes.gravity.x.getValue(),-this.attributes.gravity.y.getValue(),true);this._collisionController=gs.CollisionController.provide().init()};gs.Scene.observeValueChange=function(attribute,value){if(this._world&amp;&amp;(attribute===this.attributes.gravity.x||attribute===this.attributes.gravity.y)){this._world.setGravity(-this.attributes.gravity.x.getValue(),-this.attributes.gravity.y.getValue());for(var i=0,iend=this.layers.length;i&lt;iend;i++){var layer=this.layers[i];for(var j=0,jend=layer.actors.length;j&lt;jend;j++){var actor=layer.actors[j];actor.aspects.motion._body.setAwake(1)}}}};gs.physicsFixedStepDT=1/60;gs.physicsMinStepDT=.04;gs.physicsMaxStepCount=25;gs.physicsVelocityIterations=10;gs.physicsPositionIterations=10;gs.Scene.evaluatePhysics=function(frameDT){this.game().frameProfiler.physics.enter();var stepCount=0;while(frameDT&gt;0&amp;&amp;stepCount&lt;gs.physicsMaxStepCount){var physicsDT=Math.min(frameDT,gs.physicsFixedStepDT);frameDT-=physicsDT;if(frameDT&lt;gs.physicsMinStepDT){physicsDT+=frameDT;frameDT=0}if(gs.debug.physics){this._world.step(physicsDT,gs.physicsVelocityIterations,gs.physicsPositionIterations)}stepCount++}this._world.clearForces();this.game().frameProfiler.physics.exit()};gs.Scene.preloadAssets=function(strategy,callback){var imageSet=gs.Map.provide();var soundSet=gs.Map.provide();var fontSet=gs.Map.provide();this.getRequiredAssets(imageSet,soundSet,fontSet,strategy);var requiredImages=gs.set.setToArray(imageSet);var requiredSounds=gs.set.setToArray(soundSet);var requiredFonts=gs.set.setToArray(fontSet);var doCleanup=true;if(gs.Game.current.currentSceneStack.length&gt;1){doCleanup=false}if(strategy===gs.LoadStrategyOption.GAME||strategy===gs.LoadStrategyOption.LATENCY){doCleanup=false}var assetManager=gs.AssetManager.current;if(doCleanup){assetManager.cleanupAndLoadImages(requiredImages,callback);assetManager.cleanupAndLoadSounds(requiredSounds,callback)}else{assetManager.loadImages(requiredImages,callback);assetManager.loadSounds(requiredSounds,callback)}assetManager.loadFonts(requiredFonts,callback);gs.Map.recycle(imageSet);gs.Map.recycle(soundSet);gs.Map.recycle(fontSet);gs.array.recycle(requiredImages);gs.array.recycle(requiredSounds)};gs.Scene.prefetchAssets=function(strategy){var imageSet=gs.Map.provide();var soundSet=gs.Map.provide();var fontSet=gs.Map.provide();this.getRequiredAssets(imageSet,soundSet,fontSet,strategy);var images=gs.set.setToArray(imageSet);var sounds=gs.set.setToArray(soundSet);var assetManager=gs.AssetManager.current;assetManager.fetchSounds(sounds);assetManager.fetchImages(images);gs.Map.recycle(imageSet);gs.Map.recycle(soundSet);gs.array.recycle(images);gs.array.recycle(sounds)};gs.Scene.start=function(timestamp){this.frameCount=0;this.firstFrame=true;this.hasNotifiedRenderedOnce=false;var game=this.game();game.setLoadingFlag(true);var timebase=gs.Timebase.provide().initWithTime(timestamp);timebase.convertTimeStamp(timestamp);this.sceneTime=timebase.getTimeStamp();var that=this;var loaderAnimation=game.loaderProgress;var completeCount=0;var preloadCompleteCallback=function(){if(++completeCount===2){loaderAnimation.setProgress(2,2);loaderAnimation.endLoading();that.assetsLoadedAndStart();gs.Game.profiler.sceneLoadProfiler.assets.exit();if(strategy===gs.LoadStrategyOption.LATENCY){that.prefetchAssets(gs.LoadStrategyOption.STRICT);var thisIndex=game.scenes.indexByKey(that._objectKey);game.scenes.fetchSceneByIndex(thisIndex+1);that.prefetchAssets(gs.LoadStrategyOption.SCENE)}}};loaderAnimation.beginLoading();gs.Game.profiler.sceneLoadProfiler.assets.enter();var strategy=gs.EngineContext.current.options.loadStrategy;this.preloadAssets(strategy,preloadCompleteCallback)};gs.Scene.assetsLoadedAndStart=function(){var thisGame=this.game();thisGame.sceneLoadProfiler.time.exit();var nextSceneName=this.attributes.name.getValue();gs.platform.AnalyticsService.instance().endSceneChange(nextSceneName);thisGame.eventCenter.postEvent("sceneWillStart",null,this);this.attributes.gravity.x.addObserver(this);this.attributes.gravity.y.addObserver(this);this.startPhysics();gs.devices.start(thisGame);var gameTimebase=gs.Game.instance.gameTimebase;if(gameTimebase!==null){gs.EngineContext.current.resetFrameTime();this.timebase=gs.Timebase.provide().initWithTime(gameTimebase.currentTimeStamp);this.sceneTime=this.timebase.getTimeStamp();this.attributes.time.fastSetValue(this.sceneTime.time)}gs.Entity.start.call(this,this.sceneTime);gs.ObjectList.prototype.makeChildrenPerformFunction.call(this.layers,gs.Layer.prototype.startAspects,this.sceneTime);gs.ObjectList.prototype.makeChildrenPerformFunction.call(this.layers,gs.Layer.prototype.startBehaviors,this.sceneTime);thisGame.setLoadingFlag(false);var key=this._objectKey;var name=this.attributes.name.getValue();gs.EngineContext.current.delegate.onCurrentSceneChanged(key,name);thisGame.primePoolsPerScene()};gs.Scene.stop=function(timestamp){var game=gs.Game.current;game.eventCenter.postEvent("sceneWillEnd",null,this);gs.devices.stop(game);this.timebase.convertTimeStamp(timestamp);gs.Entity.stop.call(this,this.sceneTime);gs.ObjectList.prototype.makeChildrenPerformFunction.call(this.layers,gs.Layer.prototype.stop,this.sceneTime);var actorFactory=gs.ActorFactory.current;var layers=this.layers;for(var i=0,iend=layers.length;i&lt;iend;i++){var actors=layers[i].actors;for(var j=0,jend=actors.length;j&lt;jend;j++){var actor=actors[0];this.removeActor(actor);actor.hideActor();actorFactory.recycleActorInstance(actor)}}actorFactory.onSceneStop(this._objectKey);gs.ObjectList.prototype.makeChildrenPerformFunction.call(this.layers,gs.Layer.prototype.recycleThis,this.sceneTime);this.sceneTime=null;gs.Timebase.recycle(this.timebase);this.timebase=null;this._collisionController=null;this._world.recycleThis();this._world=null;this.attributes.gravity.x.removeObserver(this);this.attributes.gravity.y.removeObserver(this)};gs.Scene.pause=function(timestamp){var game=this.game();game.eventCenter.postEvent("sceneWillPause",null,this);this.timebase.pauseRelativeToTimestamp(timestamp)};gs.Scene.resume=function(timestamp){var game=this.game();game.eventCenter.postEvent("sceneWillResume",null,this);gs.devices.start(game);game.eventCenter.postEvent("mouseUp",null);game.eventCenter.postEvent("touchCancel",null);if(this.timebase){this.timebase.resumeRelativeToTimestamp(timestamp)}var id=this._objectKey;var name=this.attributes.name.getValue();gs.EngineContext.current.delegate.onCurrentSceneChanged(id,name)};gs.Scene.hasStarted=function(){return!!this.timebase};gs.Scene.isPaused=function(){return this.timebase&amp;&amp;this.timebase.paused};gs.Scene.evaluate=function(timestamp){if(!this.hasStarted()||this.isPaused()){return}if(this.frameCount===2&amp;&amp;!this.hasNotifiedRenderedOnce){this.notifyRenderedOnce();this.hasNotifiedRenderedOnce=true}var game=this.game();this.timebase.convertTimeStamp(timestamp);this.attributes.time.fastSetValue(this.sceneTime.time);game.frameProfiler.simulate.enter();game.entityCounter.layers.set(this.layers.length);for(var actorKey in this._actorsMarkedForDestruction){var actor=this._actorsMarkedForDestruction[actorKey];delete this._actorsMarkedForDestruction[actorKey];actor.stop(this.sceneTime);this.removeActor(actor);actor.hideActor();gs.ActorFactory.current.recycleActorInstance(actor)}gs.ObjectList.prototype.makeChildrenPerformFunction.call(this.layers,gs.Layer.prototype.evaluate,this.sceneTime);game.frameProfiler.simulate.exit();var dt=timestamp.dt;if(this.frameCount&lt;2){dt=gs.physicsFixedStepDT}this.evaluatePhysics(dt);this.frameCount++;this.firstFrame=false};gs.Scene.addActor=function(actor,layer,index){layer.addActor(actor,index);if(this._visible){layer.makeActorVisible(actor)}return true};gs.Scene.markActorForDestruction=function(actor){this._actorsMarkedForDestruction[actor._objectKey]=actor};gs.Scene.removeActor=function(actor){actor.layer.removeActor(actor)};gs.Scene.frame=function(){return{x:0,y:0,width:this.attributes.size.width.getValue(),height:this.attributes.size.height.getValue()}};gs.Scene.isInBounds=function(x,y){var SIMULATION_BORDER=gs.physicsLib.SIMULATION_BORDER;return x&gt;-SIMULATION_BORDER&amp;&amp;y&gt;-SIMULATION_BORDER&amp;&amp;x&lt;this.attributes.size.width.getValue()+SIMULATION_BORDER&amp;&amp;y&lt;this.attributes.size.height.getValue()+SIMULATION_BORDER};gs.Scene.wrappingEnabled=function(){return this.attributes.wrapX.getValue()||this.attributes.wrapY.getValue()};gs.Scene.convertViewToScene=function(point){var cameraOrigin=this.attributes.camera.origin;var originX=cameraOrigin.x.getValue();var originY=cameraOrigin.y.getValue();point[0]+=originX;point[1]+=originY;return point};gs.Scene.supportedOrientations=function(){var autorotateAttr=this.attributes.autorotate;var supported=[autorotateAttr.landscapeLeft.getValue(),autorotateAttr.landscapeRight.getValue(),autorotateAttr.portrait.getValue(),autorotateAttr.portraitUpsideDown.getValue()];return supported};gs.Scene.animateCameraToNewOrientation=function(newOrientation,degreesRotated,animate){};gs.Scene.getRequiredAssets=function(imageSet,soundSet,fontSet,strategy){var actorFactory=gs.ActorFactory.current;var instanceSet=gs.Map.provide();this.getActorInstances(instanceSet);for(var key in instanceSet){instanceSet[key].getRequiredAssets(imageSet,soundSet,fontSet,strategy,false)}var spawnSet=gs.Map.provide();this.getRequiredActors(spawnSet,true);for(var prototypeID in spawnSet){var spawnPrototype=actorFactory.getActorPrototype(prototypeID);spawnPrototype.getRequiredAssets(imageSet,soundSet,fontSet,strategy,true)}gs.Map.recycle(instanceSet);gs.Map.recycle(spawnSet)};gs.Scene.getRequiredActors=function(actorSet,spawnableActorsOnly){var layers=this.layers;for(var i=0,iend=layers.length;i&lt;iend;i++){layers[i].getRequiredActors(actorSet,spawnableActorsOnly)}};gs.Scene.getActorInstances=function(actorSet){var layers=this.layers;for(var i=0,iend=layers.length;i&lt;iend;i++){layers[i].getActorInstances(actorSet)}};gs.Scene.loadFromLite=function(node,initialState){gs.Entity.loadFromLite.call(this,node,initialState);var layers=node["layers"];if(layers){gs.ObjectListWithKeys.prototype.loadFromLite.call(this.layers,gs.Parser.parseLayer,layers,initialState);for(var i=0;i&lt;this.layers.length;i++){var layer=this.layers[i];layer.scene=this;for(var j=0;j&lt;layer.actors.length;j++){var actor=layer.actors[j];actor.scene=this}}}};gs.Scene.loadFromTable=function(t){gs.Entity.loadFromTable.call(this,t);var table=t[gs.JXON._children];if(!table){return}var itemCount=table.length;for(var i=0;i&lt;itemCount;++i){var node=table[i];var nodetype=gs.Project.nodeTypeNameMap[node[gs.JXON._type]];switch(nodetype){case"layers":this.layers.loadFromTable(node[gs.JXON._children]);break}}};gs.Scene.fileExtension=function(){return"scene"};gs.Scene.notifyRenderedOnce=function(){var sceneKey=this.getObjectKey();gs.Project.instance.dispatchAction("scene","renderOnce",sceneKey)};gs.PathResolver=function(pathPrefix){this.allowCaching=true;this.prefix=pathPrefix;if(/[/]$/.test(this.prefix)===false){this.prefix+="/"}return this};gs.PathResolver.prototype={getPath:function(rest){var path=this.prefix+rest;if(!this.allowCaching){path+="?"+Math.random().toString().substring(2)}return encodeURI(path)},getDataPath:function(name){return this.getPath(name+".json")},getObjectPath:function(){return this.getDataPath("object")},getAssetsPath:function(){return this.getDataPath("assets")},getScenePathByIndex:function(index){var name=index.toString();return this.getScenePathByName(name)},getScenePathByOffset:function(offset){return this.getScenePathByIndex(offset+1)},getScenePathByName:function(name){return this.getDataPath("scenes/"+name)},getSceneScreenshotPathByID:function(id){var file=id+".png";return this.getPath("screenshots/"+file)},getImagePath:function(file){return this.getPath("images/"+file)},getSoundPath:function(file){return this.getPath("sounds/"+file)},getFontPath:function(file){return this.getPath("fonts/"+file)},getTablePath:function(id){return this.getDataPath("tables/"+id)}};gs.Parser={compoundAttributeClassMap:{compound:gs.CompoundAttribute,attributes:gs.CompoundAttribute,point:gs.PointAttribute,size:gs.SizeAttribute,rect:gs.RectAttribute,color:gs.ColorAttribute,table:gs.TableAttribute,pair:gs.PairAttribute,tablecolumnassignment:gs.PairAttribute,array:gs.ArrayAttribute},behaviorClassMap:{AccelerateBehavior:gs.AccelerateBehavior,AccelerateTowardBehavior:gs.AccelerateTowardBehavior,AddRemoveRowAction:gs.AddRemoveRowAction,AnimateBehavior:gs.AnimateBehavior,BuzzAction:gs.BuzzAction,CallExternalFunctionAction:gs.CallExternalFunctionAction,ChangeAttributeAction:gs.ChangeAttributeAction,ChangeImageAction:gs.ChangeImageAction,ChangeRowAction:gs.ChangeRowAction,ChangeSceneAction:gs.ChangeSceneAction,ChangeTableValueAction:gs.ChangeTableValueAction,ChangeVelocityAction:gs.ChangeVelocityAction,CollideBehavior:gs.CollideBehavior,CompletingBehavior:gs.CompletingBehavior,CompoundBehavior:gs.CompoundBehavior,ConstrainAttributeBehavior:gs.ConstrainAttributeBehavior,ControlCameraBehavior:gs.ControlCameraBehavior,CopyTableAction:gs.CopyTableAction,DestroyAction:gs.DestroyAction,DisplayTextBehavior:gs.DisplayTextBehavior,EndGameAction:gs.EndGameAction,GrowShrinkBehavior:gs.GrowShrinkBehavior,InterpolateBehavior:gs.InterpolateBehavior,InsertRowAction:gs.InsertRowAction,KeyboardInputAction:gs.KeyboardInputAction,LaunchServiceAction:gs.LaunchServiceAction,LoadAttributeAction:gs.LoadAttributeAction,LogDebuggingStatementAction:gs.LogDebuggingStatementAction,LoopBehavior:gs.LoopBehavior,LoopTableBehavior:gs.LoopTableBehavior,MoveBehavior:gs.MoveBehavior,MoveToBehavior:gs.MoveToBehavior,NetworkGetTableFromURLAction:gs.NetworkGetTableFromURLAction,NetworkSendTableToURLAction:gs.NetworkSendTableToURLAction,NoteBehavior:gs.NoteBehavior,PathFindAction:gs.PathFindAction,OpenURLAction:gs.OpenURLAction,ParticlesBehavior:gs.ParticlesBehavior,PauseGameAction:gs.PauseGameAction,PauseMusicAction:gs.PauseMusicAction,PlayMusicAction:gs.PlayMusicAction,PlaySoundAction:gs.PlaySoundAction,PostEventAction:gs.PostEventAction,PurchaseItemAction:gs.PurchaseItemAction,ReplicateBehavior:gs.ReplicateBehavior,ResetGameAction:gs.ResetGameAction,ResetSceneAction:gs.ResetSceneAction,RotateBehavior:gs.RotateBehavior,RotateToAngleBehavior:gs.RotateToAngleBehavior,RotateToPositionBehavior:gs.RotateToPositionBehavior,RuleBehavior:gs.RuleBehavior,SaveAttributeAction:gs.SaveAttributeAction,SaveTableAction:gs.SaveTableAction,ShowAdAction:gs.ShowAdAction,ShowBannerBehavior:gs.ShowBannerBehavior,ShowMoreGamesAction:gs.ShowMoreGamesAction,SpawnAction:gs.SpawnAction,SpecialAction:gs.SpecialAction,StopMusicAction:gs.StopMusicAction,TimerBehavior:gs.TimerBehavior,UnpauseGameAction:gs.UnpauseGameAction,ShowiAdBehavior:gs.ShowiAdBehavior,GameCenterLoginAction:gs.GameCenterLoginAction,GameCenterPostScoreAction:gs.GameCenterPostScoreAction,GameCenterShowLeaderboardAction:gs.GameCenterShowLeaderboardAction,GameCenterShowAchievementsAction:gs.GameCenterShowAchievementsAction,GameCenterResetAchievementsAction:gs.GameCenterResetAchievementsAction,GameCenterUpdateAchievement:gs.GameCenterUpdateAchievement,InAppPurchaseItemAction:gs.InAppPurchaseItemAction,InAppPurchaseRestoreItem:gs.InAppPurchaseRestoreItem,IAPBuyItemAction:gs.IAPBuyItemAction,IAPConsumeItemAction:gs.IAPConsumeItemAction,IAPRequestPurchaseDataAction:gs.IAPRequestPurchaseDataAction,IAPRestoreItemsAction:gs.IAPRestoreItemsAction,TweetSheetAction:gs.TweetSheetAction},predicateClassMap:{"auto-rotation":gs.AutorotatePredicate,boolean:gs.BooleanPredicate,collision:gs.CollisionPredicate,enumeration:gs.EnumerationPredicate,hibernate:gs.HibernatePredicate,key:gs.KeyPredicate,mouse:gs.MousePredicate,mousePosition:gs.MousePositionPredicate,number:gs.NumberPredicate,purchase:gs.PurchasePredicate,string:gs.StringPredicate,touch:gs.TouchPredicate},parseGame:function(t){var game=gs.Game.provide().init();game.loadFromLite(t);return game},parseActor:function(t){var prototypeID=t.prototype;return gs.ActorFactory.current.provideActorInstance(prototypeID,t)},parseLayer:function(t){var layer=gs.Layer.provide().init();layer.loadFromLite(t);return layer},parseScene:function(t){var scene=gs.Scene.provide().init();var hashService=gs.platform.HashService.instance();if(hashService.id(t.hash,t.id)===t.id){scene.loadFromLite(t)}else{}return scene},parseArray:function(t){var instance=gs.PrototypicalArray.provide().init();instance.loadFromLite(t);return instance},parseBehaviorList:function(t,initialState){var behaviorList=gs.BehaviorList.provide().init();behaviorList.loadFromLite(t,initialState);return behaviorList},parseBehaviorClass:function(t){var disabled=t["enabled"]===false||t["enabled"]==="false";var behaviorClassName=t["class"];var behaviorClass=gs.Parser.behaviorClassMap[behaviorClassName];if(disabled){behaviorClass=gs.NullBehavior}else if(!behaviorClass){gs.Log.warn("Behavior not implemented:",behaviorClassName);gs.Parser.behaviorClassMap[behaviorClassName]=gs.NullBehavior;behaviorClass=gs.NullBehavior}var behavior=behaviorClass.provide().init();return behavior},parseBehavior:function(t,initialState){var behavior=gs.Parser.parseBehaviorClass(t);behavior.loadFromLite(t,initialState);return behavior},parseCondition:function(t,initialState){var condition=gs.Condition.provide().init();condition.loadFromLite(t,initialState);return condition},parseKeyValuePair:function(t,initialState){var pair=gs.KeyValuePair.provide().init();pair.loadFromLite(t,initialState);return pair},parsePredicate:function(t,initialState){var predicateClassName=t["type"];var predicateClass=gs.Parser.predicateClassMap[predicateClassName];if(!predicateClass){gs.Log.info("Predicate not implemented:",predicateClassName);gs.Parser.predicateClassMap[predicateClassName]=gs.NullPredicate;predicateClass=gs.NullPredicate}var predicate=predicateClass.provide().init();predicate.loadFromLite(t,initialState);return predicate},parseExpression:function(t){var expression=gs.Expression.provide().init();expression.loadFromLite(t);return expression},parseReference:function(t){return gs.Reference.loadFromLiteStatic(t)},parseAttributeValue:function(node,key){var attribute=node[key];if(typeof attribute==="object"){return attribute["$"]}return attribute},parse:function(t,initialState){if(!t){return null}switch(t[gs.JXON._type]){case"game":return this.parseGame(t);case"actor":return this.parseActor(t);case"layer":return this.parseLayer(t);case"scene":return this.parseScene(t);case"actors":case"scenes":return this.parseArray(t);case"behaviors":return this.parseBehaviorList(t,initialState);case"behavior":return this.parseBehavior(t,initialState);case"condition":return this.parseCondition(t,initialState);case"keyvaluepair":return this.parseKeyValuePair(t,initialState);case"predicate":case"subjectPredicate":return this.parsePredicate(t,initialState);case"attributes":case"attribute":case"boolean":case"text":case"image":case"sound":case"music":case"real":case"integer":case"index":case"angle":case"enumeration":case"table":case"pair":case"array":case"tablecolumnassignment":return t;case"expression":return this.parseExpression(t);case"reference":return this.parseReference(t);default:gs.Log.warn("Unsupported PGF tag:",t[gs.JXON._type]);return null}}};gs.DefaultConstraints={boolean:gs.BooleanConstraint.Default,text:gs.TextConstraint.Default,real:gs.NumberConstraint.Real,integer:gs.NumberConstraint.Integer,index:gs.NumberConstraint.Index,angle:gs.NumberConstraint.Angle,enumeration:gs.NumberConstraint.Index,image:gs.TextConstraint.Default,sound:gs.TextConstraint.Default,music:gs.TextConstraint.Default};gs.ImageResource=function(){this.id=null;this.ready=false;this.failed=false;this.src=null;this.imageElement=null;this.width=0;this.height=0;this.gl=null;this.texture=null;this.onLoadCallbacks=[]};gs.ImageResource.createFromCanvas=function(canvasElement){var resource=new gs.ImageResource;resource.imageElement=canvasElement;resource.width=canvasElement.width;resource.height=canvasElement.height;resource.ready=true;return resource};gs.ImageResource.prototype={registerOnLoadCallback:function(cb){this.onLoadCallbacks.push(cb)},onLoad:function(){for(var i=0;i&lt;this.onLoadCallbacks.length;i++){try{this.onLoadCallbacks[i].call(this)}catch(e){gs.Log.error("Error running image onload handler",e)}}},createTexture:function(gl){this.gl=gl;this.texture=gs.webgl.createTextureFromImage(gl,this.imageElement)},deleteTexture:function(){this.gl.deleteTexture(this.texture);this.texture=null;this.ready=false;this.gl=null},releaseImageElement:function(){var imageElement=this.imageElement;this.imageElement=null;return imageElement}};var valuesPolyfill=function values(o){return Object.keys(o).map(function(key){return o[key]})};var objectValues=Object.values||valuesPolyfill;gs.AssetManager=function(project){this._project=project;this.imageResourceMap={};this.imageResourceMapPow2={};this.imageCount=0;this.imageRequestQueue=[];this.imageElementPool=[];this.imageElementPoolSize=gs.globalOptions.imageRequestPoolSize;this.useImageQueue=false;this.useTextures=false;this.gl=null;this.fontResourceMap={};this.isBatchLoading=false;this.isPreloading=false;this.preloadRemaining=0;this.fontPreloadRemaining=0;this.preloadCompleteCallback=null;this.renderer=null;this.resourcesWaitingForRenderer=gs.array.provide();this.transparent1x1=null;this.white1x1=null;gs.AssetManager.instance=this;gs.AssetManager.current=this;while(this.imageElementPool.length&lt;this.imageElementPoolSize){this.imageElementPool.push(this.createImageElement())}};gs.AssetManager.transparent1x1PNG="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAFElEQVR4XgXAAQ0AAABAMP1L30IDCPwC/o5WcS4AAAAASUVORK5CYII=";gs.AssetManager.white1x1GIF="data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=";gs.AssetManager.onImageLoad=function(){var resource=this.resource;gs.AssetManager.current.onImageLoad(resource)};gs.AssetManager.onImageError=function(){var resource=this.resource;gs.AssetManager.current.onImageError(resource)};gs.AssetManager.prototype={setRenderer:function(renderer){this.renderer=renderer;if(renderer.gl){this.gl=renderer.gl;this.useTextures=true;this.useImageQueue=true}this.transparent1x1=this.createDataImageResource(null,gs.AssetManager.transparent1x1PNG);this.white1x1=this.createDataImageResource(null,gs.AssetManager.white1x1GIF);this.updateImageQueue()},onImageLoad:function(resource){var imageElement=resource.imageElement;resource.width=imageElement.naturalWidth||imageElement.width;resource.height=imageElement.naturalHeight||imageElement.height;resource.ready=true;try{resource.onLoad()}catch(e){gs.Log.error("Error running image onload handlers",e)}if(this.useTextures){if(!this.renderer){this.resourcesWaitingForRenderer.push(resource)}else{if(this.renderer.isImageTooLarge(resource)){gs.Log.error("Image too large for texture:",resource.id,resource.width,resource.height,this.renderer.maxTextureSize)}else{resource.createTexture(this.gl)}if(!imageElement.doNotRecycle){this.imageElementPool.push(imageElement)}resource.releaseImageElement();imageElement.resource=null}}this.updateImageQueue();if(this.isPreloading){this.preloadRemaining--;this.checkPreloadComplete()}},onImageError:function(resource){gs.Log.error("Image load failed:",resource.id);var imageElement=resource.imageElement;this.imageElementPool.push(imageElement);resource.releaseImageElement();imageElement.resource=null;this.convertToError(resource);this.updateImageQueue();if(this.isPreloading){this.preloadRemaining--;this.checkPreloadComplete()}},getImageNames:function(){var imageNames=[];for(var imageName in this.imageResourceMap){if(this.imageResourceMap.hasOwnProperty(imageName)){imageNames.push(imageName)}}return imageNames},checkPreloadComplete:function(){if(this.preloadRemaining&lt;=0&amp;&amp;this.fontPreloadRemaining&lt;=0){if(this.preloadCompleteCallback){this.preloadCompleteCallback.call(null);this.preloadCompleteCallback=null}this.isPreloading=false}},updateImageQueue:function(){while(this.imageRequestQueue.length&gt;0&amp;&amp;this.imageElementPool.length&gt;0){var resource=this.imageRequestQueue.shift();var imageElement=this.imageElementPool.shift();resource.imageElement=imageElement;imageElement.resource=resource;if(imageElement.srcRaw===resource.src){this.onImageLoad(resource)}else{imageElement.srcRaw=resource.src;imageElement.src=resource.src}}},createImageResource:function(id,src){var resource=new gs.ImageResource;resource.id=id;resource.gl=this.gl;if(src){resource.src=src;if(this.isPreloading){this.preloadRemaining++}if(this.useImageQueue){if(this.isBatchLoading){this.imageRequestQueue.push(resource)}else{this.imageRequestQueue.unshift(resource)}this.updateImageQueue()}else{resource.imageElement=this.createImageElement(src);resource.imageElement.resource=resource}}return resource},createDataImageResource:function(id,src){var resource=new gs.ImageResource;resource.id=id;resource.gl=this.gl;resource.src=src;resource.imageElement=this.createImageElement(src);resource.imageElement.doNotRecycle=true;resource.imageElement.resource=resource;return resource},convertToError:function(resource){var id=resource.id;for(var key in this.transparent1x1){resource[key]=this.transparent1x1[key]}resource.id=id;resource.failed=true},createImageElement:function(src){var imageElement=gs.dom.createImage(src);imageElement.addEventListener("load",gs.AssetManager.onImageLoad,false);imageElement.addEventListener("error",gs.AssetManager.onImageError,false);return imageElement},eraseImage:function(imageName){var resource=this.imageResourceMap[imageName];if(resource){if(this.useTextures&amp;&amp;!resource.failed){resource.deleteTexture()}delete this.imageResourceMap[imageName];this.imageCount--}},pathForImage:function(imageName){return this._project.pathForImage(imageName)},pathForFont:function(fontName){return this._project.pathForFont(fontName)},loadImageForID:function(id){if(this.imageResourceMap[id]){return}var loadSrc=this.pathForImage(id);if(!loadSrc){loadSrc=this.pathForImage(id.replace(/.png$/,""))}var resource;if(loadSrc){resource=this.createImageResource(id,loadSrc)}else{resource=this.createImageResource(id,null);this.convertToError(resource);gs.Log.strict("Image not in manifest:",id)}if(!this.imageResourceMap[id]){this.imageCount++}this.imageResourceMap[id]=resource},imageForName:function(imageName){this.loadImageForID(imageName);return this.imageResourceMap[imageName]},imageForName:function(imageName,src){this.loadImageForID(imageName,src);return this.imageResourceMap[imageName]},imageForNamePow2:function(imageName){var resource=this.imageResourceMapPow2[imageName];if(!resource&amp;&amp;this.gl){resource=new gs.ImageResource;resource.id=imageName;resource.gl=this.gl;var src=this.pathForImage(imageName);resource.imageElement=gs.dom.createImage(src);resource.imageElement.addEventListener("load",function(){var newWidth=1;var newHeight=1;while(newWidth&lt;resource.imageElement.naturalWidth){newWidth*=2}while(newHeight&lt;resource.imageElement.naturalHeight){newHeight*=2}resource.texture=gs.webgl.createTextureFromImageSize(resource.gl,resource.imageElement,newWidth,newHeight);resource.releaseImageElement();resource.width=newWidth;resource.height=newHeight;resource.ready=true},false);this.imageResourceMapPow2[imageName]=resource}return resource},cleanupUnusedImages:function(imagesToKeep){for(var imageName in this.imageResourceMap){if(this.imageResourceMap.hasOwnProperty(imageName)){if(imagesToKeep.indexOf(imageName)===-1){this.eraseImage(imageName)}}}},beginPreloading:function(){this.isPreloading=true;this.preloadRemaining=0;this.fontPreloadRemaining=0},loadImages:function(images,callback){this.isBatchLoading=true;if(callback){this.preloadCompleteCallback=callback}this.fetchImages(images);gs.Game.profiler.sceneLoadProfiler.images.set(images.length);this.isBatchLoading=false;this.updateImageQueue();var that=this;gs._yield(function(){that.checkPreloadComplete()})},fetchImages:function(images){for(var i=0;i&lt;images.length;i++){var imageName=images[i];var resource=this.imageForName(imageName)}},loadFonts:function(fonts,callback){if(fonts.length==0){callback.call(null)}this.isBatchLoading=true;if(callback){this.preloadCompleteCallback=callback}this.fetchFonts(fonts);this.isBatchLoading=false;var that=this;gs._yield(function(){that.checkPreloadComplete()})},fontByName:function(fontName){var resource=this.setupFontResource(fontName);this.setupOpentypeLoader([fontName]);return resource},fetchFonts:function(fonts){var fontNames=[];for(var i=0;i&lt;fonts.length;i++){var fontName=fonts[i];fontNames.push(fontName);this.setupFontResource(fontName)}this.setupOpentypeLoader(fontNames)},setupFontResource:function(fontName){if(this.fontResourceMap[fontName]){return this.fontResourceMap[fontName]}if(this.isBatchLoading){this.fontPreloadRemaining++}this.fontResourceMap[fontName]={name:fontName,ready:false,opentype:null};return this.fontResourceMap[fontName]},setupOpentypeLoader:function(fontNames){var _this=this;var fontsToLoad=[];var resourceMap=this.fontResourceMap;fontNames.forEach(function(fontName){var fontResource=resourceMap[fontName];if(!fontResource.ready&amp;&amp;"opentype"in resourceMap[fontName]){fontsToLoad.push(fontName)}});var isBeingPreloaded=this.isBatchLoading||this.isPreloading;var pathForFont=this._project.pathForFont.bind(this._project);fontsToLoad.forEach(function(fontName){var fontPath=pathForFont(fontName);if(!fontPath){console.error("Unknown font referenced:"+fontName+". Using Arimo (like Arial) instead.");fontPath="https://fonts.gamesalad.com/Arimo-Regular.ttf"}resourceMap[fontName].opentype=false;opentype.load(fontPath,function(err,fontData){if(err){console.error("Error loading font: "+fontName,err);if(isBeingPreloaded){_this.fontPreloadRemaining--;_this.checkPreloadComplete()}}else{resourceMap[fontName].ready=true;resourceMap[fontName].opentype=fontData;if(isBeingPreloaded){_this.fontPreloadRemaining--;_this.checkPreloadComplete()}}})})},cleanupAndLoadImages:function(images,callback){this.cleanupUnusedImages(images);this.loadImages(images,callback)},loadSounds:function(sounds,callback){gs.AudioManager.current.loadAssets(sounds,callback);callback&amp;&amp;callback.call(null)},fetchSounds:function(sounds){gs.AudioManager.current.loadAssets(sounds)},cleanupUnusedSounds:function(soundsToKeep){},cleanupAndLoadSounds:function(sounds,callback){this.cleanupUnusedSounds(sounds);this.loadSounds(sounds,callback)},getImageCount:function(){return this.imageCount}};gs.AssetList=function AssetList(){this.map={}};gs.AssetList.neuw=function(){return new gs.AssetList};gs.AssetList.prototype.add=function(asset){this.map[asset.name]=asset};gs.AssetList.prototype.indexOfAssetWithName=function(name){if(!this.map[name]){return-1}return 1};gs.AssetList.prototype.assetForName=function(name){return this.map[name]};gs.AssetList.prototype.removeAssetWithName=function(name){delete this.map[name]};gs.AssetList.prototype.toArray=function(){return Object.keys(this.map)};gs.Asset={};gs.Asset.typeForFileExtension=function(extension){if(typeof extension!=="string"||extension.length===0){return null}var ext=extension.toLowerCase();if(/^(png|jpg|jpeg)$/.test(ext)){return"image"}if(/^(ogg|m4a|wav|aac|caf|mp4)$/.test(ext)){return"sound"}return null};gs.Asset.newAsset=function(filename,assetname,size){var replist=[{filename:filename,size:size}];var assetType=gs.Asset.typeForFileExtension(filename.pathExtension());if(assetType==="image"){return gs.ImageAsset.create().initWithName(assetname,replist)}else if(assetType==="sound"){return gs.SoundAsset.create().initWithName(assetname,replist)}else if(assetType==="music"){return gs.SoundAsset.create().initWithName(assetname,replist)}else if(assetType==="font"){return gs.FontAsset.create().initWithName(assetname,replist)}return null};gs.Asset.init=function(){this.representations=gs.array.provide();return this};gs.Asset.initWithName=function(name,representations){this.name=name;this.representations=representations||[];return this};gs.Asset.getRepresentations=function(){return this.representations};gs.Asset.addRepresentation=function(filename,size){var filetype=filename.pathExtension();if(!this.representations[filetype]){var rep={filename:filename,size:size};this.representations.push(rep);this.representations[filetype]=rep}};gs.Asset.representationForType=function(filetype){return this.representations[filetype]};gs.Asset.bestFileRepresentation=function(){if(this.representations.length){return this.representations[0]}else{return null}};gs.Asset.loadFromLite=function(node,initialState){this.name=node["name"];var files=node["files"];var file,filename;if(Array.isArray(files)){for(var i=0;i&lt;files.length;i++){file=files[i];filename=this.ensureReasonableFilename(file["name"]);if(filename){this.addRepresentation(filename,file["size"])}}}else if(files){file=files;filename=this.ensureReasonableFilename(file["name"]);if(filename){this.addRepresentation(filename,file["size"])}}this.validateName(true)};gs.Asset.loadFromTable=function(t){this.name=t["name"];var assetTable=t[gs.JXON._children];if(!assetTable){this.addRepresentation(this.name,5e3);return}var length=assetTable.length;for(var i=0;i&lt;length;++i){var file=assetTable[i];var filename=this.ensureReasonableFilename(file["name"]);var filesize=file["size"];if(filename){this.addRepresentation(filename,filesize)}}this.validateName(true)};gs.Asset.ensureReasonableFilename=function(filename){if(!filename){return null}var assetType=this.getType();if(gs.Asset.typeForFileExtension(filename.pathExtension())!==assetType){if(assetType==="image"){filename=filename+".png"}else if(assetType==="sound"){filename=filename+".m4a"}}return filename};gs.Asset.validateName=function(shouldCorrect){if(!this.name&amp;&amp;shouldCorrect){var rep=this.bestFileRepresentation();if(rep&amp;&amp;rep.filename){if(gs.Asset.typeForFileExtension(rep.filename.pathExtension())===this.getType()){var components=rep.filename.split(".");this.name=components[components.length-2]}else{this.name=this.filename}}}return this.name!=null};gs.FontAsset=function(){};gs.FontAsset.prototype=Object.create(gs.Asset);gs.FontAsset.neuw=function(){var asset=new gs.FontAsset;asset.isLoaded=false;asset.onLoadedCallbacks=[];asset.init();return asset};gs.FontAsset.prototype.getType=function(){return"font"};gs.FontAsset.prototype.onLoaded=function(cb){if(cb){if(this.isLoaded){cb.call()}else{this.onLoadedCallbacks.push(cb)}}else{this.isLoaded=true;var cbs=this.onLoadedCallbacks;if(cbs.length&gt;0){for(var i=0;i&lt;cbs.length;i++){cbs[i].call()}}}};gs.ImageAsset=function(){};gs.ImageAsset.prototype=Object.create(gs.Asset);gs.ImageAsset.neuw=function(){var asset=new gs.ImageAsset;asset.init();return asset};gs.ImageAsset.prototype.getType=function(){return"image"};gs.ImageAsset.prototype.bestFileRepresentation=function(){if(this.representations["uri"]){return this.representations["uri"]}if(this.representations["jpg"]){return this.representations["jpg"]}if(this.representations["png"]){return this.representations["png"]}return gs.Asset.bestFileRepresentation.call(this)};gs.SoundAsset=function(){};gs.SoundAsset.prototype=Object.create(gs.Asset);gs.SoundAsset.neuw=function(){var asset=new gs.SoundAsset;asset.init();return asset};gs.SoundAsset.prototype.getType=function(){return"sound"};gs.SoundAsset.prototype.bestFileRepresentation=function(){var extensions=["m4a","ogg","wav","mp4"];var i,extension;for(i=0;i&lt;extensions.length;i++){extension=extensions[i];if(extension in this.representations){if(gs.html5.Audio.canPlayExtension(extension)){return this.representations[extension]}}}for(i=0;i&lt;extensions.length;i++){extension=extensions[i];if(gs.html5.Audio.canPlayExtension(extension)){var filename=this.name+"."+extension;return{filename:filename,size:1}}}return null};gs.Project=function(){gs.Project.instance=this;gs.Project.current=this;var _assetStack=[];var _images=gs.AssetList.neuw();var _sounds=gs.AssetList.neuw();var _fonts=gs.AssetList.neuw();var _loaderProgress={beginTransition:function(){},endTransition:function(){},beginLoading:function(){},endLoading:function(){},tick:function(){},setProgress:function(progress,total){},onError:function(asset){}};var _displayAnchor=null;var _project=this;this._readyToPlay=false;var _playGameQueued=false;var _assetManager=new gs.AssetManager(this);this._displayAnchor=null;var options=gs.EngineContext.current.options;this._changeSceneQueued=null;this.gameLoadProfiler=new gs.LoadProfiler;this.gameLoop=new gs.GameLoop(options.targetRate);this.virtualFileCache=new gs.file.VirtualFileCache;this.virtualFileCache.setFormats([gs.globalOptions.format]);this.promiseGameReady=new gs.Promise;var initialSceneIndex=1;var validateDomain=function(url){var hashService=gs.platform.HashService.instance();return hashService.host(url)};function onGameLoaded(file){var rootJXON=file.getData();_loaderProgress.setProgress(1,2);_project.gameLoadProfiler.load.exit();var hashService=gs.platform.HashService.instance();hashService.init(rootJXON);var promises=[];promises.push(_project.virtualFileCache.fetchAllActorPrototypes());var gameAttributesJXON=rootJXON["attributes"];var gameAttributes=gs.CompoundAttribute.provide().init();gameAttributes.addReservedCompoundAttribute("displaySize","size",{width:gs.Game.IPHONE_SCREEN_WIDTH,height:gs.Game.IPHONE_SCREEN_HEIGHT});if(gameAttributesJXON){gameAttributes.loadFromLite(gameAttributesJXON,true)}var gameWidth=gameAttributes.displaySize.width.getValue();var gameHeight=gameAttributes.displaySize.height.getValue();gs.EngineContext.current.delegate.onGameDimensionsKnown(gameWidth,gameHeight);gs._yield().then(function(){gs.Promise.all(promises,function successAllEntities(){_project.gameLoadProfiler.parse.enter();var game=gs.Parser.parseGame(rootJXON);game.promiseGameParsed.then(function successGameParsed(){game.loadTableData(_project.virtualFileCache);_project.gameLoadProfiler.parse.exit();_project.gameLoadProfiler.time.exit();_project.game=game;game.project=_project;game.sharedAssetManager=_assetManager;game.loaderProgress=_loaderProgress;game.setLoadingFlag(true);_project.virtualFileCache.loadAssetsManifest().then(function successLoadAssetManifest(assetsFile){onAssetsManifestLoaded(assetsFile);_project.loadSceneByIndex(initialSceneIndex).then(onGameReadyToPlay);_project.virtualFileCache.deleteGame()})})})})}function onGameReadyToPlay(){var game=_project.game;game.initEngine(_displayAnchor);game.reset();_project._readyToPlay=true;_project.gameLoop.setCallback(function(){gs.EngineContext.current.update()});_project.gameLoop.setDOMElement(game.renderer.getRoot());_project.promiseGameReady.resolve();gs.EngineContext.current.delegate.onGameReady();if(_playGameQueued){_project.play()}}this.load=function(url,displayAnchor){if(!validateDomain(url))return;this.virtualFileCache.setPrefix(url);this.pathResolver=new gs.PathResolver(url);_displayAnchor=displayAnchor;this._displayAnchor=displayAnchor;this.gameLoadProfiler.time.enter();this.gameLoadProfiler.load.enter();this.virtualFileCache.loadGame().then(onGameLoaded,function failureLoadGame(failure){gs.Log.error(failure);gs.Log.error("Game data not found",url)});this.virtualFileCache.fetchAssetsManifest();this.virtualFileCache.fetchSceneByIndex(initialSceneIndex);return this};this.getObjectJSON=function(callback){this.virtualFileCache.loadGame().then(function(file){var data=file.getData();callback&amp;&amp;callback.call(null,data)})};function onSceneLoaded(file){var promise=new gs.Promise;gs.Game.profiler.sceneLoadProfiler.load.exit();var game=_project.game;var root=file.getData();var sceneKey=root.id;var sceneIndex=game.scenes.indexAndKey(sceneKey);sceneIndex++;var retain=_project.virtualFileCache.isSceneRetainedByIndex(sceneIndex);game.scenes.inflateScene(sceneKey,root,game).then(function(){if(!retain){gs.array.recycleJXONArraysAndMaps(root)}promise.resolve()});_loaderProgress.endLoading();return promise}this.loadScene=function(offset){var index=offset+1;this.loadSceneByIndex(index)};this.loadSceneByIndex=function(index){var promise=new gs.Promise;gs.Game.profiler.sceneLoadProfiler.load.enter();this.virtualFileCache.loadSceneByIndex(index).then(function(file){onSceneLoaded(file).then(function(){promise.resolve()})});return promise};function onAssetsManifestLoaded(file){var i,asset;var root=file.getData();var images=root["images"];var sounds=root["sounds"];var fonts=root["fonts"];if(images){if(Array.isArray(images)){for(i=0;i&lt;images.length;i++){asset=gs.ImageAsset.neuw();asset.loadFromLite(images[i]);_images.add(asset)}}else{asset=gs.ImageAsset.neuw();asset.loadFromLite(images);_images.add(asset)}}if(sounds){if(Array.isArray(sounds)){for(i=0;i&lt;sounds.length;i++){var asset=gs.SoundAsset.neuw();asset.loadFromLite(sounds[i]);_sounds.add(asset)}}else{var asset=gs.SoundAsset.neuw();asset.loadFromLite(sounds);_sounds.add(asset)}}if(fonts){if(Array.isArray(fonts)){for(i=0;i&lt;fonts.length;i++){var asset=gs.FontAsset.neuw();asset.loadFromLite(fonts[i]);_fonts.add(asset)}}else{var asset=gs.FontAsset.neuw();asset.loadFromLite(fonts);_fonts.add(asset)}}}this.preloadAllScenes=function(callback){if(!validateDomain())return;_project.virtualFileCache.loadGame().then(function successLoadGame(gameFile){var scenes=gameFile.getData().scenes;if(scenes&amp;&amp;!Array.isArray(scenes)){scenes=[scenes]}callback&amp;&amp;callback.call(null,scenes)})};this.pathForImage=function(imageName){var imageAsset=_images.assetForName(imageName);if(!imageAsset){return null}var rep=imageAsset.bestFileRepresentation();if(rep){if(rep.uri){return rep.uri}return this.pathResolver.getImagePath(rep.filename)}else{return null}};this.pathForSound=function(soundName){var soundAsset=_sounds.assetForName(soundName);if(!soundAsset){return null}var rep=soundAsset.bestFileRepresentation();if(rep){return this.pathResolver.getSoundPath(rep.filename)}else{return null}};this.pathForFont=function(fontName){var fontAsset=_fonts.assetForName(fontName);if(!fontAsset){return null}var rep=fontAsset.bestFileRepresentation();if(rep){return this.pathResolver.getFontPath(rep.filename)}else{return null}};this.pathForTable=function(tableName){return this.pathResolver.getTablePath(tableName)};this.isPathCrossOrigin=function(path){var httpRegex=/^https?:\/\//;if(!httpRegex.test(path)){return false}var originRegex=/^\w+:\/\/[^\/]+/;var originMatch=originRegex.exec(path);var toOrigin=originMatch!==null?originMatch[0]:null;var fromOrigin=window.location.protocol+"//"+window.location.host;return fromOrigin!==toOrigin};this.getImageSize=function(imageName){var imageAsset=_images.assetForName(imageName);if(!imageAsset){return 0}var rep=imageAsset.bestFileRepresentation();if(rep){var numBytes=Number(rep.size)}if(!numBytes){numBytes=5e3}return numBytes};this.play=function(){if(!this._readyToPlay){_playGameQueued=true;return}var game=this.game;game.interceptKeyEvents=true;if(game.systemPaused){game.systemResume();this.startGameLoop();game.eventCenter.postEvent("resume",null)}else if(game.isPlaying){game.gameTimebase.resume();game.eventCenter.postEvent("resume",null)}else{game.updateGraphicsDimensions();if(_project._changeSceneQueued!==null){var sceneKey=_project._changeSceneQueued;if(typeof sceneKey==="number"){sceneKey=game.scenes.keyForScene(_project._changeSceneQueued)}game.forceNeedsToChangeScene(sceneKey)}game.gameTimebase=gs.Timebase.provide().init();gs.EngineContext.current.resetFrameTime();game.start(game.gameTimebase.nextTimestamp(0))}if(!this.gameLoopIsRunning()){this.startGameLoop()}game.isPlaying=true};this.gameLoopIsRunning=function(){return this.gameLoop.isRunning};this.startGameLoop=function(){this.gameLoop.start()};this.stopGameLoop=function(){this.gameLoop.stop()};this.setLoaderProgress=function(loaderProgress){if(loaderProgress){_loaderProgress=loaderProgress;_loaderProgress.beginTransition();_loaderProgress.beginLoading()}};this.addActionListener=function(area,action,listener){if(!this.actionListeners){this.actionListeners={}}if(!this.actionListeners[area]){this.actionListeners[area]={}}if(!this.actionListeners[area][action]){this.actionListeners[area][action]=[]}this.actionListeners[area][action].push(listener)};this.dispatchAction=function(area,action,args){if(!this.actionListeners){this.actionListeners={}}if(!this.actionListeners[area]){this.actionListeners[area]={}}if(this.actionListeners[area][action]){this.actionListeners[area][action].forEach(function(listener){try{listener.call(null,args)}catch(exception){gs.Log.error(exception)}})}};this.deferAction=function(area,action,args){if(!this.deferredActions){this.deferredActions=[]}this.deferredActions.push({area:area,action:action,args:args})};this.dispatchDeferredActions=function(){if(this.deferredActions){for(var index=0,end=this.deferredActions.length;index!==end;index++){var tuple=this.deferredActions[index];this.dispatchAction(tuple.area,tuple.action,tuple.args)}this.deferredActions.length=0}};this.getImages=function(){return _images};this.getSounds=function(){return _sounds};this.getFonts=function(){return _fonts};this.SHOW_FRAMERATE=false;return this};gs.Project.nodeTypeNameMap=gs.util.createObfuscationLookup({actor:"actor",actors:"actors",angle:"angle",array:"array",aspects:"aspects",assets:"assets",attribute:"attribute",attributes:"attributes",behavior:"behavior",behaviors:"behaviors",color:"color",condition:"condition",conditions:"conditions",elseBehaviors:"elseBehaviors",enumeration:"enumeration",expression:"expression",file:"file",game:"game",graphics:"graphics",images:"images",index:"index",info:"info",instructions:"instructions",layer:"layer",layers:"layers",longDescription:"longDescription",motion:"motion",pair:"pair",physics:"physics",point:"point",predicate:"predicate",prototypes:"prototypes",real:"real",reference:"reference",resolution:"resolution",resolutionIndependence:"resolutionIndependence",scene:"scene",scenes:"scenes",size:"size",sounds:"sounds",subjectPredicate:"subjectPredicate",string:"string",tags:"tags",tablecolumnassignment:"tablecolumnassignment",tablecolumns:"tablecolumns",text:"text",boolean:"boolean"});gs.Layer.prototype.render=function(){var actors=this.actors;for(var i=0,iend=actors.length;i&lt;iend;i++){var renderNode=actors[i].renderNode;if(renderNode){renderNode.compute()}}};gs.Layer.prototype.showLayer=function(scene){var space;var camera=scene.attributes.camera;if(gs.Scene.HUDDisabled){space=scene.sgScene.createSpace(gs.SGSpace.NodeType.SGSpace)}else{space=scene.sgScene.createSpace(gs.SGSpace.NodeType.SGOrtho2DSpace);if(!this.scrollable()){space._x.setValue(0);space._y.setValue(0)}else{space._x.connectToAttribute(camera.origin.x);space._y.connectToAttribute(camera.origin.y)}space._width.connectToAttribute(camera.size.width);space._height.connectToAttribute(camera.size.height);space._near.setValue(0);space._far.setValue(1);space._viewRotation.connectToAttribute(this.game().devices.screen.deviceRotation);space._modelRotation.connectToAttribute(camera.rotation)}var actors=this.actors;for(var i=0,iend=actors.length;i&lt;iend;i++){actors[i].showActor(space)}this.space=space;this.sortRenderNodes()};gs.Layer.prototype.hideLayer=function(){this.space=null};gs.Layer.prototype.sortRenderNodes=function(){var actors=this.actors;for(var i=0,iend=actors.length;i&lt;iend;i++){actors[i].setLayerIndex(i)}this.space.sortRenderNodes()};gs.Layer.prototype.makeActorVisible=function(actor){var space=this.space;actor.showActor(space);this.sortRenderNodes()};gs.Scene.showScene=function(clearSceneBeforeRender){var game=this.game();var sgScene=gs.SGScene.create(game.sharedAssetManager,game.sharedHandleManager);this.sgScene=sgScene;gs.ObjectList.prototype.makeChildrenPerformFunction.call(this.layers,gs.Layer.prototype.showLayer,this);var defaultSpace=sgScene.defaultSpace();if(!gs.Scene.HUDDisabled){if(clearSceneBeforeRender){var clearNode=defaultSpace.createNode(gs.SGSpace.NodeType.SGClear);var color=this.attributes.color;color.red.connectToSprite(clearNode,"colorR","dirty");color.green.connectToSprite(clearNode,"colorG","dirty");color.blue.connectToSprite(clearNode,"colorB","dirty")}}var camera=this.attributes.camera;var wDivider=defaultSpace.createNode(gs.SGSpace.NodeType.SGArithmetic);var hDivider=defaultSpace.createNode(gs.SGSpace.NodeType.SGArithmetic);wDivider.setOperation("/");hDivider.setOperation("/");wDivider._input1.connectToAttribute(camera.size.width);hDivider._input1.connectToAttribute(camera.size.height);wDivider._input2.setValue(2);hDivider._input2.setValue(2);var xAdder=defaultSpace.createNode(gs.SGSpace.NodeType.SGArithmetic);var yAdder=defaultSpace.createNode(gs.SGSpace.NodeType.SGArithmetic);xAdder._input1.connectToAttribute(camera.origin.x);yAdder._input1.connectToAttribute(camera.origin.y);xAdder._input2.connectToPort(wDivider._output);yAdder._input2.connectToPort(hDivider._output);var soundListener=defaultSpace.createNode(gs.SGSpace.NodeType.SGSoundListener);soundListener._x.connectToPort(xAdder._output);soundListener._y.connectToPort(yAdder._output);soundListener.compute();this._visible=true};gs.Scene.hideScene=function(){this.sgScene=null;this._visible=null};gs.Actor.isDrawing=function(){return!!this.rootSpace};gs.Actor.showActor=function(space){this.rootSpace=space;this.spaceSources=gs.array.provide();this.spaceSources[0]=this;this.nodeSources=gs.array.provide();this.nodeSources[0]=this;this.createSceneGraph()};gs.Actor.hideActor=function(){this.deleteSceneGraph();this.rootSpace=null;if(this.spaceSources){gs.array.recycle(this.spaceSources);this.spaceSources=null}if(this.nodeSources){gs.array.recycle(this.nodeSources);this.nodeSources=null}};gs.Actor.topLevelSpace=function(){var topLevelSpace=this.rootSpace;var spaceSources=this.spaceSources;if(spaceSources&amp;&amp;spaceSources.length&gt;0){topLevelSpace=spaceSources[spaceSources.length-1].getSpace()}return topLevelSpace};gs.Actor.createSceneGraph=function(){var spaceSources=this.spaceSources;var nodeSources=this.nodeSources;var topLevelSpace=this.rootSpace;var i,count;if(spaceSources){count=spaceSources.length;for(i=0;i&lt;count;++i){topLevelSpace=spaceSources[i].createSpace(topLevelSpace)}}if(nodeSources){var nodeIndex=0;count=nodeSources.length;for(i=0;i&lt;count;++i){nodeIndex=nodeIndex+nodeSources[i].createNodesInSpace(topLevelSpace,nodeIndex)}}if(topLevelSpace){topLevelSpace.sortRenderNodes()}};gs.Actor.deleteSceneGraph=function(){var rootSpace=this.rootSpace;var spaceSources=this.spaceSources;var nodeSources=this.nodeSources;var topLevelSpace=this.topLevelSpace();if(nodeSources){var count=nodeSources.length;for(var i=0;i&lt;count;++i){nodeSources[i].removeNodesFromSpace(topLevelSpace)}}if(spaceSources){for(var i=spaceSources.length-1;i&gt;=0;i--){var parentSpace;if(i===0){parentSpace=rootSpace}else{parentSpace=spaceSources[i-1].getSpace()}spaceSources[i].removeSpace(parentSpace)}}};gs.Actor.getLayerIndex=function(){return this._layerIndex};gs.Actor.setLayerIndex=function(index){this._layerIndex=index;if(this.spaceSources){if(this.spaceSources.length&gt;0){this.spaceSources[0].getSpace().setLayer(index)}else{this._spriteNode.setLayer(index)}}};gs.Actor.addSpaceSource=function(spaceSource){if(!this.visible()||!this.isDrawing()){return}var layerIndex=this.getLayerIndex();this.deleteSceneGraph();var spaceSources=this.spaceSources;spaceSources.push(spaceSource);this.createSceneGraph();this.setLayerIndex(layerIndex);var layer=this.layer;if(layer){layer.sortRenderNodes()}};gs.Actor.removeSpaceSource=function(spaceSource){if(!this.visible()||!this.isDrawing()){return}var layerIndex=this.getLayerIndex();this.deleteSceneGraph();var spaceSources=this.spaceSources;if(spaceSources){var index=spaceSources.indexOf(spaceSource);if(index&gt;-1){spaceSources.splice(index,1)}}this.createSceneGraph();this.setLayerIndex(layerIndex);var layer=this.layer;if(layer){layer.sortRenderNodes()}};gs.Actor.addNodeSource=function(nodeSource){if(!this.visible()||!this.isDrawing()){return}var topLevelSpace=this.topLevelSpace();var nodeSources=this.nodeSources;if(nodeSources){nodeSources[nodeSources.length]=nodeSource;var nodeIndex=topLevelSpace.countRenderNodes();nodeSource.createNodesInSpace(topLevelSpace,nodeIndex);topLevelSpace.sortRenderNodes()}};gs.Actor.removeNodeSource=function(nodeSource){if(!this.visible()||!this.isDrawing()){return}var topLevelSpace=this.topLevelSpace();var nodeSources=this.nodeSources;if(nodeSources){var index=nodeSources.indexOf(nodeSource);if(index&gt;-1){nodeSources.splice(index,1);nodeSource.removeNodesFromSpace(topLevelSpace)}}};gs.Actor.createSpace=function(parentSpace){var actorSpace;if(this.scene.wrappingEnabled()){actorSpace=parentSpace.createNode(gs.SGSpace.NodeType.SGWrap);var attributes=this.attributes;actorSpace._x.connectToAttribute(attributes.position.x);actorSpace._y.connectToAttribute(attributes.position.y);actorSpace._wrapX.setValue(false);actorSpace._wrapY.setValue(false)}else{actorSpace=parentSpace.createNode(gs.SGSpace.NodeType.SGSpace)}actorSpace.visible=this.visible();this.actorSpace=actorSpace;return actorSpace};gs.Actor.getSpace=function(){return this.actorSpace};gs.Actor.removeSpace=function(parentSpace){if(this.actorSpace){parentSpace.removeNode(this.actorSpace);if(!(this.actorSpace instanceof gs.SGWrapNode)){gs.SGSpace.recycle(this.actorSpace)}this.actorSpace=null}};gs.Actor.createNodesInSpace=function(parentSpace,nodeIndex){var sprite=parentSpace.createNode(gs.SGSpace.NodeType.SGSprite);this._spriteNode=sprite;var attributes=this.attributes;attributes.position.x.connectToSprite(sprite,"x","dirtyTransform");attributes.position.y.connectToSprite(sprite,"y","dirtyTransform");attributes.rotation.connectToSprite(sprite,"angleDeg","dirtyTransform");attributes.size.width.connectToSprite(sprite,"width","dirtyTransform");attributes.size.height.connectToSprite(sprite,"height","dirtyTransform");attributes.color.red.connectToSprite(sprite,"colorR","dirtyColor");attributes.color.green.connectToSprite(sprite,"colorG","dirtyColor");attributes.color.blue.connectToSprite(sprite,"colorB","dirtyColor");attributes.color.alpha.connectToSprite(sprite,"colorA","dirtyColor");attributes.image.connectToSprite(sprite,"imageID","dirtyImage");var graphics=this.aspects.graphics.attributes;graphics.flipHorizontally.connectToSprite(sprite,"flipY","dirtyTransform");graphics.flipVertically.connectToSprite(sprite,"flipX","dirtyTransform");graphics.blendingMode.connectToSprite(sprite,"blendMode","dirtyGraphics");graphics.horizontalWrap.connectToSprite(sprite,"wrapModeS","dirtyGraphics");graphics.verticalWrap.connectToSprite(sprite,"wrapModeT","dirtyGraphics");graphics.horizontalAnchor.connectToSprite(sprite,"anchorS","dirtyGraphics");graphics.verticalAnchor.connectToSprite(sprite,"anchorT","dirtyGraphics");graphics.tileWidth.connectToSprite(sprite,"tileWidth","dirtyGraphics");graphics.tileHeight.connectToSprite(sprite,"tileHeight","dirtyGraphics");return 1};gs.Actor.removeNodesFromSpace=function(parentSpace){var attributes=this.attributes;attributes.position.x.disconnectFromSprite();attributes.position.y.disconnectFromSprite();attributes.rotation.disconnectFromSprite();attributes.size.width.disconnectFromSprite();attributes.size.height.disconnectFromSprite();attributes.color.red.disconnectFromSprite();attributes.color.green.disconnectFromSprite();attributes.color.blue.disconnectFromSprite();attributes.color.alpha.disconnectFromSprite();attributes.image.disconnectFromSprite();var graphics=this.aspects.graphics.attributes;graphics.flipHorizontally.disconnectFromSprite();graphics.flipVertically.disconnectFromSprite();graphics.blendingMode.disconnectFromSprite();graphics.horizontalWrap.disconnectFromSprite();graphics.verticalWrap.disconnectFromSprite();graphics.horizontalAnchor.disconnectFromSprite();graphics.verticalAnchor.disconnectFromSprite();graphics.tileWidth.disconnectFromSprite();graphics.tileHeight.disconnectFromSprite();parentSpace.removeNode(this._spriteNode);this._spriteNode.recycle();this._spriteNode=null};gs.Actor.startWrap=function(dimension,wrapValue){var wrapSpace=this.actorSpace;if(dimension===gs.Vector2.X_COMPONENT){wrapSpace._wrapX.setValue(true);wrapSpace._wrapWidth.setValue(wrapValue)}else{wrapSpace._wrapY.setValue(true);wrapSpace._wrapHeight.setValue(wrapValue)}};gs.Actor.stopWrap=function(dimension){var wrapSpace=this.actorSpace;if(dimension===gs.Vector2.X_COMPONENT){wrapSpace._wrapX.setValue(false)}else{wrapSpace._wrapY.setValue(false)}};gs.Game.render=function(){if(this.loadingFlag){return}for(var i=0,iend=this.currentSceneStack.length;i&lt;iend;i++){var scene=this.currentSceneStack[i];var draw=scene.frameCount&gt;2;this.currentSceneStack[i].sgScene.render(this,draw)}if(gs.globalOptions.forceTexturePrimeFrames&amp;&amp;this.texturePrimeFrames&lt;gs.globalOptions.forceTexturePrimeFrames){this.texturePrimeFrames++;this.renderer.drawBlank()}};gs.Game.updateMousePosition=function(locationInViewX,locationInViewY){this.devices.mouse.position.x.fastSetValue(locationInViewX);this.devices.mouse.position.y.fastSetValue(locationInViewY)};gs.Game.mouseButtonDown=function(locationInViewX,locationInViewY){this.devices.mouse.button.fastSetValue(true);this.updateMousePosition(locationInViewX,locationInViewY)};gs.Game.mouseButtonUp=function(viewLocationX,viewLocationY){this.devices.mouse.button.fastSetValue(false)};gs.Game.updateAccelerometer=function(x,y,z){this.devices.accelerometer.x.fastSetValue(x);this.devices.accelerometer.y.fastSetValue(y);this.devices.accelerometer.z.fastSetValue(z)};gs.Game.updateTouchPosition=function(index,locationInViewX,locationInViewY,active){var key=gs.CompoundAttribute.obfuscationLookupTable["touch"+index];var touchActiveAttribute=this.devices.touches.active[key];touchActiveAttribute.fastSetValue(active);var touchAttribute=this.devices.touches[key];touchAttribute.x.fastSetValue(locationInViewX);touchAttribute.y.fastSetValue(locationInViewY)};gs.Game.touchDown=function(index,locationInViewX,locationInViewY){this.updateTouchPosition(index,locationInViewX,locationInViewY,true)};gs.Game.touchUp=function(index,locationInViewX,locationInViewY){this.updateTouchPosition(index,locationInViewX,locationInViewY,false)};gs.Game.datetime=new Date;gs.Game.updateClock=function(){var datetime=gs.Game.datetime;var now=Date.now();datetime.setTime(now);this.devices.clock.epochTime.fastSetValue(now);this.devices.clock.year.fastSetValue(datetime.getFullYear());this.devices.clock.month.fastSetValue(datetime.getMonth()+1);this.devices.clock.day.fastSetValue(datetime.getDate());this.devices.clock.hour.fastSetValue(datetime.getHours());this.devices.clock.minute.fastSetValue(datetime.getMinutes());this.devices.clock.second.fastSetValue(datetime.getSeconds());this.devices.clock.millisecond.fastSetValue(datetime.getMilliseconds())};gs.SGAnchorMode={SGAnchorMin:0,SGAnchorCenter:1,SGAnchorMax:2};gs.SGBlendingMode={Normal:0,Opaque:1,Additive:2,Screen:3,Multiply:4};gs.SGTextAlignment={Left:0,Center:1,Right:2};gs.SGWrapMode={SGWrapScale:0,SGWrapFixed:1,SGWrapTile:2};gs.SGTextureRect=function(left,bottom,right,top){this.left=left;this.bottom=bottom;this.right=right;this.top=top};gs.SGTextureRect.prototype.getWidth=function(){return Math.abs(this.right-this.left)};gs.SGTextureRect.prototype.getHeight=function(){return Math.abs(this.top-this.bottom)};gs.SGTextureRect.prototype.cropHorizontallyExact=function(newWidth,anchorMode){var oldWidth=this.right-this.left;switch(anchorMode){case gs.SGAnchorMode.SGAnchorMin:this.right=this.left+newWidth;break;case gs.SGAnchorMode.SGAnchorCenter:var offset=(oldWidth-newWidth)*.5;this.left=this.left+offset;this.right=this.left+newWidth;break;case gs.SGAnchorMode.SGAnchorMax:this.right=oldWidth;this.left=oldWidth-newWidth;break}};gs.SGTextureRect.prototype.cropVerticallyExact=function(newHeight,anchorMode){var oldHeight=this.top-this.bottom;switch(anchorMode){case gs.SGAnchorMode.SGAnchorMin:this.top=this.bottom+newHeight;break;case gs.SGAnchorMode.SGAnchorCenter:var offset=(oldHeight-newHeight)*.5;this.bottom=this.bottom+offset;this.top=this.bottom+newHeight;break;case gs.SGAnchorMode.SGAnchorMax:this.top=oldHeight;this.bottom=oldHeight-newHeight;break}};gs.SGNode=function(){this.dirty=true};gs.SGNode.prototype={update:function(){if(this.dirty){this.dirty=false;this.compute()}},compute:function(){}};gs.SGPort=function(){this._value=null;this.ignoreDirty=false;this.node=null;this.sourcePort=null;this.destPorts=gs.array.provide()};gs.Pool.init(gs.SGPort);gs.SGPort.addOutputPort=function(node){var newPort=gs.SGPort.provide();newPort.node=node;if(!node.outputPortsArray){node.outputPortsArray=gs.array.provide()}node.outputPortsArray.push(newPort);return newPort};gs.SGPort.addInputPort=function(node,ignoreDirty){var newPort=gs.SGPort.provide();newPort.ignoreDirty=!!ignoreDirty;newPort.node=node;var outputCount=node.outputPortsArray?node.outputPortsArray.length:0;for(var i=0;i&lt;outputCount;++i){newPort.addDestPort(node.outputPortsArray[i])}return newPort};gs.SGPort.prototype={getValue:function(){if(this.sourcePort){return this.sourcePort.getValue()}else{this.node.update();return this._value}},stringValue:function(){var v=this.getValue();return gs.Attribute.convertValueToString(v)},numberValue:function(){return Number(this.getValue())},intValue:function(){return this.numberValue()|0},boolValue:function(){return Boolean(this.getValue())},markAsDirty:function(){if(this.ignoreDirty){return}var node=this.node;if(node.dirty){return}for(var i=0,iend=this.destPorts.length;i&lt;iend;i++){this.destPorts[i].markAsDirty()}node.dirty=true},markAsForceDirty:function(){var node=this.node;var i=0,iend=this.destPorts.length;for(;i&lt;iend;i++){this.destPorts[i].markAsForceDirty()}node.dirty=true},addDestPort:function(port){this.destPorts.push(port)},removeDestPort:function(port){var portIndex=this.destPorts.indexOf(port);if(portIndex&gt;-1){this.destPorts.splice(portIndex,1)}},setValue:function(value){if(this._value!==value){this._value=value;this.markAsDirty()}},setValueForceDirty:function(value){this._value=value;this.markAsForceDirty()},connectToPort:function(source){if(!source){this.disconnect()}else{this.sourcePort=source;source.addDestPort(this)}},disconnect:function(){if(this.sourcePort){this.sourcePort.removeDestPort(this);this.sourcePort=null}},connectToAttribute:function(attribute){var attributeNode=attribute.getNode();this.connectToPort(attributeNode._value)}};gs.SGRenderNode=function(){gs.SGNode.call(this);this.layer=0};gs.SGRenderNode.compare=function(node1,node2){if(node1.layer&lt;node2.layer){return-1}else if(node1.layer&gt;node2.layer){return 1}return 0};gs.SGRenderNode.prototype=gs.subclass(gs.SGNode,{setLayer:function(layerIndex){this.layer=layerIndex}});gs.SGSpace=function(){gs.SGRenderNode.call(this);if(!this.allNodes){this.allNodes=gs.array.provide()}this.singleRenderNode=null;this.renderNodes=null;this.assetManager=null;this.handleManager=null};gs.SGSpace.NodeType={SGArithmetic:"SGArithmetic",SGAssetLoader:"SGAssetLoader",SGAttribute:"SGAttribute",SGClear:"SGClear",SGColor:"SGColor",SGReplicator:"SGReplicator",SGRender:"SGRender",SGSpace:"SGSpace",SGSprite:"SGSprite",SGOrtho2DSpace:"SGOrtho2DSpace",SGParticleSystem:"SGParticleSystem",SGText:"SGText",SGWrap:"SGWrap",SGSoundListener:"SGSoundListener"};gs.Pool.init(gs.SGSpace);gs.SGSpace.prototype=gs.subclass(gs.SGRenderNode,{init:function(assetManager,handleManager){this.assetManager=assetManager;this.handleManager=handleManager;return this},initFromParent:function(parentSpace){return this.init(parentSpace.assetManager,parentSpace.handleManager)},createNode:function(nodeType){var node=null;switch(nodeType){case gs.SGSpace.NodeType.SGArithmetic:node=gs.SGArithmeticNode.provide();break;case gs.SGSpace.NodeType.SGClear:node=gs.SGClearNode.provide();break;case gs.SGSpace.NodeType.SGColor:node=gs.SGColorNode.provide();break;case gs.SGSpace.NodeType.SGReplicator:node=gs.SGReplicatorNode.provide().initFromParent(this);break;case gs.SGSpace.NodeType.SGSpace:node=gs.SGSpace.provide().initFromParent(this);break;case gs.SGSpace.NodeType.SGSprite:node=gs.SGSpriteNode.provide();break;case gs.SGSpace.NodeType.SGParticleSystem:node=gs.SGParticleSystemNode.provide();break;case gs.SGSpace.NodeType.SGText:node=gs.SGTextNode.provide();break;case gs.SGSpace.NodeType.SGWrap:node=gs.SGWrapNode.provide().init(this.assetManager,this.handleManager);break;case gs.SGSpace.NodeType.SGSoundListener:node=gs.SGSoundListenerNode.provide();break;default:node=null}this.addNode(node);return node},removeNode:function(node){var index=this.allNodes.indexOf(node);if(index&gt;-1){if(node instanceof gs.SGRenderNode){if(node===this.singleRenderNode){this.singleRenderNode=null}else{var renderNodeIndex=this.renderNodes.indexOf(node);if(renderNodeIndex&gt;-1){this.renderNodes.splice(renderNodeIndex,1)}}}this.allNodes.splice(index,1)}},compute:function(renderer,draw){this.dirty=false;this.render(renderer,draw)},sortRenderNodes:function(){if(this.renderNodes){this.renderNodes.sort(gs.SGRenderNode.compare)}},render:function(renderer,draw){if(this.visible===false){return}if(this.renderNodes){this.renderAll(renderer,draw)}else if(this.singleRenderNode){this.singleRenderNode.compute(renderer,draw)}},renderAll:function(renderer,draw){var nodes=this.renderNodes;for(var i=0,iend=nodes.length;i&lt;iend;i++){nodes[i].compute(renderer,draw)}},addNode:function(node){this.allNodes.push(node);if(node instanceof gs.SGRenderNode){if(this.renderNodes){this.renderNodes[this.renderNodes.length]=node}else if(this.singleRenderNode){this.renderNodes=gs.array.provide();this.renderNodes[0]=this.singleRenderNode;this.singleRenderNode=null;this.renderNodes[1]=node}else{this.singleRenderNode=node}}},countRenderNodes:function(){return this.singleRenderNode?1:this.renderNodes?this.renderNodes.length:0}});gs.SGOrtho2DSpace=function(){gs.SGSpace.call(this);this._x=gs.SGPort.addInputPort(this);this._y=gs.SGPort.addInputPort(this);this._width=gs.SGPort.addInputPort(this);this._height=gs.SGPort.addInputPort(this);this._near=gs.SGPort.addInputPort(this);this._far=gs.SGPort.addInputPort(this);this._viewRotation=gs.SGPort.addInputPort(this);this._modelRotation=gs.SGPort.addInputPort(this)};gs.Pool.init(gs.SGOrtho2DSpace);gs.SGOrtho2DSpace.prototype=gs.subclass(gs.SGSpace,{render:function(renderer,draw){this.willRender(renderer);gs.SGSpace.prototype.render.call(this,renderer,draw);this.didRender(renderer)},willRender:function(renderer){var x=this._x.getValue();var y=this._y.getValue();var width=this._width.getValue();var height=this._height.getValue();var viewRotation=this._viewRotation.getValue();var modelRotation=this._modelRotation.getValue();renderer.beginSpace(x,y,width,height,viewRotation,modelRotation)},didRender:function(renderer){renderer.endSpace()}});gs.SGScene=function(assetManager,handleManager){this.spaces=gs.array.provide();this._defaultSpace=gs.SGSpace.provide().init(assetManager,handleManager);this.assetManager=assetManager;this.handleManager=handleManager};gs.SGScene.create=function(assetManager,handleManager){return new gs.SGScene(assetManager,handleManager)};gs.SGScene.prototype={defaultSpace:function(){return this._defaultSpace},createSpace:function(spaceClass){var space=null;if(spaceClass===gs.SGSpace.NodeType.SGOrtho2DSpace){space=gs.SGOrtho2DSpace.provide().init(this.assetManager,this.handleManager)}else{space=gs.SGSpace.provide().init(this.assetManager,this.handleManager)}this.spaces.push(space);return space},removeSpace:function(space){},render:function(game,draw){var renderer=game.renderer;renderer.beginScene();this._defaultSpace.compute(renderer,draw);var spaceCount=this.spaces.length;for(var index=0;index&lt;spaceCount;++index){this.spaces[index].compute(renderer,draw)}renderer.endScene()}};gs.SGAttributeNode=function(){gs.SGNode.call(this);this._value=gs.SGPort.addOutputPort(this)};gs.Pool.init(gs.SGAttributeNode);gs.SGAttributeNode.prototype=gs.subclass(gs.SGNode,{setValue:function(newValue){this._value.setValue(newValue)}});gs.SGAssetLoaderNode=function(){gs.SGNode.call(this);this.assetManager=null};gs.SGAssetLoaderNode.prototype=gs.subclass(gs.SGNode);gs.SGColorNode=function(){gs.SGNode.call(this);this._output=gs.SGPort.addOutputPort(this);this._r=gs.SGPort.addInputPort(this);this._g=gs.SGPort.addInputPort(this);this._b=gs.SGPort.addInputPort(this);this._a=gs.SGPort.addInputPort(this);this._r._value=1;this._g._value=1;this._b._value=1;this._a._value=1;var color=gs.array.provide();color[0]=1;color[1]=1;color[2]=1;color[3]=1;this._output._value=color};gs.Pool.init(gs.SGColorNode);gs.SGColorNode.prototype=gs.subclass(gs.SGNode,{compute:function(){var color=this._output._value;color[0]=this._r.getValue();color[1]=this._g.getValue();color[2]=this._b.getValue();color[3]=this._a.getValue()}});gs.SGImageLoaderNode=function(){gs.SGAssetLoaderNode.call(this);this._asset=gs.SGPort.addOutputPort(this);this._name=gs.SGPort.addInputPort(this);this.previousImageName=null;this.handleManager=null};gs.Pool.init(gs.SGImageLoaderNode);gs.SGImageLoaderNode.prototype=gs.subclass(gs.SGAssetLoaderNode,{init:function(assetManager,handleManager){this.assetManager=assetManager;this.handleManager=handleManager;return this},compute:function(){var imageName=this._name.getValue();if(!imageName){this.previousImageName=null;this._asset._value=this.handleManager.getColorHandle(0,0,0,0);return}if(imageName===this.previousImageName){return}this.previousImageName=imageName;var resource=this.assetManager.imageForName(imageName);this._asset._value=this.handleManager.getImageHandle(resource)}});gs.SGWhiteColor=[1,1,1,1];gs.SGSpriteNode=function(){gs.SGRenderNode.call(this);this.reset()};gs.Pool.init(gs.SGSpriteNode);gs.SGSpriteNode.prototype=gs.subclass(gs.SGRenderNode,{reset:function(){if(!this.color){this.color=gs.array.provide()}this.dirtyTransform=true;this.x=0;this.y=0;this.angleDeg=0;this.angleRad=0;this.width=0;this.height=0;this.flipX=false;this.flipY=false;this.dirtyImage=true;this.imageID=null;this.imageHandle=null;this.loadingHandle=null;this.dirtyColor=true;this.colorR=1;this.colorG=1;this.colorB=1;this.colorA=1;this.color[0]=1;this.color[1]=1;this.color[2]=1;this.color[3]=1;this.dirtyGraphics=true;this.blendMode=0;this.wrapModeS=0;this.wrapModeT=0;this.anchorS=0;this.anchorT=0;this.tileWidth=0;this.tileHeight=0},recycle:function(){if(this.imageHandle){this.imageHandle.release()}if(this.loadingHandle){this.loadingHandle.release()}gs.SGSpriteNode.recycle(this)},updateDirty:function(renderer){if(this.dirtyTransform){this.angleRad=this.angleDeg*-gsMath.DEG2RAD;this.dirtyTransform=false}if(this.dirtyColor){if(this.blendMode===1){this.colorA=1}var color=this.color;color[0]=this.colorR;color[1]=this.colorG;color[2]=this.colorB;color[3]=this.colorA;this.dirtyColor=false}var imageHandle=this.imageHandle;var dirtyImage=this.dirtyImage;if(dirtyImage){if(this.loadingHandle){this.loadingHandle.release();this.loadingHandle=null}var imageID=this.imageID;if(!imageID){if(this.imageHandle){this.imageHandle.release();this.imageHandle=null}}else{var resource=gs.AssetManager.current.imageForName(imageID);var newHandle=renderer.handleManager.getImageHandle(resource);if(newHandle.ready){if(this.imageHandle){this.imageHandle.release()}this.imageHandle=newHandle}else{this.loadingHandle=newHandle}}imageHandle=this.imageHandle;this.dirtyImage=false}if(dirtyImage||this.dirtyGraphics||imageHandle&amp;&amp;imageHandle.isCanvas){if(imageHandle){imageHandle.update(this)}this.dirtyGraphics=false}},updateLoading:function(){var loadingHandle=this.loadingHandle;loadingHandle.checkReady();if(loadingHandle.ready){if(this.imageHandle){this.imageHandle.release()}this.imageHandle=loadingHandle;this.loadingHandle=null;loadingHandle.update(this)}},compute:function(renderer,draw){gs.Game.profiler.entityCounter.sprites.increment();var anyDirty=this.dirtyTransform||this.dirtyColor||this.dirtyImage||this.dirtyGraphics;if(anyDirty||renderer instanceof gs.SGCanvasRenderer){this.updateDirty(renderer)}this.dirty=false;if(this.loadingHandle){this.updateLoading()}var imageHandle=this.imageHandle;if(imageHandle&amp;&amp;!imageHandle.ready){imageHandle.checkReady()}if(!draw||imageHandle&amp;&amp;!imageHandle.ready||this.width&lt;=0||this.height&lt;=0||this.colorA&lt;=0){return}if(imageHandle){if(this.wrapModeS!==0||this.wrapModeT!==0){renderer.drawImageWithWrap(this,imageHandle)}else{renderer.drawImage(this,imageHandle)}}else if(!this.loadingHandle){renderer.drawRect(this)}}});gs.SGClearNode=function(){gs.SGRenderNode.call(this);this.colorR=1;this.colorG=1;this.colorB=1};gs.Pool.init(gs.SGClearNode);gs.SGClearNode.prototype=gs.subclass(gs.SGRenderNode,{compute:function(renderer,draw){if(draw){renderer.clear(this.colorR,this.colorG,this.colorB)}}});gs.SGArithmeticNode=function(){gs.SGNode.call(this);this._output=gs.SGPort.addOutputPort(this);this._input1=gs.SGPort.addInputPort(this);this._input2=gs.SGPort.addInputPort(this);this._operation="+"};gs.Pool.init(gs.SGArithmeticNode);gs.SGArithmeticNode.prototype=gs.subclass(gs.SGNode,{setOperation:function(operation){this._operation=operation},compute:function(){var operand1=this._input1.getValue();var operand2=this._input2.getValue();switch(this._operation){case"+":this._output._value=operand1+operand2;break;case"-":this._output._value=operand1-operand2;break;case"*":this._output._value=operand1*operand2;break;case"/":this._output._value=operand1/operand2;break;case"%":this._output._value=operand1%operand2;break}}});gs.SGReplicatorNode=function(){gs.SGSpace.call(this);this.angle=0;this.spacing=0;this.copies=0};gs.Pool.init(gs.SGReplicatorNode);gs.SGReplicatorNode.prototype=gs.subclass(gs.SGSpace,{render:function(renderer,draw){this.dirty=false;renderer.pushMatrix();for(var i=0;i&lt;this.copies;i++){gs.SGSpace.prototype.render.call(this,renderer,draw);renderer.transformPolar(this.angle,this.spacing)}renderer.popMatrix()}});gs.SGTextNode=function(){gs.SGSpriteNode.call(this);this.dirtyText=false;this.text=null;this.safeText=null;this.cachedLines=null;this.fontFamily=null;this.sizePx=0;this.alignment=gs.SGTextAlignment.Left;this.wrap=false;this.lineHeightFactor=1.35};gs.Pool.init(gs.SGTextNode);gs.SGTextNode.prototype=gs.subclass(gs.SGSpriteNode,{init:function(){this.dirtyTransform=true;this.dirtyColor=true;this.dirtyText=true;this.lineHeight=this.sizePx*this.lineHeightFactor},compute:function(renderer,draw){this.dirty=false;if(!gs.debug.text){return}if(this.dirtyTransform){this.angleRad=this.angleDeg*-gsMath.DEG2RAD;this.dirtyTransform=false}if(this.dirtyColor){var color=this.color;color[0]=this.colorR;color[1]=this.colorG;color[2]=this.colorB;color[3]=this.colorA;this.dirtyColor=false}if(this.dirtyText){if(this.cachedLines){gs.array.recycle(this.cachedLines)}this.safeText=String(this.text);this.safeText=gs.html5.Text.normalizeString(this.safeText);this.cachedLines=null;this.dirtyText=false}if(draw){this.cachedLines=renderer.drawText(this,this.cachedLines||this.safeText)}}});gs.SGWrapNode=function(){gs.SGSpace.call(this);this._x=gs.SGPort.addInputPort(this);this._y=gs.SGPort.addInputPort(this);this._wrapX=gs.SGPort.addInputPort(this);this._wrapY=gs.SGPort.addInputPort(this);this._wrapWidth=gs.SGPort.addInputPort(this);this._wrapHeight=gs.SGPort.addInputPort(this)};gs.Pool.init(gs.SGWrapNode);gs.SGWrapNode.prototype=gs.subclass(gs.SGSpace,{render:function(renderer,draw){this.dirty=false;var wrapX=this._wrapX.getValue();var wrapY=this._wrapY.getValue();gs.SGSpace.prototype.render.call(this,renderer,draw);var xOffset=0;var yOffset=0;if(wrapX){var wrapWidth=this._wrapWidth.getValue();var x=this._x.getValue();if(x&lt;wrapWidth*.5){xOffset=wrapWidth}else{xOffset=-wrapWidth}renderer.pushMatrix();renderer.transformPolar(0,xOffset);gs.SGSpace.prototype.render.call(this,renderer,draw);renderer.popMatrix()}if(wrapY){var wrapHeight=this._wrapHeight.getValue();var y=this._y.getValue();if(y&lt;wrapHeight*.5){yOffset=-wrapHeight}else{yOffset=wrapHeight}renderer.pushMatrix();renderer.transformPolar(-90,yOffset);gs.SGSpace.prototype.render.call(this,renderer,draw);renderer.popMatrix()}if(wrapX&amp;&amp;wrapY){renderer.pushMatrix();renderer.transformPolar(0,xOffset);renderer.transformPolar(-90,yOffset);gs.SGSpace.prototype.render.call(this,renderer,draw);renderer.popMatrix()}}});gs.InternalParticle=function(){this.initialized=false;this.startTime=0;this.lifeTime=0;this.initialX=0;this.initialY=0;this.initialDX=0;this.initialDY=0;this.initialAngleRad=0;this.angularVelocityRad=0;this.sizeBegin=0;this.sizeEnd=0;this.sizeTime=0;this.colorTime=0};gs.Pool.init(gs.InternalParticle);gs.InternalParticle.prototype.toString=function(){return this.startTime};gs.SGParticleSystemNode=function(){gs.SGRenderNode.call(this);this.reset()};gs.SGParticleSystemNode.interpolateFast=function(begin,end,delta){return begin+(end-begin)*delta};gs.Pool.init(gs.SGParticleSystemNode);gs.SGParticleSystemNode.prototype=gs.subclass(gs.SGRenderNode,{reset:function(){if(!this.particles){this.particles=gs.array.provide();this.colorBegin=gs.array.provide();this.colorEnd=gs.array.provide();this.particleColor=gs.array.provide()}this.hasAllocatedParticles=false;this.dirtyOrigin=false;this.dirtyOffset=false;this.dirtySettings=false;this.attributesWithExpressions=null;this.time=0;this.spawnParticles=false;this.stopSpawning=false;this.particleCount=0;this.lifeTime=0;this.lifeTimeMin=0;this.lifeTimeMax=0;this.lifeStart=0;this.gravityX=0;this.gravityY=0;this.originX=0;this.originY=0;this.originAngleDeg=0;this.originAngleRad=0;this.offsetX=0;this.offsetY=0;this.offsetAngleDeg=0;this.offsetAngleRad=0;this.emitterX=0;this.emitterY=0;this.emitterAngleDeg=0;this.emitterAngleRad=0;this.imageID=null;this.imageHandle=null;this.blendMode=0;var colorBegin=this.colorBegin;colorBegin[0]=1;colorBegin[1]=1;colorBegin[2]=1;colorBegin[3]=1;var colorEnd=this.colorEnd;colorEnd[0]=1;colorEnd[1]=1;colorEnd[2]=1;colorEnd[3]=1;this.colorTime=0;this.colorChanges=false;this.onlyAlphaChanges=false;this.speed=0;this.particleAngleDeg=0;this.particleAngleRad=0;this.particleAngularVelocityDeg=0;this.particleAngularVelocityRad=0;this.sizeBegin=0;this.sizeEnd=0;this.sizeTime=0;this.sizeChanges=false;var particleColor=this.particleColor;particleColor[0]=1;particleColor[1]=1;particleColor[2]=1;particleColor[3]=1},recycle:function(){var n=this.particleCount;var particles=this.particles;for(var i=0;i&lt;n;i++){gs.InternalParticle.recycle(particles[i])}particles.length=0;this.particleCount=0;this.hasAllocatedParticles=false;if(this.imageHandle){this.imageHandle.release();this.imageHandle=null}this.attributesWithExpressions=null;gs.SGParticleSystemNode.recycle(this)},allocateParticles:function(){var n=this.particleCount;var particles=this.particles;for(var i=0;i&lt;n;i++){particles[i]=gs.InternalParticle.provide()}this.hasAllocatedParticles=true},init:function(){this.dirtyOrigin=true;this.dirtyOffset=true;this.dirtySettings=true;this.lifeTimeMax=this.lifeTime;this.lifeTimeMin=this.lifeTime*.5;var a=this.colorBegin;var b=this.colorEnd;this.onlyAlphaChanges=this.colorChanges&amp;&amp;(a[3]!==b[3]&amp;&amp;a[0]===b[0]&amp;&amp;a[1]===b[1]&amp;&amp;a[2]===b[2]);if(!this.hasAllocatedParticles){this.allocateParticles()}this.generateParticles()},randomizeParticle:function(particle){this.updateDynamicValues();var direction=this.emitterAngleRad;var velocity=this.speed;particle.initialX=this.emitterX;particle.initialY=this.emitterY;particle.initialDX=Math.cos(direction)*velocity;particle.initialDY=Math.sin(direction)*velocity;particle.initialAngleRad=this.particleAngleRad;particle.angularVelocityRad=this.particleAngularVelocityRad;particle.lifeTime=Math.random()*(this.lifeTimeMax-this.lifeTimeMin)+this.lifeTimeMin;particle.sizeBegin=this.sizeBegin;if(this.sizeChanges){particle.sizeEnd=this.sizeEnd}else{particle.sizeEnd=this.sizeBegin}particle.sizeTime=this.sizeTime;particle.colorTime=this.colorTime;particle.initialized=true},generateParticles:function(){var particles=this.particles;for(var i=0,iend=this.particleCount;i&lt;iend;i++){var particle=particles[i];particle.startTime=Math.random()*this.lifeStart;particle.initialized=false}},refreshParticles:function(time){var particles=this.particles;for(var i=0,iend=this.particleCount;i&lt;iend;i++){var particle=particles[i];if(time&gt;particle.startTime+particle.lifeTime){particle.startTime=time;this.randomizeParticle(particle)}}if(this.stopSpawning){this.spawnParticles=false;this.stopSpawning=false}},updateDynamicValues:function(){var attributesWithExpressions=this.attributesWithExpressions;if(attributesWithExpressions){for(var i=0,iend=attributesWithExpressions.length;i&lt;iend;i++){attributesWithExpressions[i].getValue()}}this.particleAngleRad=this.particleAngleDeg*-gsMath.DEG2RAD;this.particleAngularVelocityRad=this.particleAngularVelocityDeg*-gsMath.DEG2RAD;this.emitterX=this.originX+this.offsetX;this.emitterY=this.originY+this.offsetY},renderAtTime:function(renderer,time,draw){var image=this.imageHandle;if(!image&amp;&amp;this.imageID){var resource=gs.AssetManager.current.imageForName(this.imageID);image=renderer.handleManager.getImageHandle(resource);this.imageHandle=image}if(image&amp;&amp;!image.ready){image.checkReady()}draw=draw&amp;&amp;(!image||image.ready);var colorChanges=this.colorChanges;var onlyAlphaChanges=this.onlyAlphaChanges;var colorBegin=this.colorBegin;var colorEnd=this.colorEnd;var constantColor=colorChanges?null:this.colorEnd;var particleColor=colorChanges?this.particleColor:null;if(particleColor&amp;&amp;onlyAlphaChanges){particleColor[0]=colorEnd[0];particleColor[1]=colorEnd[1];particleColor[2]=colorEnd[2]}var gravityX=this.gravityX;var gravityY=this.gravityY;if(draw){renderer.beginParticles(image,this.blendMode,constantColor)}var aliveCount=0;var particles=this.particles;for(var i=0,iend=this.particleCount;i&lt;iend;i++){var particle=particles[i];var particleAge=time-particle.startTime;if(0&lt;particleAge&amp;&amp;particleAge&lt;particle.lifeTime){aliveCount++;if(!particle.initialized){this.randomizeParticle(particle)}var dx=particle.initialDX+gravityX*particleAge*.5;var dy=particle.initialDY+gravityY*particleAge*.5;var x=particle.initialX+dx*particleAge;var y=particle.initialY+dy*particleAge;var angleRad=particle.initialAngleRad+particleAge*particle.angularVelocityRad;var size;if(particleAge&lt;particle.sizeTime){var sizeFraction=particleAge/particle.sizeTime;size=particle.sizeBegin+(particle.sizeEnd-particle.sizeBegin)*sizeFraction}else{size=particle.sizeEnd}if(colorChanges){if(particleAge&lt;particle.colorTime){var colorFraction=particleAge/particle.colorTime;if(!onlyAlphaChanges){particleColor[0]=colorBegin[0]+(colorEnd[0]-colorBegin[0])*colorFraction;particleColor[1]=colorBegin[1]+(colorEnd[1]-colorBegin[1])*colorFraction;particleColor[2]=colorBegin[2]+(colorEnd[2]-colorBegin[2])*colorFraction}particleColor[3]=colorBegin[3]+(colorEnd[3]-colorBegin[3])*colorFraction}else{if(!onlyAlphaChanges){particleColor[0]=colorEnd[0];particleColor[1]=colorEnd[1];particleColor[2]=colorEnd[2]}particleColor[3]=colorEnd[3]}}if(draw){renderer.drawParticle(x,y,angleRad,size,particleColor)}}}if(draw){renderer.endParticles()}gs.Game.profiler.entityCounter.particles.add(aliveCount)},compute:function(renderer,draw){this.dirty=false;if(!gs.debug.particles){return}var dirtyOrigin=this.dirtyOrigin;if(dirtyOrigin){this.originAngleRad=this.originAngleDeg*gsMath.DEG2RAD;this.dirtyOrigin=false}var dirtyOffset=this.dirtyOffset;if(dirtyOffset){this.offsetAngleRad=this.offsetAngleDeg*gsMath.DEG2RAD;this.dirtyOffset=false}if(this.dirtySettings){this.particleAngleRad=this.particleAngleDeg*-gsMath.DEG2RAD;this.dirtySettings=false}if(dirtyOffset||dirtyOrigin){this.emitterX=this.originX+this.offsetX;this.emitterY=this.originY+this.offsetY;this.emitterAngleRad=this.originAngleRad+this.offsetAngleRad}if(this.spawnParticles){this.refreshParticles(this.time)}this.renderAtTime(renderer,this.time,draw)}});var DEFAULT_LISTENER_Z_VALUE=-50;gs.SGSoundListenerNode=function(){gs.SGNode.call(this);this._x=gs.SGPort.addInputPort(this);this._y=gs.SGPort.addInputPort(this);this._x.setValue(240);this._y.setValue(160);var audioCtx=gs.AudioManager.current.context;if(audioCtx){var listener=audioCtx.listener;if(listener){this.listener=listener;var x=this._x.getValue();var y=this._y.getValue();if(listener.positionX){listener.positionX.value=x;listener.positionY.value=y;listener.positionZ.value=DEFAULT_LISTENER_Z_VALUE}else{listener.setPosition(x,y,DEFAULT_LISTENER_Z_VALUE)}}}};gs.Pool.init(gs.SGSoundListenerNode);gs.SGSoundListenerNode.prototype=gs.subclass(gs.SGNode,{compute:function(){if(this.listener){var listener=this.listener;var x=this._x.getValue();var y=this._y.getValue();if(listener.positionX){listener.positionX.value=x;listener.positionY.value=y}else{listener.setPosition(x,y,DEFAULT_LISTENER_Z_VALUE)}}}});gs.SGCanvasColor=function(r,g,b,a){this.isColorHandle=true;this.ready=true;this.color=gs.array.provide();this.color[0]=r;this.color[1]=g;this.color[2]=b;this.color[3]=a};gs.SGCanvasColor.prototype={update:function(color,angleDegrees,blendingMode){this.color[0]=color[0];this.color[1]=color[1];this.color[2]=color[2];this.color[3]=color[3];this.blendingMode=blendingMode},release:function(){}};gs.SGCanvasString=function(){this.isStringHandle=true;this.lineHeightFactor=1.35;this.text=null;this.color=null;this.angleRadians=0;this.sizePx=0;this.lineHeight=0;this.fontFamily=null;this.alignment=gs.SGTextAlignment.Center;this.wrap=false;this.textLines=gs.array.provide();this.wrapWidth=0};gs.SGCanvasString.prototype={isReady:function(){return true},update:function(text,color,fontFamily,sizePx,alignment,wrap){if(text!==this.text){this.clearTextLines()}this.text=text;this.color=color;this.sizePx=sizePx;this.lineHeight=sizePx*this.lineHeightFactor;this.fontFamily=fontFamily;this.alignment=alignment;this.wrap=wrap},clearTextLines:function(){this.textLines.length=0},appendTextLine:function(line){this.textLines.push(line)}};gs.SGCanvasImage=function(imageTintCache){this.isImageHandle=true;this.isCanvas=true;this.imageTintCache=imageTintCache;this.ready=false;this.color=gs.array.provide();this.color[0]=1;this.color[1]=1;this.color[2]=1;this.color[3]=1;this.colorEpsilon=1/64};gs.SGCanvasImage.prototype={reset:function(){this.resource=null;this.ready=false;this.color[0]=1;this.color[1]=1;this.color[2]=1;this.color[3]=1},release:function(){},setResource:function(resource){this.resource=resource;this.ready=false;this.checkReady()},checkReady:function(){if(!this.ready&amp;&amp;this.resource&amp;&amp;this.resource.ready){this.initFromResource()}},initFromResource:function(){var resource=this.resource;this.width=resource.width;this.height=resource.height;this.color[0]=1;this.color[1]=1;this.color[2]=1;this.color[3]=1;this.currentImage=resource.imageElement;this.originalImage=resource.imageElement;this.imageWidth=resource.width;this.imageHeight=resource.height;this.assetWidth=resource.width;this.assetHeight=resource.height;this.tileWidth=resource.width;this.tileHeight=resource.height;this.ready=true},update:function(sprite){this.checkReady();if(!this.ready){return}var imageWasResized=false;var imageColorChanged=false;var imageIsNotAssetSize=false;var tileWidth=sprite.tileWidth||this.assetWidth;var tileHeight=sprite.tileHeight||this.assetHeight;if(this.width!==sprite.width){this.width=sprite.width;imageWasResized=true}if(this.height!==sprite.height){this.height=sprite.height;imageWasResized=true}if(this.tileWidth!==tileWidth){this.tileWidth=tileWidth;imageWasResized=true}if(this.tileHeight!==tileHeight){this.tileHeight=tileHeight;imageWasResized=true}var colorEpsilon=this.colorEpsilon;var color=sprite.color;if(Math.abs(color[0]-this.color[0])&gt;colorEpsilon||Math.abs(color[1]-this.color[1])&gt;colorEpsilon||Math.abs(color[2]-this.color[2])&gt;colorEpsilon){this.color[0]=color[0];this.color[1]=color[1];this.color[2]=color[2];imageColorChanged=true}this.color[3]=color[3];this.flipY=sprite.flipY;this.flipX=sprite.flipX;var baseImage=this.originalImage;var currentImage=this.currentImage;if(imageColorChanged){baseImage=this.imageTintCache.getTintedImage(this.originalImage,this.color[0],this.color[1],this.color[2]);currentImage=baseImage;if(sprite.width!==this.assetWidth||sprite.height!==this.assetHeight){imageIsNotAssetSize=true}}if(imageWasResized||imageColorChanged&amp;&amp;imageIsNotAssetSize){if((sprite.wrapModeS!==gs.SGWrapMode.SGWrapScale||sprite.wrapModeT!==gs.SGWrapMode.SGWrapScale)&amp;&amp;(sprite.width&gt;0||sprite.height&gt;0)){var wrapWidth=Math.ceil(sprite.width);var wrapHeight=Math.ceil(sprite.height);baseImage=this.imageTintCache.getTintedImage(this.originalImage,this.color[0],this.color[1],this.color[2]);currentImage=this.createFinalImage(baseImage,wrapWidth,wrapHeight,sprite.wrapModeS,sprite.wrapModeT,sprite.anchorS,sprite.anchorT,this.tileWidth,this.tileHeight);this.imageWidth=currentImage.width;this.imageHeight=currentImage.height}else{this.imageWidth=this.assetWidth;this.imageHeight=this.assetHeight}}this.currentImage=currentImage;this.ready=true},createFinalImage:function(image,width,height,wrapS,wrapT,anchorS,anchorT,tileWidth,tileHeight){if(wrapS===gs.SGWrapMode.SGWrapScale&amp;&amp;wrapT===gs.SGWrapMode.SGWrapScale){return image}var anchorHorizontal=anchorS===0?"left":anchorS===1?"center":"right";var anchorVertical=anchorT===0?"bottom":anchorT===1?"center":"top";if(wrapS===gs.SGWrapMode.SGWrapTile&amp;&amp;wrapT===gs.SGWrapMode.SGWrapTile){image=gs.html5.Canvas.createTiledImage(image,width,height,tileWidth,tileHeight);if(image.width!==width||image.height!==height){image=gs.html5.Canvas.createCroppedImage(image,width,height,anchorHorizontal,anchorVertical)}}else if(wrapS===gs.SGWrapMode.SGWrapTile&amp;&amp;wrapT===gs.SGWrapMode.SGWrapScale){image=gs.html5.Canvas.createTiledImageHorizontal(image,width,tileWidth);if(image.width!==width){image=gs.html5.Canvas.createCroppedImage(image,width,image.height,anchorHorizontal,anchorVertical)}}else if(wrapS===gs.SGWrapMode.SGWrapScale&amp;&amp;wrapT===gs.SGWrapMode.SGWrapTile){image=gs.html5.Canvas.createTiledImageVertical(image,height,tileHeight);if(image.height!==height){image=gs.html5.Canvas.createCroppedImage(image,image.width,height,anchorHorizontal,anchorVertical)}}else if(wrapS===gs.SGWrapMode.SGWrapTile&amp;&amp;wrapT===gs.SGWrapMode.SGWrapFixed){if(image.height&gt;height){image=gs.html5.Canvas.createTiledImageHorizontal(image,width,tileWidth);image=gs.html5.Canvas.createCroppedImage(image,width,height,anchorHorizontal,anchorVertical)}else{image=gs.html5.Canvas.createTiledImageHorizontal(image,width,tileWidth);if(image.width&gt;width){image=gs.html5.Canvas.createCroppedImage(image,width,image.height,anchorHorizontal,anchorVertical)}image=gs.html5.Canvas.createPaddedImage(image,width,height)}}else if(wrapS===gs.SGWrapMode.SGWrapFixed&amp;&amp;wrapT===gs.SGWrapMode.SGWrapTile){if(image.width&gt;width){image=gs.html5.Canvas.createTiledImageVertical(image,height,tileHeight);image=gs.html5.Canvas.createCroppedImage(image,width,height,anchorHorizontal,anchorVertical)}else{image=gs.html5.Canvas.createTiledImageVertical(image,height,tileHeight);if(image.height&gt;height){image=gs.html5.Canvas.createCroppedImage(image,image.width,height,anchorHorizontal,anchorVertical)}image=gs.html5.Canvas.createPaddedImage(image,width,height)}}if(wrapS===gs.SGWrapMode.SGWrapFixed&amp;&amp;wrapT===gs.SGWrapMode.SGWrapFixed){if(image.width&gt;width&amp;&amp;image.height&gt;height){image=gs.html5.Canvas.createCroppedImage(image,width,height,anchorHorizontal,anchorVertical)}else if(image.width&gt;width){image=gs.html5.Canvas.createCroppedImage(image,width,image.height,anchorHorizontal,anchorVertical);image=gs.html5.Canvas.createPaddedImage(image,width,height)}else if(image.height&gt;height){image=gs.html5.Canvas.createCroppedImage(image,image.width,height,anchorHorizontal,anchorVertical);image=gs.html5.Canvas.createPaddedImage(image,width,height)}else{image=gs.html5.Canvas.createPaddedImage(image,width,height)}}else if(wrapS===gs.SGWrapMode.SGWrapFixed&amp;&amp;wrapT===gs.SGWrapMode.SGWrapScale){if(image.width&gt;width){image=gs.html5.Canvas.createCroppedImage(image,width,image.height,anchorHorizontal,anchorVertical)}else{image=gs.html5.Canvas.createPaddedImage(image,width,image.height,anchorHorizontal,anchorVertical)}}else if(wrapS===gs.SGWrapMode.SGWrapScale&amp;&amp;wrapT===gs.SGWrapMode.SGWrapFixed){if(image.height&gt;height){image=gs.html5.Canvas.createCroppedImage(image,image.width,height,anchorHorizontal,anchorVertical)}else{image=gs.html5.Canvas.createPaddedImage(image,image.width,height,anchorHorizontal,anchorVertical)}}return image}};gs.SGCanvasHandleManager=function(){this.imageTintCache=new gs.SGCanvasImageTintCache};gs.SGCanvasHandleManager.prototype={reset:function(){},releaseHandle:function(aHandle){},getImageHandle:function(resource){var handle=new gs.SGCanvasImage(this.imageTintCache);handle.reset();handle.setResource(resource);return handle},getColorHandle:function(r,g,b,a){return new gs.SGCanvasColor(r,g,b,a)},getStringHandle:function(){return new gs.SGCanvasString}};gs.SGCanvasImageTintCache=function(){this.imageResourceMap={};this.rCompromise=0;this.gCompromise=0;this.bCompromise=0;this.compromiseFactor=8};gs.SGCanvasImageTintCache.prototype.getTintedImage=function(image,r,g,b){var needTint=this.compromiseColor(r,g,b);if(!needTint){return image}var imageKey=image.resource.id;var colorMap=this.imageResourceMap[imageKey];if(!colorMap){colorMap={};this.imageResourceMap[imageKey]=colorMap}var colorKey=this.formatColorKey(this.rCompromise,this.gCompromise,this.bCompromise);var tintedImage=colorMap[colorKey];if(!tintedImage){tintedImage=gs.html5.Canvas.createTintedImage(image,r,g,b);colorMap[colorKey]=tintedImage}return tintedImage};gs.SGCanvasImageTintCache.prototype.formatColorKey=function(r,g,b){return(r*255|0).toString(16)+","+(g*255|0).toString(16)+","+(b*255|0).toString(16)};gs.SGCanvasImageTintCache.prototype.compromiseColor=function(r,g,b){var compromiseFactor=this.compromiseFactor;if(r===1&amp;&amp;g===1&amp;&amp;b===1){return false}this.rCompromise=Math.round(r*compromiseFactor)/compromiseFactor;this.gCompromise=Math.round(g*compromiseFactor)/compromiseFactor;this.bCompromise=Math.round(b*compromiseFactor)/compromiseFactor;return true};gs.SGCanvasRenderer=function(displayAnchor){this.canvas=displayAnchor.canvas;this.context=this.canvas.getContext("2d");this.handleManager=new gs.SGCanvasHandleManager;this.fontPicker=new gs.html5.text.FontPicker;this.canvasWidth=this.canvas.width;this.canvasHeight=this.canvas.height;this.currentFont=null;this.particleImage=null;this.particleInverseTextureWidth=null;this.particleInverseTextureHeight=null;this.particleBlendMode=null};gs.SGCanvasRenderer.CompositeOperation={SOURCE_OVER:"source-over",LIGHTER:"lighter"};gs.SGCanvasRenderer.prototype={getRoot:function(){return this.canvas},getHandleManager:function(){return this.handleManager},setFillColorRGBA:function(r,g,b,a){this.context.fillStyle="rgba("+r*100+"%,"+g*100+"%,"+b*100+"%,"+a+")"},setFillColorArray:function(color){var s="rgba(";s+=color[0]*100;s+="%,";s+=color[1]*100;s+="%,";s+=color[2]*100;s+="%,";s+=color[3];s+=")";this.context.fillStyle=s},setGlobalAlpha:function(alpha){if(alpha!==1){this.context.globalAlpha=alpha}},resetGlobalAlpha:function(){this.context.globalAlpha=1},setFont:function(family,sizePx){this.currentFont=this.fontPicker.pickBestFont(family,sizePx);this.context.font=this.currentFont.toCSS()},clear:function(r,g,b){this.setFillColorRGBA(r,g,b,1);this.context.fillRect(0,0,this.canvasWidth,this.canvasHeight)},beginScene:function(){this.canvasWidth=this.canvas.width;this.canvasHeight=this.canvas.height;this.resetGlobalAlpha()},endScene:function(){},updateSize:function(){},beginSpace:function(x,y,width,height,viewRotation,modelRotation){var context=this.context;var left=x;var right=x+width;var bottom=y;var top=y+height;var canvasWidth=this.canvasWidth;var canvasHeight=this.canvasHeight;context.save();if(width===0){width=1e-6}if(height===0){height=1e-6}var a=canvasWidth/width;var b=0;var c=0;var d=canvasHeight/height;var e=a*-x;var f=d*y+(canvasHeight-canvasHeight*(canvasHeight/height));context.transform(a,b,c,d,e,f);var dx=(right+left)*.5;var dy=(top+bottom)*.5;context.translate(dx,canvasHeight-dy);context.rotate(-modelRotation*gsMath.DEG2RAD);context.translate(-dx,-(canvasHeight-dy))},endSpace:function(){this.context.restore()},pushMatrix:function(){this.context.save()},popMatrix:function(){this.context.restore()},transformPolar:function(angleDegrees,spacing){var angleRadians=-angleDegrees*gsMath.DEG2RAD;var dx=Math.cos(angleRadians)*spacing;var dy=Math.sin(angleRadians)*spacing;this.context.translate(dx,dy)},drawImage:function(sprite,imageHandle){var context=this.context;var x=sprite.x;var y=this.canvasHeight-sprite.y;var width=sprite.width;var height=sprite.height;var angle=sprite.angleRad;var flip=sprite.flipX||sprite.flipY;var onlyTranslate=angle===0&amp;&amp;!flip;if(onlyTranslate){context.translate(x,y)}else{context.save();context.translate(x,y);context.rotate(angle);if(flip){context.scale(sprite.flipY?-1:1,sprite.flipX?-1:1)}}var alpha=sprite.colorA;var compositeOperationChanged=false;var gs_SGBlendingMode=gs.SGBlendingMode;switch(sprite.blendMode){case gs_SGBlendingMode.Normal:if(alpha&lt;1){context.globalAlpha=alpha}break;case gs_SGBlendingMode.Multiply:context.globalAlpha=alpha;break;case gs_SGBlendingMode.Opaque:context.globalAlpha=1;break;case gs_SGBlendingMode.Additive:context.globalAlpha=alpha;context.globalCompositeOperation=gs.SGCanvasRenderer.CompositeOperation.LIGHTER;compositeOperationChanged=true;break;case gs_SGBlendingMode.Screen:context.globalAlpha=alpha;context.globalCompositeOperation=gs.SGCanvasRenderer.CompositeOperation.LIGHTER;compositeOperationChanged=true;break}if(imageHandle.currentImage&amp;&amp;imageHandle.imageWidth&gt;0&amp;&amp;imageHandle.imageHeight&gt;0){context.drawImage(imageHandle.currentImage,0,0,imageHandle.imageWidth,imageHandle.imageHeight,-.5*width,-.5*height,width,height)}if(onlyTranslate){context.translate(-x,-y);if(alpha&lt;1){context.globalAlpha=1}if(compositeOperationChanged){context.globalCompositeOperation=gs.SGCanvasRenderer.CompositeOperation.SOURCE_OVER}}else{context.restore()}},drawImageWithWrap:function(sprite,imageHandle){this.drawImage(sprite,imageHandle)},drawRect:function(sprite){var context=this.context;var x=sprite.x;var y=sprite.y;var width=sprite.width;var height=sprite.height;var angle=sprite.angleRad;var blendingMode=sprite.blendMode;var color=sprite.color;var alpha=color[3];if(alpha===0){return}if(width===0||height===0){return}if(blendingMode===gs.SGBlendingMode.Multiply){return}context.save();context.translate(x,this.canvasHeight-y);context.rotate(angle);var h=width*.5;var v=height*.5;context.translate(-h,-v);this.setFillColorArray(color);switch(blendingMode){case gs.SGBlendingMode.Normal:this.setGlobalAlpha(alpha);break;case gs.SGBlendingMode.Opaque:this.setGlobalAlpha(1);break;case gs.SGBlendingMode.Additive:this.setGlobalAlpha(alpha);context.globalCompositeOperation="lighter";break;default:this.setGlobalAlpha(alpha);break}context.fillRect(0,0,width,height);context.restore()},drawText:function(textNode,text){var context=this.context;var x=textNode.x;var y=textNode.y;var sizePx=textNode.sizePx;var fontFamily=textNode.fontFamily;var textToDraw=text;var color=textNode.color;var alignment=textNode.alignment;var angle=textNode.angleRad;var wrap=textNode.wrap;var lineHeight=textNode.lineHeight;var padding=wrap?1+.1*sizePx:0;var width=Math.ceil(textNode.width-2*padding);var height=Math.ceil(textNode.height-2*padding);this.setFont(fontFamily,sizePx);var textLines=textNode.textLines;var lineCount=textLines?textLines.length:0;if(lineCount===0){if(!wrap&amp;&amp;textToDraw.indexOf("\n")===-1){textLines=[textToDraw];textNode.wrapWidth=0;lineCount=1}else{this.formatTextLines(textNode,textToDraw,width);textLines=textNode.textLines;lineCount=textLines.length;if(wrap){textNode.wrapWidth=width}else{width=textNode.wrapWidth}}}if(textNode.wrapWidth){width=textNode.wrapWidth}context.save();{if(color){this.setFillColorArray(color)}var textTopOffset=0;context.textBaseline="middle";if(wrap){textTopOffset=-((height-lineCount*lineHeight)/2);context.textBaseline="top"}else if(lineCount&gt;1){textTopOffset=-.5*lineCount*lineHeight;context.textBaseline="top"}var h=width*.5;if(alignment===0){context.textAlign="left"}else if(alignment===1){h=0;context.textAlign="center"}else if(alignment===2){h=-h;context.textAlign="right"}var v=0;if(wrap){v=lineHeight*lineCount*.5}var linesToDraw=lineCount;if(wrap&amp;&amp;linesToDraw&gt;1){linesToDraw=Math.min(linesToDraw,Math.floor(height/lineHeight))}for(var i=0;i&lt;linesToDraw;++i){context.save();{var dy=textTopOffset+i*lineHeight;if(angle===0){context.translate(x,this.canvasHeight-y+dy)}else{context.translate(x+Math.cos(Math.PI/2+angle)*dy,this.canvasHeight-(y-Math.sin(Math.PI/2+angle)*dy));context.rotate(angle)}var line=textLines[i];context.fillText(line,Math.round(-h),Math.round(-v))}context.restore()}}context.restore()},formatTextLines:function(textNode,text,width){var context=this.context;var textFragments=text.split(/\n/);var wrap=textNode.wrap;var maxWidth=0;for(var i=0;i&lt;textFragments.length;++i){var textFragment=textFragments[i];var fragmentWidth=context.measureText(textFragment).width;if(fragmentWidth&gt;maxWidth){maxWidth=fragmentWidth}var newSubString=textFragment;var remainderString="";var lastSpaceIndex=-1;if(wrap){while(fragmentWidth&gt;width){lastSpaceIndex=newSubString.lastIndexOf(" ");if(lastSpaceIndex===-1){break}remainderString=newSubString.substring(lastSpaceIndex)+remainderString;newSubString=newSubString.substring(0,lastSpaceIndex);fragmentWidth=context.measureText(newSubString).width}if(lastSpaceIndex!==-1){remainderString=remainderString.trim();newSubString=newSubString.trim();textFragments.splice(i,1,newSubString,remainderString)}}}textNode.wrapWidth=maxWidth;textNode.textLines=textFragments},beginParticles:function(particleImageHandle,blendMode,color){var context=this.context;this.particleImage=particleImageHandle;this.particleBlendMode=blendMode;if(color){var alpha=color[3];this.setFillColorArray(color);switch(blendMode){case gs.SGBlendingMode.Normal:context.globalAlpha=alpha;break;case gs.SGBlendingMode.Opaque:context.globalAlpha=1;break;case gs.SGBlendingMode.Additive:context.globalAlpha=alpha;context.globalCompositeOperation="lighter";break;default:context.globalAlpha=alpha;break}}else{if(blendMode===gs.SGBlendingMode.Additive){context.globalCompositeOperation="lighter"}}},drawParticle:function(x,y,angleRad,size,color){var context=this.context;if(color){if(this.particleBlendMode!==gs.SGBlendingMode.Opaque){context.globalAlpha=color[3]}}context.translate(x,this.canvasHeight-y);if(angleRad!==0){context.rotate(angleRad)}var particleImage=this.particleImage;if(particleImage){context.drawImage(particleImage.currentImage,0,0,particleImage.imageWidth,particleImage.imageHeight,-.5*size,-.5*size,size,size)}else{if(color){this.setFillColorArray(color)}context.fillRect(-.5*size,-.5*size,size,size)}if(angleRad!==0){context.rotate(-angleRad)}context.translate(-x,y-this.canvasHeight)},endParticles:function(){var context=this.context;context.globalAlpha=1;context.globalCompositeOperation=gs.SGCanvasRenderer.CompositeOperation.SOURCE_OVER}};gs.webgl.shaders={tint:{vertex:"attribute vec3 aPosition;attribute vec2 aTextureUV;uniform mat4 uPMatrix;uniform mat4 uMVMatrix;varying vec2 vTextureUV;void main(void) {\tgl_Position = uPMatrix * uMVMatrix * vec4(aPosition, 1.0);\tvTextureUV = aTextureUV;}",fragment:"precision mediump float;uniform sampler2D uTexture;uniform vec4 uTint;varying vec2 vTextureUV;void main(void) {\tgl_FragColor = uTint * texture2D(uTexture, vTextureUV);}"},alpha:{vertex:"",fragment:""},white:{vertex:"",fragment:""},solid:{vertex:"",fragment:""},safe:{vertex:"attribute vec2 aPositionXY;attribute vec2 aTextureUV;uniform mat3 pMatrix;uniform mat3 mvMatrix;uniform vec2 uSizeXY;uniform vec4 uTextureSSTT;varying vec2 vTextureUV;void main(void) {\tgl_Position = vec4(pMatrix * mvMatrix * vec3(aPositionXY * uSizeXY, 1.0), 1.0);\tvTextureUV = aTextureUV * uTextureSSTT.yw + uTextureSSTT.xz;}",fragment:"precision lowp float;varying vec2 vTextureUV;uniform vec4 uTint;uniform sampler2D uTexture;void main(void) {\tgl_FragColor = uTint * texture2D(uTexture, vTextureUV);}"}};gs.SGWebGLColor=function(r,g,b,a){this.isColorHandle=true;this.ready=true;this.color=gs.array.provide();this.color[0]=r;this.color[1]=g;this.color[2]=b;this.color[3]=a;this.blendingMode=null};gs.SGWebGLColor.prototype={update:function(color,angleDegrees,blendingMode){this.color[0]=color[0];this.color[1]=color[1];this.color[2]=color[2];this.color[3]=color[3];this.blendingMode=blendingMode},release:function(){gs.array.recycle(this.color);this.color=null}};gs.SGWebGLImage=function(){this.isImageHandle=true;this.resource=null;this.ready=false;this.handleManager=null;this.tileWidth=0;this.tileHeight=0;this.isPowerOf2=false;this.waitingForPow2=false;this.texture=null;this.textureWidth=0;this.textureHeight=0;this.inverseTextureWidth=0;this.inverseTextureHeight=0;this.previousTextureU=1;this.previousTextureV=1};gs.Pool.init(gs.SGWebGLImage);gs.SGWebGLImage.prototype={setResource:function(resource){this.resource=resource;this.ready=false;this.checkReady()},checkReady:function(){if(!this.ready&amp;&amp;this.resource&amp;&amp;this.resource.ready){this.initFromResource()}},initFromResource:function(){var width=this.resource.width;var height=this.resource.height;this.textureWidth=width;this.textureHeight=height;this.inverseTextureWidth=1/width;this.inverseTextureHeight=1/height;if(this.waitingForPow2){this.waitingForPow2=false}else{this.originalWidth=width;this.originalHeight=height}this.texture=this.resource.texture;this.ready=true;var testWidth=width;var testHeight=height;while(testWidth&gt;1){testWidth/=2}while(testHeight&gt;1){testHeight/=2}this.isPowerOf2=testWidth===1&amp;&amp;testHeight===1},upsizeToPowerOf2Image:function(){this.ready=false;this.waitingForPow2=true;var id=this.resource.id;var resource=gs.AssetManager.current.imageForNamePow2(id);this.setResource(resource)},update:function(sprite){this.checkReady();this.tileWidth=sprite.tileWidth||this.originalWidth;this.tileHeight=sprite.tileHeight||this.originalHeight;if(this.ready&amp;&amp;!this.isPowerOf2&amp;&amp;(sprite.wrapModeS===2||sprite.wrapModeT===2)){this.upsizeToPowerOf2Image()}},release:function(){this.handleManager.releaseHandle(this)}};gs.SGWebGLString=function(){this.isStringHandle=true;this.ready=true;this.lineHeightFactor=1.35};gs.SGWebGLString.prototype={update:function(text,color,fontFamily,sizePx,alignment,wrap){this.text=text;this.color=color;this.fontFamily=fontFamily;this.sizePx=sizePx;this.alignment=alignment;this.wrap=wrap;this.lineHeight=sizePx*this.lineHeightFactor}};gs.SGWebGLHandleManager=function(){};gs.SGWebGLHandleManager.prototype={reset:function(){},getImageHandle:function(resource){var handle=gs.SGWebGLImage.provide();handle.handleManager=this;handle.setResource(resource);return handle},getColorHandle:function(r,g,b,a){return new gs.SGWebGLColor(r,g,b,a)},getStringHandle:function(){return new gs.SGWebGLString},releaseHandle:function(handle){if(handle instanceof gs.SGWebGLImage){handle.resource=null;handle.ready=false;gs.SGWebGLImage.recycle(handle)}}};gs.SGWebGLRenderer=function(viewportTuple){this.useFloat32Matrices=false;this.gl=null;this.maxTextureSize=0;this.canvas=viewportTuple.webgl;this.canvasWidth=this.canvas.width;this.canvasHeight=this.canvas.height;this.frameCount=0;this.mvMatrix=null;this.onlyTranslate=null;this.mvMatrixStack=gs.array.provide();this.onlyTranslateStack=gs.array.provide();this.stackTop=-1;this.stackSize=0;this.p4Matrix=this.createMatrix();this.p3Matrix=this.createMatrix();this.f32mvMatrix=new Float32Array([1,0,0,0,1,0,0,0,1]);this.tempMultiplyMatrix=this.createMatrix();this.shaderProgram=null;this.tintColor=new Float32Array([-1,-1,-1,-1]);this.previous={bestCase:false,clearColor:new Float32Array([-1,-1,-1,-1]),tintColor:new Float32Array([-1,-1,-1,-1]),blendMode:null,texture:null,sizeXY:new Float32Array([-1,-1]),textureSSTT:new Float32Array([-1,-1,-1,-1]),isDefaultTextureSSTT:false};this.particleInverseTextureWidth=null;this.particleInverseTextureHeight=null;this.particleBlendMode=null;this.fontSprite=null;this.fontInverseTextureWidth=null;this.fontInverseTextureHeight=null;this.defaultVertexBuffer=null;this.defaultTextureCoordinateBuffer=null;this.defaultTextureSSTT=new Float32Array([0,1,0,1]);this.tempTextureCoordinateArray=new Float32Array(8);this.tintWhite=new Float32Array([1,1,1,1]);this.tintBlack=new Float32Array([0,0,0,1]);this.handleManager=new gs.SGWebGLHandleManager(this);this.fontPicker=new gs.html5.text.FontPicker;this.fontCache=gs.array.provide();this.initMatrixStack();this.init();gs.AssetManager.current.setRenderer(this);this.whiteImage=this.getHandleManager().getImageHandle(gs.AssetManager.current.white1x1)};gs.SGWebGLRenderer.prototype={transformPolar:function(angleDegrees,spacing){var tx=0;var ty=0;switch(angleDegrees){case 0:tx=spacing;break;case-90:ty=spacing;break;default:var angleRadians=angleDegrees*-gsMath.DEG2RAD;tx=Math.cos(angleRadians)*spacing;ty=Math.sin(angleRadians)*spacing;if(Math.abs(tx)&lt;1e-6){tx=0}if(Math.abs(ty)&lt;1e-6){ty=0}break}this.translate(tx,ty)},beginScene:function(){this.whiteImage.checkReady();this.frameCount++;this.previous.texture=null;this.previous.bestCase=false;this.setBlendMode(0)},endScene:function(){if(gs.debug.renderFlush){this.gl.finish()}},beginSpace:function(x,y,width,height,viewRotation,modelRotation){var left=x;var right=x+width;var bottom=y;var top=y+height;var canvasHeight=this.canvasHeight;var canvasWidth=this.canvasWidth;this.pushMatrix();if(width===0){width=1e-6}if(height===0){height=1e-6}var a=canvasWidth/width;var b=0;var c=0;var d=canvasHeight/height;var e=a*-x;var f=d*y+(canvasHeight-canvasHeight*(canvasHeight/height));this.setMatrix(a,b,c,d,e,f);var dx=(right+left)*.5;var dy=(top+bottom)*.5;this.translate(dx,canvasHeight-dy);this.rotate(modelRotation*-gsMath.DEG2RAD);this.translate(-dx,-(canvasHeight-dy))},endSpace:function(){this.popMatrix()},getRoot:function(){return this.canvas},getHandleManager:function(){return this.handleManager},clear:function(r,g,b){var gl=this.gl;var prev=this.previous.clearColor;if(r!==prev[0]||g!==prev[1]||b!==prev[2]){gl.clearColor(r,g,b,1);prev[0]=r;prev[1]=g;prev[2]=b}gl.clear(gl.COLOR_BUFFER_BIT)},init:function(){var gl=gs.webgl.getContext(this.canvas);this.gl=gl;if(!gl){gs.Log.fatal("Failed to initialize WebGL")}this.maxTextureSize=gl.getParameter(gl.MAX_TEXTURE_SIZE);gl.enable(this.gl.BLEND);var vertices=new Float32Array([.5,.5,-.5,.5,.5,-.5,-.5,-.5]);this.defaultVertexBuffer=this.createBuffer(vertices,2,4);this.defaultTextureCoordinateBuffer=this.createTextureCoordinateBuffer(1,1);this.initShaders();this.setViewport(this.canvas.width,this.canvas.height);this.loadIdentityMatrix()},setMaterial:function(color,blendMode){this.setTintArray(color,blendMode);if(blendMode!==this.previous.blendMode){var gl=this.gl;this.previous.blendMode=blendMode;switch(blendMode){case 0:gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);break;case 1:gl.blendFunc(gl.ONE,gl.ZERO);break;case 2:gl.blendFunc(gl.ONE,gl.ONE);break;case 3:gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_COLOR);break;case 4:gl.blendFunc(gl.ZERO,gl.SRC_COLOR);break}}},drawImageRelative:function(imageHandle,x,y){this.translate(x,y);this.setTexture(imageHandle.texture);this.setUniformTextureSSTTToDefault();this.setUniformSizeXY(imageHandle.textureWidth,imageHandle.textureHeight);this.setUniformMVMatrix();var gl=this.gl;gl.drawArrays(gl.TRIANGLE_STRIP,0,4);this.translate(-x,-y)},drawImage:function(sprite,imageHandle){var gl=this.gl;var previous=this.previous;var tx=sprite.x;var ty=this.canvasHeight-sprite.y;var angleRad=sprite.angleRad;var scaleX=sprite.width*imageHandle.inverseTextureWidth;var scaleY=sprite.height*imageHandle.inverseTextureHeight;if(sprite.flipY){scaleX*=-1}if(sprite.flipX){scaleY*=-1}var onlyTranslate=angleRad===0&amp;&amp;scaleX===1&amp;&amp;scaleY===1;if(onlyTranslate){this.translate(tx,ty)}else{this.pushMatrix();this.translate(tx,ty);this.rotate(angleRad);this.scale(scaleX,scaleY)}this.setMaterial(sprite.color,sprite.blendMode);this.setUniformTintFromMaterial();var textureChanged=this.setTexture(imageHandle.texture);if(textureChanged||!previous.bestCase){this.setUniformSizeXY(imageHandle.textureWidth,imageHandle.textureHeight)}if(!previous.bestCase){this.setUniformTextureSSTTToDefault()}this.setUniformMVMatrix();gl.drawArrays(gl.TRIANGLE_STRIP,0,4);this.previous.bestCase=true;if(onlyTranslate){this.translate(-tx,-ty)}else{this.popMatrix()}},drawImageWithWrap:function(sprite,imageHandle){var gl=this.gl;var width=sprite.width;var height=sprite.height;var textureWidth=imageHandle.textureWidth;var textureHeight=imageHandle.textureHeight;var originalWidth=imageHandle.originalWidth;var originalHeight=imageHandle.originalHeight;var wrapModeS=sprite.wrapModeS;var wrapModeT=sprite.wrapModeT;var anchorS=sprite.anchorS;var anchorT=sprite.anchorT;var scaleX=sprite.width*imageHandle.inverseTextureWidth;var scaleY=sprite.height*imageHandle.inverseTextureHeight;var beginS=0;var beginT=0;var endS=textureWidth;var endT=textureHeight;var glWrapModeS=gl.CLAMP_TO_EDGE;var glWrapModeT=gl.CLAMP_TO_EDGE;var uMax=1;var vMax=1;if(wrapModeS===2){glWrapModeS=gl.REPEAT;endS=width;uMax=textureWidth/imageHandle.tileWidth}else if(wrapModeS===1){if(originalWidth&lt;=width){scaleX=1}else{switch(anchorS){case gs.SGAnchorMode.SGAnchorMax:beginS=textureWidth*(1-width/originalWidth);endS=textureWidth;break;case gs.SGAnchorMode.SGAnchorCenter:beginS=(textureWidth-width)*.5;endS=(textureWidth+width)*.5;break;case gs.SGAnchorMode.SGAnchorMin:default:beginS=0;endS=width*(textureWidth/originalWidth);break}}}if(wrapModeT===2){glWrapModeT=gl.REPEAT;var m=height%textureHeight;beginT=-m;endT=height-m;vMax=textureHeight/imageHandle.tileHeight}else if(wrapModeT===1){if(textureHeight&lt;=height){scaleY=1}else{switch(anchorT){case gs.SGAnchorMode.SGAnchorMax:beginT=0;endT=height*(textureHeight/originalHeight);break;case gs.SGAnchorMode.SGAnchorCenter:beginT=(textureHeight-height)/2;endT=(textureHeight+height)/2;break;case gs.SGAnchorMode.SGAnchorMin:default:beginT=textureHeight*(1-height/originalHeight);endT=textureHeight;break}}}if(sprite.flipY){scaleX*=-1}if(sprite.flipX){scaleY*=-1}this.pushMatrix();this.translate(sprite.x,this.canvasHeight-sprite.y);this.rotate(sprite.angleRad);this.scale(scaleX,scaleY);if(uMax!==imageHandle.previousTextureU||vMax!==imageHandle.previousTextureV){imageHandle.previousTextureU=uMax;imageHandle.previousTextureV=vMax}var s=beginS*imageHandle.inverseTextureWidth;var ds=(endS-beginS)*imageHandle.inverseTextureWidth*imageHandle.previousTextureU;var t=1-endT*imageHandle.inverseTextureHeight;var dt=(endT-beginT)*imageHandle.inverseTextureHeight*imageHandle.previousTextureV;this.setMaterial(sprite.color,sprite.blendMode);this.setUniformTintFromMaterial();this.setTextureWithWrap(imageHandle.texture,glWrapModeS,glWrapModeT);this.setUniformTextureSSTT(s,ds,t,dt);this.setUniformSizeXY(imageHandle.textureWidth,imageHandle.textureHeight);this.setUniformMVMatrix();gl.drawArrays(gl.TRIANGLE_STRIP,0,4);this.popMatrix();this.previous.bestCase=false},setUniformTintFromMaterial:function(){var curr=this.tintColor;var prev=this.previous.tintColor;if(curr[3]!==prev[3]||curr[0]!==prev[0]||curr[1]!==prev[1]||curr[2]!==prev[2]){this.gl.uniform4fv(this.shaderProgram.tint,curr)}},setUniformPMatrix:function(matrix){this.Matrix_flatten3x3to9(matrix,this.f32mvMatrix);this.gl.uniformMatrix3fv(this.shaderProgram.pMatrix,false,this.f32mvMatrix)},setUniformMVMatrix:function(){this.Matrix_flatten3x3to9(this.mvMatrix,this.f32mvMatrix);this.gl.uniformMatrix3fv(this.shaderProgram.mvMatrix,false,this.f32mvMatrix)},setTextureWithWrap:function(texture,wrapS,wrapT){if(!texture){texture=this.whiteImage.texture}var previous=this.previous;if(texture!==previous.texture){var gl=this.gl;gl.bindTexture(gl.TEXTURE_2D,texture);previous.texture=texture;if(texture.previousWrapS!==wrapS){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,wrapS);texture.previousWrapS=wrapS}if(texture.previousWrapT!==wrapT){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,wrapT);texture.previousWrapT=wrapT}return true}return false},setTexture:function(texture){if(!texture){texture=this.whiteImage.texture}var previous=this.previous;if(texture!==previous.texture){var gl=this.gl;gl.bindTexture(gl.TEXTURE_2D,texture);previous.texture=texture;if(texture.previousWrapS!==gl.CLAMP_TO_EDGE){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);texture.previousWrapS=gl.CLAMP_TO_EDGE}if(texture.previousWrapT!==gl.CLAMP_TO_EDGE){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);texture.previousWrapT=gl.CLAMP_TO_EDGE}return true}return false},setFontSprite:function(fontImageHandle){var didChange=this.setTexture(fontImageHandle.texture);if(didChange){this.fontSprite=fontImageHandle;this.fontInverseTextureWidth=fontImageHandle.inverseTextureWidth;this.fontInverseTextureHeight=fontImageHandle.inverseTextureHeight}},setUniformTextureSSTT:function(s,ds,t,dt){var sstt=this.previous.textureSSTT;sstt[0]=s;sstt[1]=ds;sstt[2]=t;sstt[3]=dt;this.gl.uniform4fv(this.shaderProgram.textureSSTT,sstt);this.previous.isDefaultTextureSSTT=false},setUniformTextureSSTTToDefault:function(){if(!this.previous.isDefaultTextureSSTT){this.gl.uniform4fv(this.shaderProgram.textureSSTT,this.defaultTextureSSTT);this.previous.isDefaultTextureSSTT=true}},setUniformSizeXY:function(width,height){var prev=this.previous.sizeXY;if(width!==prev[0]||height!==prev[1]){prev[0]=width;prev[1]=height;this.gl.uniform2fv(this.shaderProgram.sizeXY,prev)}},beginParticles:function(particleImageHandle,blendMode,color){var gl=this.gl;if(!particleImageHandle){particleImageHandle=this.whiteImage}this.particleInverseTextureWidth=particleImageHandle.inverseTextureWidth;this.particleInverseTextureHeight=particleImageHandle.inverseTextureHeight;this.particleBlendMode=blendMode;if(color){this.setMaterial(color,blendMode);this.setUniformTintFromMaterial()}else{this.setBlendMode(blendMode)}this.setTexture(particleImageHandle.texture);this.setUniformSizeXY(particleImageHandle.textureWidth,particleImageHandle.textureHeight);this.setUniformTextureSSTTToDefault()},drawParticle:function(x,y,angleRadians,size,color){var gl=this.gl;var shaderProgram=this.shaderProgram;var f32mvMatrix=this.f32mvMatrix;var scaleX=size*this.particleInverseTextureWidth;var scaleY=size*this.particleInverseTextureHeight;if(color){this.setTintArray(color,this.particleBlendMode);gl.uniform4fv(shaderProgram.tint,this.tintColor)}var tx=x;var ty=this.canvasHeight-y;this.pushMatrix();if(this.onlyTranslate){var mvMatrix=this.mvMatrix;mvMatrix[0][2]+=tx;mvMatrix[1][2]+=ty;mvMatrix[0][0]*=scaleX;mvMatrix[1][1]*=scaleY;this.rotate(angleRadians)}else{this.translate(tx,ty);this.rotate(angleRadians);this.scale(scaleX,scaleY)}this.Matrix_flatten3x3to9(this.mvMatrix,f32mvMatrix);gl.uniformMatrix3fv(shaderProgram.mvMatrix,false,f32mvMatrix);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);this.popMatrix()},endParticles:function(){this.previous.bestCase=true},beginGlyphs:function(fontImageHandle,color){this.setFontSprite(fontImageHandle);this.setMaterial(color,0);this.setUniformTintFromMaterial()},drawGlyph:function(fontImageHandle,offsetX,offsetY,offsetWidth,offsetHeight){var gl=this.gl;this.setFontSprite(fontImageHandle);var s=offsetX*this.fontInverseTextureWidth;var ds=offsetWidth*this.fontInverseTextureWidth;var t=offsetY*this.fontInverseTextureHeight;var dt=offsetHeight*this.fontInverseTextureHeight;this.setUniformTextureSSTT(s,ds,t,dt);this.setUniformSizeXY(offsetWidth,offsetHeight);this.setUniformMVMatrix();gl.drawArrays(gl.TRIANGLE_STRIP,0,4)},drawGlyphTexture:function(imageHandle){var gl=this.gl;this.setTexture(imageHandle.texture);this.setUniformTextureSSTTToDefault();this.setUniformSizeXY(imageHandle.textureWidth,imageHandle.textureHeight);this.setUniformMVMatrix();gl.drawArrays(gl.TRIANGLE_STRIP,0,4);this.setTexture(this.fontSprite.texture)},endGlyphs:function(){this.previous.bestCase=false},drawRect:function(sprite){var gl=this.gl;var imageHandle=this.whiteImage;var tx=sprite.x;var ty=this.canvasHeight-sprite.y;var angleRad=sprite.angleRad;var onlyTranslate=angleRad===0;if(onlyTranslate){this.translate(tx,ty)}else{this.pushMatrix();this.translate(tx,ty);this.rotate(angleRad)}this.setMaterial(sprite.color,sprite.blendMode);this.setUniformTintFromMaterial();this.setTexture(imageHandle.texture);this.setUniformTextureSSTTToDefault();this.setUniformSizeXY(sprite.width,sprite.height);this.setUniformMVMatrix();if(onlyTranslate){this.translate(-tx,-ty)}else{this.popMatrix()}gl.drawArrays(gl.TRIANGLE_STRIP,0,4);this.previous.bestCase=true},getFontRenderer:function(fontFamily,sizePx){var fontCSS=sizePx+"px "+fontFamily;if(fontCSS in this.fontCache){return this.fontCache[fontCSS]}var fontRenderer=new gs.FontRenderer(this,fontFamily,sizePx);this.fontCache[fontCSS]=fontRenderer;return fontRenderer},drawText:function(textNode,text){var fontRenderer=this.getFontRenderer(textNode.fontFamily,textNode.sizePx);if(!fontRenderer.checkReady()){return null}this.beginGlyphs(fontRenderer.sheets[0],textNode.color);var lines=fontRenderer.drawText(text,textNode.alignment,textNode.x,this.canvasHeight-textNode.y,textNode.width,textNode.height,textNode.angleRad,textNode.sizePx,textNode.wrap);this.endGlyphs();return lines},primeTexture:function(resource){var gl=this.gl;this.setMaterial(this.tintWhite,0);this.setUniformTintFromMaterial();this.setTexture(resource.texture);this.setUniformSizeXY(resource.width,resource.height);this.setUniformTextureSSTTToDefault();this.setUniformMVMatrix();gl.drawArrays(gl.TRIANGLE_STRIP,0,4);this.previous.bestCase=false},drawBlank:function(){var gl=this.gl;var imageHandle=this.whiteImage;this.pushMatrix();this.translate(this.canvasWidth*.5,this.canvasHeight*.5);this.setMaterial(this.tintBlack,0);this.setUniformTintFromMaterial();this.setTexture(imageHandle.texture);this.setUniformTextureSSTTToDefault();this.setUniformSizeXY(this.canvasWidth,this.canvasHeight);this.setUniformMVMatrix();this.popMatrix();gl.drawArrays(gl.TRIANGLE_STRIP,0,4);this.previous.bestCase=false},updateSize:function(){this.canvasWidth=this.canvas.width;this.canvasHeight=this.canvas.height;this.setViewport(this.canvas.width,this.canvas.height)},createMatrix:function(){if(this.useFloat32Matrices){var m=[new Float32Array(4),new Float32Array(4),new Float32Array(4),new Float32Array(4)];this.Matrix_identity4x4(m);return m}else{return[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]}},initMatrixStack:function(){this.stackSize=16;for(var i=0;i&lt;this.stackSize;i++){this.mvMatrixStack[i]=this.createMatrix();this.onlyTranslateStack[i]=true}this.stackTop=0;this.mvMatrix=this.mvMatrixStack[this.stackTop];this.onlyTranslate=this.onlyTranslateStack[this.stackTop]},pushMatrix:function(){this.onlyTranslateStack[this.stackTop]=this.onlyTranslate;this.stackTop++;var top=this.mvMatrixStack[this.stackTop];this.Matrix_copy3x3(this.mvMatrix,top);this.mvMatrix=top},popMatrix:function(){this.stackTop--;this.mvMatrix=this.mvMatrixStack[this.stackTop];this.onlyTranslate=this.onlyTranslateStack[this.stackTop]},loadIdentityMatrix:function(){this.Matrix_identity4x4(this.mvMatrix)},multiplyMatrix:function(m){var top=this.mvMatrix;var temp=this.tempMultiplyMatrix;this.Matrix_multiply3x3(top,m,temp);this.mvMatrix=temp;this.mvMatrixStack[this.stackTop]=temp;this.tempMultiplyMatrix=top},multiplyMatrixTranslate:function(x,y){var top=this.mvMatrix;var temp=this.tempMultiplyMatrix;this.Matrix_multiply3x3_translate(top,x,y,temp);this.mvMatrix=temp;this.mvMatrixStack[this.stackTop]=temp;this.tempMultiplyMatrix=top},multiplyMatrixRotate:function(angleRad){var top=this.mvMatrix;var temp=this.tempMultiplyMatrix;this.Matrix_multiply3x3_rotate(top,angleRad,temp);this.mvMatrix=temp;this.mvMatrixStack[this.stackTop]=temp;this.tempMultiplyMatrix=top},multiplyMatrixScale:function(sx,sy){var top=this.mvMatrix;var temp=this.tempMultiplyMatrix;this.Matrix_multiply3x3_scale(top,sx,sy,temp);this.mvMatrix=temp;this.mvMatrixStack[this.stackTop]=temp;this.tempMultiplyMatrix=top},translate:function(x,y){if(this.onlyTranslate){var m=this.mvMatrix;m[0][2]+=x;m[1][2]+=y}else{this.multiplyMatrixTranslate(x,y)}},rotate:function(angleRad){if(angleRad===0){return}this.multiplyMatrixRotate(angleRad);this.onlyTranslate=false},scale:function(sx,sy){if(sx===1&amp;&amp;sy===1){return}if(this.onlyTranslate){var m=this.mvMatrix;m[0][0]*=sx;m[1][1]*=sy}else{this.multiplyMatrixScale(sx,sy);this.onlyTranslate=false}},getShader:function(name,type){var gl=this.gl;var shader=gl.createShader(type);var shaderText=null;if(type===gl.VERTEX_SHADER){shaderText=gs.webgl.shaders[name].vertex}else if(type===gl.FRAGMENT_SHADER){shaderText=gs.webgl.shaders[name].fragment}gl.shaderSource(shader,shaderText);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){gs.Log.error(gl.getShaderInfoLog(shader));return null}return shader},createShaderProgram:function(){var gl=this.gl;var program=gl.createProgram();gl.attachShader(program,this.getShader("safe",gl.VERTEX_SHADER));gl.attachShader(program,this.getShader("safe",gl.FRAGMENT_SHADER));gl.linkProgram(program);if(!gl.getProgramParameter(program,gl.LINK_STATUS)){gs.Log.error(gl.getProgramInfoLog(program))}return program},createBuffer:function(array,itemSize,itemCount){var gl=this.gl;var buffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,array,gl.STATIC_DRAW);buffer.itemSize=itemSize;buffer.itemCount=itemCount;return buffer},createTextureCoordinateBuffer:function(width,height){var coords=this.tempTextureCoordinateArray;coords[0]=width;coords[1]=0;coords[2]=0;coords[3]=0;coords[4]=width;coords[5]=height;coords[6]=0;coords[7]=height;return this.createBuffer(coords,2,4)},initShaders:function(){var gl=this.gl;this.shaderProgram=this.createShaderProgram();gl.useProgram(this.shaderProgram);this.shaderProgram.positionXY=gl.getAttribLocation(this.shaderProgram,"aPositionXY");gl.enableVertexAttribArray(this.shaderProgram.positionXY);this.shaderProgram.textureUV=gl.getAttribLocation(this.shaderProgram,"aTextureUV");gl.enableVertexAttribArray(this.shaderProgram.textureUV);this.shaderProgram.pMatrix=gl.getUniformLocation(this.shaderProgram,"pMatrix");this.shaderProgram.mvMatrix=gl.getUniformLocation(this.shaderProgram,"mvMatrix");this.shaderProgram.sizeXY=gl.getUniformLocation(this.shaderProgram,"uSizeXY");this.shaderProgram.textureSSTT=gl.getUniformLocation(this.shaderProgram,"uTextureSSTT");this.shaderProgram.texture=gl.getUniformLocation(this.shaderProgram,"uTexture");this.shaderProgram.tint=gl.getUniformLocation(this.shaderProgram,"uTint");gl.activeTexture(gl.TEXTURE0);gl.uniform1i(this.shaderProgram.texture,0);gl.bindBuffer(gl.ARRAY_BUFFER,this.defaultVertexBuffer);gl.vertexAttribPointer(this.shaderProgram.positionXY,this.defaultVertexBuffer.itemSize,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,this.defaultTextureCoordinateBuffer);gl.vertexAttribPointer(this.shaderProgram.textureUV,this.defaultTextureCoordinateBuffer.itemSize,gl.FLOAT,false,0,0)},setMatrix:function(a,b,c,d,e,f){this.mvMatrix[0][0]=a;this.mvMatrix[1][0]=b;this.mvMatrix[2][0]=0;this.mvMatrix[0][1]=c;this.mvMatrix[1][1]=d;this.mvMatrix[2][1]=0;this.mvMatrix[0][2]=e;this.mvMatrix[1][2]=f;this.mvMatrix[2][2]=1;if(a!==1||b!==0||c!==0||d!==1){this.onlyTranslate=false}},setTintArray:function(color,blendMode){var tintColor=this.previous.tintColor;this.previous.tintColor=this.tintColor;this.tintColor=tintColor;var alpha=Math.max(0,Math.min(color[3],1));tintColor[0]=color[0];tintColor[1]=color[1];tintColor[2]=color[2];tintColor[3]=alpha;if(blendMode===0||blendMode===3){tintColor[0]*=alpha;tintColor[1]*=alpha;tintColor[2]*=alpha}else if(blendMode===2){tintColor[0]*=alpha;tintColor[1]*=alpha;tintColor[2]*=alpha}},setBlendMode:function(blendMode){if(blendMode!==this.previous.blendMode){var gl=this.gl;this.previous.blendMode=blendMode;switch(blendMode){case 0:gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);break;case 1:gl.blendFunc(gl.ONE,gl.ZERO);break;case 2:gl.blendFunc(gl.ONE,gl.ONE);break;case 3:gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_COLOR);break;case 4:gl.blendFunc(gl.ZERO,gl.SRC_COLOR);break}}},setViewport:function(width,height){this.gl.viewport(0,0,width,height);this.makeOrtho(0,width,height,0,1,-1,this.p4Matrix);this.Matrix_copy4x4to3x3(this.p4Matrix,this.p3Matrix);this.setUniformPMatrix(this.p3Matrix)},height:function(){return this.canvasHeight},width:function(){return this.canvasWidth},isImageTooLarge:function(resource){var size=Math.max(resource.width,resource.height);return size&gt;this.maxTextureSize}};gs.SGWebGLRenderer.prototype.Matrix_multiply4x4=function(a,b,r){var ni=4,ki=ni,i,nj,kj=4,j;var cols=4,sum,nc,c;do{i=ki-ni;nj=kj;do{j=kj-nj;sum=0;nc=cols;do{c=cols-nc;sum+=a[i][c]*b[c][j]}while(--nc);r[i][j]=sum}while(--nj)}while(--ni)};gs.SGWebGLRenderer.prototype.Matrix_copy4x4=function(a,b){b[0][0]=a[0][0];b[0][1]=a[0][1];b[0][2]=a[0][2];b[0][3]=a[0][3];b[1][0]=a[1][0];b[1][1]=a[1][1];b[1][2]=a[1][2];b[1][3]=a[1][3];b[2][0]=a[2][0];b[2][1]=a[2][1];b[2][2]=a[2][2];b[2][3]=a[2][3];b[3][0]=a[3][0];b[3][1]=a[3][1];b[3][2]=a[3][2];b[3][3]=a[3][3]};gs.SGWebGLRenderer.prototype.Matrix_multiply3x3=function(a,b,r){r[0][0]=a[0][0]*b[0][0]+a[0][1]*b[1][0];r[0][1]=a[0][0]*b[0][1]+a[0][1]*b[1][1];r[0][2]=a[0][0]*b[0][2]+a[0][1]*b[1][2]+a[0][2];r[1][0]=a[1][0]*b[0][0]+a[1][1]*b[1][0];r[1][1]=a[1][0]*b[0][1]+a[1][1]*b[1][1];r[1][2]=a[1][0]*b[0][2]+a[1][1]*b[1][2]+a[1][2]};gs.SGWebGLRenderer.prototype.Matrix_multiply3x3_translate=function(a,x,y,r){r[0][0]=a[0][0];r[0][1]=a[0][1];r[0][2]=a[0][0]*x+a[0][1]*y+a[0][2];r[1][0]=a[1][0];r[1][1]=a[1][1];r[1][2]=a[1][0]*x+a[1][1]*y+a[1][2]};gs.SGWebGLRenderer.prototype.Matrix_multiply3x3_rotate=function(a,angleRad,r){var c=Math.cos(angleRad);var s=Math.sin(angleRad);r[0][0]=a[0][0]*c+a[0][1]*s;r[0][1]=a[0][0]*-s+a[0][1]*c;r[0][2]=a[0][2];r[1][0]=a[1][0]*c+a[1][1]*s;r[1][1]=a[1][0]*-s+a[1][1]*c;r[1][2]=a[1][2]};gs.SGWebGLRenderer.prototype.Matrix_multiply3x3_scale=function(a,sx,sy,r){r[0][0]=a[0][0]*sx;r[0][1]=a[0][1]*sy;r[0][2]=a[0][2];r[1][0]=a[1][0]*sx;r[1][1]=a[1][1]*sy;r[1][2]=a[1][2]};gs.SGWebGLRenderer.prototype.Matrix_copy3x3=function(a,b){b[0][0]=a[0][0];b[0][1]=a[0][1];b[0][2]=a[0][2];b[1][0]=a[1][0];b[1][1]=a[1][1];b[1][2]=a[1][2]};gs.SGWebGLRenderer.prototype.Matrix_copy3x3to4x4=function(a,b){b[0][0]=a[0][0];b[0][1]=a[0][1];b[0][3]=a[0][2];b[1][0]=a[1][0];b[1][1]=a[1][1];b[1][3]=a[1][2];b[2][0]=a[2][0];b[2][1]=a[2][1];b[3][3]=a[2][2]};gs.SGWebGLRenderer.prototype.Matrix_copy4x4to3x3=function(a,b){b[0][0]=a[0][0];b[0][1]=a[0][1];b[0][2]=a[0][3];b[1][0]=a[1][0];b[1][1]=a[1][1];b[1][2]=a[1][3];b[2][0]=a[2][0];b[2][1]=a[2][1];b[2][2]=a[3][3]};gs.SGWebGLRenderer.prototype.Matrix_identity4x4=function(m){m[0][0]=1;m[0][1]=0;m[0][2]=0;m[0][3]=0;m[1][0]=0;m[1][1]=1;m[1][2]=0;m[1][3]=0;m[2][0]=0;m[2][1]=0;m[2][2]=1;m[2][3]=0;m[3][0]=0;m[3][1]=0;m[3][2]=0;m[3][3]=1};gs.SGWebGLRenderer.prototype.Matrix_flatten4x4to16=function(a,b){b[0]=a[0][0];b[1]=a[1][0];b[2]=a[2][0];b[3]=a[3][0];b[4]=a[0][1];b[5]=a[1][1];b[6]=a[2][1];b[7]=a[3][1];b[8]=a[0][2];b[9]=a[1][2];b[10]=a[2][2];b[11]=a[3][2];b[12]=a[0][3];b[13]=a[1][3];b[14]=a[2][3];b[15]=a[3][3]};gs.SGWebGLRenderer.prototype.Matrix_flatten3x3to16=function(a,b){b[0]=a[0][0];b[1]=a[1][0];b[4]=a[0][1];b[5]=a[1][1];b[12]=a[0][2];b[13]=a[1][2]};gs.SGWebGLRenderer.prototype.Matrix_flatten3x3to9=function(a,b){b[0]=a[0][0];b[1]=a[1][0];b[3]=a[0][1];b[4]=a[1][1];b[6]=a[0][2];b[7]=a[1][2]};gs.SGWebGLRenderer.prototype.makeOrtho=function(left,right,bottom,top,znear,zfar,r){var tx=-(right+left)/(right-left);var ty=-(top+bottom)/(top-bottom);var tz=-(zfar+znear)/(zfar-znear);r[0][0]=2/(right-left);r[0][3]=tx;r[1][1]=2/(top-bottom);r[1][3]=ty;r[2][2]=-2/(zfar-znear);r[2][3]=tz;r[3][3]=1};gs.FontRenderer=function(renderer,fontFamily,sizePx){this.fontResource=gs.AssetManager.current.fontByName(fontFamily);this.renderContext=renderer;this.glyphData=gs.array.provide();this.rareData=gs.Map.provide();this.sheets=gs.array.provide();this.spaceChar=" ".charCodeAt(0);this.tabChar="\t".charCodeAt(0);this.spaceWidth=0;this.tabWidth=0;this.fontFamily=fontFamily;this.sizePx=sizePx;this.sheetCount=1;this.ready=false;this.fontCSS=sizePx+'px "'+fontFamily+'"';this.textureScale=window.devicePixelRatio||1;if(gs.globalOptions.maxFontSheetTextureSize){this.maxTextureWidth=Math.sqrt(gs.globalOptions.maxFontSheetTextureSize)}else{this.maxTextureWidth=512}this.checkReady()};gs.FontRenderer.sharedBuffer=null;gs.FontRenderer.prototype={checkReady:function(){if(this.fontResource.ready===true){if(this.sheets.length&lt;=0){this.generateFontMap()}return true}else{return false}},drawText:function(text,alignment,x,y,width,height,angle,sizePx,wrap){if(text===undefined||text===null||!this.checkReady()){return null}var isSingleLine=false;var lines;if(Array.isArray(text)){lines=text}else{lines=this.splitLines(text);if(!Array.isArray(lines)){isSingleLine=true;var temp=gs.array.provide();temp[0]=lines;lines=temp}}var context=this.renderContext;context.pushMatrix();context.translate(x,y);context.rotate(angle);var padding=1+.1*sizePx;if(wrap){padding=1+.1*sizePx;this.wrapLinesInPlace(lines,width-2)}var drawWidth=this.calculateMaxStringWidthPx(lines);var drawHeight=this.calculateLinesHeightPx(lines);var drawX=0;if(alignment===1||alignment==="center"){drawX=-.5*drawWidth}else if(alignment===2||alignment==="right"){drawX=.5*width-drawWidth-padding}else{drawX=-.5*width+padding}var usedLineHeight=drawHeight;if(lines.length&gt;1&amp;&amp;wrap){usedLineHeight=Math.min(height,drawHeight)}var drawY=-.5*usedLineHeight;var clipHeight=wrap?height:drawHeight;this.drawLines(lines,alignment,drawX,drawY,drawWidth,clipHeight,wrap);context.popMatrix();if(isSingleLine){gs.array.recycle(lines);lines=null}return lines},drawLines:function(lines,alignment,x,y,width,height,wrap){var context=this.renderContext;context.translate(x,y);var linesToDraw=lines.length;var maxDrawHeight=this.calculateLinesHeightPx(lines);var lineHeight=maxDrawHeight/linesToDraw;if(wrap&amp;&amp;maxDrawHeight&gt;height){linesToDraw=Math.max(1,Math.min(linesToDraw,Math.floor(height/lineHeight)))}for(var i=0,iend=linesToDraw;i&lt;iend;i++){this.drawLine(lines[i],alignment,width);context.translate(0,lineHeight)}},drawLine:function(s,alignment,alignWidth){var s=s.trim();var context=this.renderContext;var fontData=this.glyphData;var font=this.fontResource.opentype;var scaledFontSize=this.sizePx*this.textureScale;var fontScaler=1/font.unitsPerEm*scaledFontSize;var stringWidth=this.calculateStringWidthPx(s);var startX=0;if(alignment===1||alignment==="center"){startX=.5*(alignWidth-stringWidth)}else if(alignment===2||alignment==="right"){startX=alignWidth-stringWidth}else{startX=0}context.pushMatrix();context.translate(Math.round(startX),this.unscaledLineHeight*.5);if(this.textureScale!==1){var scaleValue=1/this.textureScale;context.scale(scaleValue,scaleValue)}var charCount=s.length;var lastGlyph=null;for(var i=0;i&lt;charCount;i++){var c=s.charCodeAt(i);var glyph=font.charToGlyph(s.charAt(i));if(c==160&amp;&amp;glyph.name===".notdef"){c=this.spaceChar}var index=(c-32)*4;if(c===this.spaceChar){context.translate(this.spaceWidth,0)}else if(c===this.tabChar){context.translate(this.tabWidth,0)}else if(0&lt;=index&amp;&amp;index+3&lt;fontData.length){var sheet=this.sheets[fontData[index]];var sx=fontData[index+1];var sy=fontData[index+3];var w=fontData[index+2];var glyphXMin="xMin"in glyph?glyph.xMin:glyph.path.getBoundingBox().x1;var hw=.5*w+glyphXMin*fontScaler;if(lastGlyph){var kerning=font.getKerningValue(lastGlyph,glyph);hw+=kerning*fontScaler}var advanceWidth=glyph.advanceWidth*fontScaler;context.translate(hw,0);context.drawGlyph(sheet,sx,sy,w,this.fontHeight);context.translate(advanceWidth-hw,0)}else{if(!this.rareData[c]){this.genRareChar(c)}var rareGlyph=this.rareData[c];var sprite=rareGlyph.sprite;var w=rareGlyph.width;var hw=.5*w+rareGlyph.xShift;if(lastGlyph){var kerning=font.getKerningValue(lastGlyph,glyph);hw+=kerning*fontScaler}context.translate(hw,0);sprite.checkReady();if(sprite.ready){context.drawGlyphTexture(sprite)}var advanceWidth=glyph.advanceWidth*fontScaler;context.translate(advanceWidth-hw,0)}lastGlyph=glyph}context.popMatrix()},calculateStringWidthPx:function(s){if(!this.stringWidthCache){this.stringWidthCache={}}var cache=this.stringWidthCache;if(!(s in cache)){var w=0;var font=this.fontResource.opentype;var stringBox=font.getPath(s,0,0,this.sizePx).getBoundingBox();cache[s]=stringBox.x2}return cache[s]},calculateMaxStringWidthPx:function(lines){var maxWidthPx=0;for(var i=0,iend=lines.length;i&lt;iend;i++){var widthPx=this.calculateStringWidthPx(lines[i]);maxWidthPx=Math.max(maxWidthPx,widthPx)}return maxWidthPx},calculateLinesHeightPx:function(lines){return this.unscaledLineHeight*lines.length},generateFontMap:function(){this.sheets=[];var font=this.fontResource.opentype;var scaledFontSize=this.sizePx*this.textureScale;var fontPtScaler=scaledFontSize/font.unitsPerEm;if(font.descender&gt;0){font.descender=font.descender*-1}var fontHeight=font.ascender-font.descender;this.unscaledLineHeight=Math.ceil(fontHeight*(this.sizePx/font.unitsPerEm))+1;fontHeight=this.fontHeight=Math.ceil(fontHeight*fontPtScaler)+1;var fontBaseline=this.fontBaseline=Math.ceil(font.ascender*fontPtScaler);var maxTextureDim=this.maxTextureWidth;var charBegin=32;var charEnd=127;var maxCharWidth=0;var maxCharHeight=fontHeight;var glyphs=gs.array.provide();var paths=gs.array.provide();var widths=gs.array.provide();for(var ci=charBegin;ci&lt;charEnd;ci++){var c=String.fromCharCode(ci);var glyph=font.charToGlyph(c);var path=glyph.getPath(0,0,scaledFontSize);path.fill="white";var box=path.getBoundingBox();var width=box.x2-box.x1;var height=box.y2-box.y1;maxCharWidth=Math.max(maxCharWidth,width);maxCharHeight=Math.max(maxCharHeight,height);if(c===" "){this.spaceWidth=glyph.advanceWidth*fontPtScaler;this.tabWidth=4*width}glyphs.push(glyph);paths.push(path);widths.push(width)}maxCharWidth=Math.ceil(maxCharWidth);var colCount=Math.floor(maxTextureDim/maxCharWidth);var rowCount=Math.ceil((charEnd-charBegin)/colCount);rowCount=Math.min(rowCount,Math.floor(maxTextureDim/maxCharHeight));var buffer=new OffscreenCanvas(maxTextureDim,maxTextureDim);var context=buffer.getContext("2d");context.fillStyle="transparent";context.fillRect(0,0,maxTextureDim,maxTextureDim);var fontData=this.glyphData;var sheet=0,col=1,row=1;var cx=0,cy=fontBaseline,ty=0;for(var i=0;i&lt;paths.length;i++){var invertedY=maxTextureDim-fontHeight-ty;fontData.push(sheet);fontData.push(cx);fontData.push(widths[i]);fontData.push(invertedY);var path=paths[i];var box=path.getBoundingBox();context.resetTransform();context.translate(cx-box.x1,cy);path.draw(context);col++;if(col&lt;=colCount){cx+=maxCharWidth}else{cx=0;col=1;cy+=maxCharHeight;ty+=maxCharHeight;row++}if(row&gt;rowCount){this.sheets[sheet]=this.finalizeSheet(buffer,sheet);buffer=new OffscreenCanvas(maxTextureDim,maxTextureDim);context=buffer.getContext("2d");context.fillStyle="transparent";context.fillRect(0,0,maxTextureDim,maxTextureDim);sheet++;row=1;cy=fontBaseline;ty=0}}if(!this.sheets[sheet]){this.sheets[sheet]=this.finalizeSheet(buffer,sheet)}},appendDebugAtlas:function(buffer,sheet){var fontCSS=this.fontCSS+":"+sheet;buffer.convertToBlob().then(function(blob){var img=new Image;img.id=fontCSS;img.src=URL.createObjectURL(blob);img.style.border="1px solid white";document.body.appendChild(img)})},finalizeSheet:function(canvas,sheet){var resource=gs.ImageResource.createFromCanvas(canvas);resource.id="font:"+this.fontCSS+"("+sheet+")";resource.createTexture(this.renderContext.gl);resource.releaseImageElement();return this.renderContext.getHandleManager().getImageHandle(resource)},genRareChar:function(charCode){var font=this.fontResource.opentype;var scaledFontSize=this.sizePx*this.textureScale;var fontPtScaler=1/font.unitsPerEm*scaledFontSize;var fontHeight=Math.ceil((font.ascender-font.descender)*fontPtScaler);var fontBaseline=Math.ceil(font.ascender*fontPtScaler);var charStr=String.fromCharCode(charCode);var glyph=font.charToGlyph(charStr);var path=glyph.getPath(0,0,scaledFontSize);path.fill="white";var box=path.getBoundingBox();var width=box.x2-box.x1;if("leftSideBearing"in glyph){width+=Math.abs(glyph.leftSideBearing)}var buffer=new OffscreenCanvas(width,fontHeight);var context=buffer.getContext("2d");var xShift=Math.floor(-1*box.x1);if("leftSideBearing"in glyph){xShift+=(glyph.leftSideBearing||0)*fontPtScaler}context.translate(xShift,fontBaseline);path.draw(context);var resource=gs.ImageResource.createFromCanvas(buffer);resource.id="char:"+charStr+this.fontCSS;resource.createTexture(this.renderContext.gl);resource.releaseImageElement();var sprite=this.renderContext.getHandleManager().getImageHandle(resource);this.rareData[charCode]={width:width,sprite:sprite,xShift:xShift}},splitLines:function(s){if(s.indexOf("\n")===-1){return s}return s.split("\n")},wrapLinesInPlace:function(lines,wrapWidthPx){var lineCount=lines.length;var i;for(i=0;i&lt;lineCount;i++){lines[i]=this.wrapString(lines[i],wrapWidthPx)}for(i=0;i&lt;lines.length;i++){var sublines=this.splitLines(lines[i]);if(Array.isArray(sublines)){lines.splice(i,1);for(var j=0;j&lt;sublines.length;j++){lines.splice(i+j,0,sublines[j])}i+=sublines.length-1;gs.array.recycle(sublines)}}return lines},wrapString:function(s,wrapWidthPx){var stringWidthPx=this.calculateStringWidthPx(s);if(stringWidthPx&lt;=wrapWidthPx){return s}else{var words=s.split(/\s+/g);var wordCount=words.length;var spaceWidthPx=this.spaceWidth;var word=words[0];var wrappedString="";var lineWidthPx=this.calculateStringWidthPx(word);var lineString=word;for(var i=1;i&lt;wordCount;i++){word=words[i];var newStringWidth=this.calculateStringWidthPx(lineString+" "+word);if(newStringWidth&gt;wrapWidthPx){wrappedString+=lineString+"\n";lineString=word;lineWidthPx=this.calculateStringWidthPx(word)}else{lineString+=" ";lineString+=word;lineWidthPx=newStringWidth}}wrappedString+=lineString;gs.array.recycle(words);return wrappedString}}};Box2D.Dynamics.b2Body.prototype.SetUserData=function(userData){this.userData=userData};Box2D.Dynamics.b2Body.prototype.GetUserData=function(){return this.userData};Box2D.Dynamics.b2Fixture.prototype.SetUserData=function(userData){this.userData=userData};Box2D.Dynamics.b2Fixture.prototype.GetUserData=function(){return this.userData};Box2D.Dynamics.b2Fixture.prototype.ResizeShapeAsBox=function(hx,hy){this.m_shape.SetAsBox(hx,hy)};Box2D.Dynamics.b2Fixture.prototype.ResizeShapeAsCircle=function(radius){this.m_shape.SetRadius(radius)};Box2D.Dynamics.b2Body.prototype.ResizeFixtureShapesAsBox=function(hx,hy){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.ResizeShapeAsBox(hx,hy)}this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.ResizeFixtureShapesAsCircle=function(radius){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.ResizeShapeAsCircle(radius)}this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.ChangeFixtureDensities=function(value){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.SetDensity(value)}this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.ChangeFixtureFrictions=function(value){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.SetFriction(value)}this.ResetMassData()};Box2D.Dynamics.b2Body.prototype.ChangeFixtureRestitutions=function(value){for(var node=this.fixtureList.GetFirstNode();node;node=node.GetNextNode()){node.fixture.SetRestitution(value)}this.ResetMassData()};gs.GS_COLLISION_SHAPE_ID=1;gs.GS_SENSOR_SHAPE_ID=2;gs.ActorUserData=function(){this.actorID=null;if(this.collisionCategories){this.collisionCategories.length=0}else{this.collisionCategories=gs.array.provide()}};gs.Pool.init(gs.ActorUserData);gs.ActorUserData.prototype.setActorID=function(newId){this.actorID=newId};gs.ActorUserData.prototype.addCollisionCategory=function(category){this.collisionCategories.push(category)};gs.ActorUserData.prototype.removeCollisionCategory=function(category){var index=this.collisionCategories.indexOf(category);if(index&gt;-1){this.collisionCategories.splice(index,1)}};gs.FixtureUserData=function(){this.fixtureID=null;if(this.collisionMask){this.collisionMask.length=0}else{this.collisionMask=gs.array.provide()}};gs.Pool.init(gs.FixtureUserData);gs.FixtureUserData.prototype.setFixtureID=function(newId){this.fixtureID=newId};gs.FixtureUserData.prototype.addCollisionMaskCategory=function(category){this.collisionMask.push(category)};gs.FixtureUserData.prototype.removeCollisionMaskCategory=function(category){var index=this.collisionMask.indexOf(category);if(index&gt;-1){this.collisionMask.splice(index,1)}};gs.ContactListener={m_collidingShapes:[],getContactCount:function(){return this.m_collidingShapes.length}};gs.ContactListener.m_collidingShapes.find=function(fixtureA,fixtureB){var testPair;for(var i=0;i&lt;this.length;++i){testPair=this[i];if(testPair.equivalentTo(fixtureA,fixtureB)){return testPair}}return null};gs.ContactListener.m_collidingShapes.add=function(fixtureA,fixtureB,collideCount){var pair=gs.FixturePair.provide(fixtureA,fixtureB);pair.collideCount=collideCount;this.push(pair)};gs.ContactListener.m_collidingShapes.erase=function(pair){var index=this.indexOf(pair);gs.FixturePair.recycle(this[index]);this.splice(index,1);return null};gs.FixturePair=function(fixtureA,fixtureB){this.fixtureA=fixtureA;this.fixtureB=fixtureB;this.collideCount=0};gs.FixturePair.pool=[];gs.FixturePair.recycle=function(o){o.fixtureA=null;o.fixtureB=null;gs.FixturePair.pool.push(o)};gs.FixturePair.provide=function(fixtureA,fixtureB){if(gs.FixturePair.pool.length&gt;0){var pair=gs.FixturePair.pool.pop();gs.FixturePair.call(pair,fixtureA,fixtureB);return pair}return new gs.FixturePair(fixtureA,fixtureB)};gs.FixturePair.prototype={equivalentTo:function(fixtureA,fixtureB){if(this.fixtureA===fixtureA){return this.fixtureB===fixtureB}if(this.fixtureB===fixtureA){return this.fixtureA===fixtureB}return false}};gs.ContactListener.getSensorFixture=function(body){var node=body.fixtureList.GetFirstNode();while(node&amp;&amp;node.fixture.GetUserData().fixtureID!==gs.GS_SENSOR_SHAPE_ID){node=node.GetNextNode()}return node?node.fixture:null};gs.ContactListener.BeginContact=function(contact){var fixtureA=contact.m_fixtureA;var fixtureB=contact.m_fixtureB;if(fixtureA.GetUserData().fixtureID!==gs.GS_SENSOR_SHAPE_ID){var sensorFixture1=this.getSensorFixture(fixtureA.m_body);if(!sensorFixture1){return}}if(fixtureB.GetUserData().fixtureID!==gs.GS_SENSOR_SHAPE_ID){var sensorFixture2=this.getSensorFixture(fixtureB.m_body);if(!sensorFixture2){return}}var pair=this.m_collidingShapes.find(fixtureA,fixtureB);if(pair===null){this.fixtureCollisionBegan(fixtureA,fixtureB);this.m_collidingShapes.add(fixtureA,fixtureB,1);return}++pair.collideCount};gs.ContactListener.EndContact=function(contact){var fixtureA=contact.m_fixtureA;var fixtureB=contact.m_fixtureB;var pair=this.m_collidingShapes.find(fixtureA,fixtureB);if(pair===null){return}if(--pair.collideCount===0){this.fixtureCollisionEnded(fixtureA,fixtureB);this.m_collidingShapes.erase(pair)}};gs.ContactListener.PreSolve=function(contact,oldManifold){};gs.ContactListener.PostSolve=function(contact,impulse){};gs.ContactFilter={};gs.ContactFilter.hasIntersection=function(s1,s2){if(s1.length===0||s2.length===0){return false}for(var it1=0;it1&lt;s1.length;it1++){for(var it2=0;it2&lt;s2.length;it2++){if(s2[it2]===s1[it1]){return true}}}return false};gs.ContactFilter.ShouldCollide=function(fixtureA,fixtureB){var fixtureDataA=fixtureA.GetUserData();var fixtureDataB=fixtureB.GetUserData();if(fixtureDataA.fixtureID===fixtureDataB.fixtureID){var actorDataA=fixtureA.m_body.GetUserData();var actorDataB=fixtureB.m_body.GetUserData();var shouldCollide=gs.ContactFilter.hasIntersection(fixtureDataA.collisionMask,actorDataB.collisionCategories)||gs.ContactFilter.hasIntersection(fixtureDataB.collisionMask,actorDataA.collisionCategories);return shouldCollide}return false};gs.ContactListener.fixtureCollisionBegan=function(fixtureA,fixtureB){var game=gs.Game.current;var collisionController=game.getCurrentScene()._collisionController;var actorA=fixtureA.m_body.GetUserData().actorID;var collidingActor1=collisionController.getActorFromActorID(actorA);if(!collidingActor1){return}var actorB=fixtureB.m_body.GetUserData().actorID;var collidingActor2=collisionController.getActorFromActorID(actorB);if(!collidingActor2){return}var delegates=collisionController.delegatesForActorCollisionPair(collidingActor1,collidingActor2);for(var i=0;i&lt;delegates.length;++i){delegates[i].collisionBegan(collidingActor1,collidingActor2)}};gs.ContactListener.fixtureCollisionEnded=function(fixtureA,fixtureB){var game=gs.Game.current;var currentScene=game.getCurrentScene();var collisionController;if(currentScene){collisionController=currentScene._collisionController}if(!currentScene||!collisionController){return}var actorA=fixtureA.m_body.GetUserData().actorID;var collidingActor1=collisionController.getActorFromActorID(actorA);if(!collidingActor1){return}var actorB=fixtureB.m_body.GetUserData().actorID;var collidingActor2=collisionController.getActorFromActorID(actorB);if(!collidingActor2){return}var delegates=collisionController.delegatesForActorCollisionPair(collidingActor1,collidingActor2);for(var i=0;i&lt;delegates.length;++i){delegates[i].collisionEnded(collidingActor1,collidingActor2)}};gs.physicsLib=function(){var Box2D=window.Box2D;if(Box2D===undefined){Box2D=window}var SIMULATION_BORDER=500;var BOX2D_TO_GS=50;var GS_TO_BOX2D=1/BOX2D_TO_GS;var sharedTempVector=new Box2D.Common.Math.b2Vec2(0,0);var sharedb2BodyDef=new Box2D.Dynamics.b2BodyDef;var sharedTempJointDef=new Box2D.Dynamics.Joints.b2RevoluteJointDef;var Physics=function(){};Physics.SIMULATION_BORDER=SIMULATION_BORDER;Physics.BOX2D_TO_GS=BOX2D_TO_GS;Physics.GS_TO_BOX2D=GS_TO_BOX2D;Physics.DYNAMIC_BODY=Box2D.Dynamics.b2BodyDef.b2_dynamicBody;Physics.STATIC_BODY=Box2D.Dynamics.b2BodyDef.b2_staticBody;Physics.World=function(gravityX,gravityY,doSleep){var gravity=Box2D.Common.Math.b2Vec2.Get(gravityX*GS_TO_BOX2D,gravityY*GS_TO_BOX2D);var world=Box2D.Dynamics.b2World.Get(gravity,doSleep);Box2D.Common.Math.b2Vec2.Free(gravity);world.SetContactListener(gs.ContactListener);world.SetContactFilter(gs.ContactFilter);var worldBodyDef=new Box2D.Dynamics.b2BodyDef;this.worldBackground=world.CreateBody(worldBodyDef);this._world=world;return this};Physics.World.prototype={setGravity:function(gravityX,gravityY){gravityX=gravityX*GS_TO_BOX2D;gravityY=gravityY*GS_TO_BOX2D;this._world.SetGravity(Box2D.Common.Math.b2Vec2.Get(gravityX,gravityY))},step:function(dt,velocityIterations,positionIterations){this._world.Step(dt,velocityIterations,positionIterations)},clearForces:function(){this._world.ClearForces()},createBody:function(bodyDef){var newBody=Physics.Body.provide();newBody._body=this._world.CreateBody(bodyDef._bodyDef);newBody._body.SetUserData(gs.ActorUserData.provide());return newBody},destroyBody:function(body){var actorUserData=body._body.GetUserData();if(actorUserData&amp;&amp;actorUserData.pinJoint){this._world.DestroyJoint(actorUserData.pinJoint);actorUserData.pinJoint=null}body._body.SetUserData(null);this._world.DestroyBody(body._body);body._body=null;gs.ActorUserData.recycle(actorUserData);Physics.Body.recycle(body)},recycleThis:function(){Box2D.Dynamics.b2World.Free(this._world);this._world=null}};Physics.BodyDef=function(){this.userData=null;this._bodyDef=sharedb2BodyDef;return this};Physics.BodyDef.prototype={setPosition:function(x,y){this._bodyDef.position.Set(x*GS_TO_BOX2D,y*GS_TO_BOX2D)},setAngle:function(angle){this._bodyDef.angle=angle},setFixedRotation:function(isFixedRotation){this._bodyDef.fixedRotation=isFixedRotation},setIsBullet:function(isBullet){this._bodyDef.bullet=isBullet},setCanSleep:function(canSleep){this._bodyDef.allowSleep=canSleep},setType:function(bodyType){this._bodyDef.type=bodyType}};var sharedBodyDef=new Physics.BodyDef;Physics.GetBodyDef=function(){return sharedBodyDef};Physics.Fixture=function(){};gs.Pool.init(Physics.Fixture);Physics.Fixture.prototype={fixtureID:function(){var userData=this._fixture.GetUserData();return userData.fixtureID},setFixtureID:function(fixtureID){var userData=this._fixture.GetUserData();userData.setFixtureID(fixtureID)},addCollisionMaskCategory:function(category){var userData=this._fixture.GetUserData();userData.addCollisionMaskCategory(category)},removeCollisionMaskCategory:function(category){var userData=this._fixture.GetUserData();userData.removeCollisionMaskCategory(category)},testPoint:function(x,y){return this._fixture.TestPoint({x:x*GS_TO_BOX2D,y:y*GS_TO_BOX2D})}};Physics.Body=function(){};gs.Pool.init(Physics.Body);Physics.Body.prototype={setActorID:function(actorID){var userData=this._body.GetUserData();userData.setActorID(actorID)},addCollisionCategory:function(category){if(category===null){gs.Log.error("bad category to addCollisionCategory")}var userData=this._body.GetUserData();userData.addCollisionCategory(category)},getPosition:function(returnVec){var tempVec=this._body.GetPosition();returnVec[0]=tempVec.x*BOX2D_TO_GS;returnVec[1]=tempVec.y*BOX2D_TO_GS;return returnVec},angle:function(){return this._body.GetAngle()},setLinearVelocity:function(velX,velY){sharedTempVector.x=velX*GS_TO_BOX2D;sharedTempVector.y=velY*GS_TO_BOX2D;this._body.SetAwake(true);this._body.SetLinearVelocity(sharedTempVector)},getLinearVelocity:function(returnVec){var velocity=this._body.GetLinearVelocity();returnVec[0]=velocity.x*BOX2D_TO_GS;returnVec[1]=velocity.y*BOX2D_TO_GS;return returnVec},setAngularVelocity:function(velocity){this._body.SetAwake(true);this._body.SetAngularVelocity(velocity)},angularVelocity:function(){return this._body.GetAngularVelocity()},setAngularDamping:function(omega){this._body.SetAngularDamping(omega)},applyForce:function(force,point){this._body.SetAwake(true);sharedTempVector.x=force[0]*GS_TO_BOX2D;sharedTempVector.y=force[1]*GS_TO_BOX2D;this._body.ApplyForce(sharedTempVector,point)},applyForceNoConversion:function(force,point){this._body.ApplyForce(force,point)},pin:function(world,pin){var body=this._body;var userData=body.GetUserData();if(userData&amp;&amp;userData.pinJoint){world._world.DestroyJoint(userData.pinJoint);userData.pinJoint=null}if(pin){var worldCenter=body.GetWorldCenter();sharedTempJointDef.Initialize(world.worldBackground,body,worldCenter);var pinJointRef=world._world.CreateJoint(sharedTempJointDef);if(userData){userData.pinJoint=pinJointRef}}},setCenterOfMass:function(x,y){var tempVector=new Box2D.Common.Math.b2Vec2(x*GS_TO_BOX2D,y*GS_TO_BOX2D);this._body.SetMassOffset(tempVector)},centerOfMass:function(x,y){var massData=this._body.GetMassData();var com=gs.array.provide();com[0]=massData.center.x*BOX2D_TO_GS;com[1]=massData.center.y*BOX2D_TO_GS;return com},setAwake:function(awake){this._body.SetAwake(awake);this._body.SetActive(awake)},isAwake:function(){return this._body.IsAwake()},setPositionAndAngle:function(positionX,positionY,angle){var body=this._body;sharedTempVector.x=positionX*GS_TO_BOX2D;sharedTempVector.y=positionY*GS_TO_BOX2D;body.SetAwake(true);body.SetPositionAndAngle(sharedTempVector,angle)},createFixture:function(fixtureDef){var fixture=Physics.Fixture.provide();var body=this._body;fixture._fixture=body.CreateFixture(fixtureDef._fixtureDef);fixture._fixture.SetUserData(gs.FixtureUserData.provide());return fixture},destroyFixture:function(fixture){if(fixture._fixture){var fixtureUserData=fixture._fixture.GetUserData();this._body.DestroyFixture(fixture._fixture);fixture._fixture=null;gs.FixtureUserData.recycle(fixtureUserData);Physics.Fixture.recycle(fixture)}},resizeFixtureShapesAsBox:function(halfWidth,halfHeight){this._body.ResizeFixtureShapesAsBox(halfWidth*GS_TO_BOX2D,halfHeight*GS_TO_BOX2D)},resizeFixtureShapesAsCircle:function(radius){this._body.ResizeFixtureShapesAsCircle(radius*GS_TO_BOX2D)},changeFixtureDensities:function(value){this._body.ChangeFixtureDensities(value)},changeFixtureFrictions:function(value){this._body.ChangeFixtureFrictions(value)},changeFixtureRestitutions:function(value){this._body.ChangeFixtureRestitutions(value)},getMass:function(){return this._body.GetMass()},getWorldCenter:function(){return this._body.GetWorldCenter()}};Physics.FixtureDef=function(){this.userData=null;this._fixtureDef=new Box2D.Dynamics.b2FixtureDef};Physics.FixtureDef.prototype={setShape:function(shape){this._fixtureDef.shape=shape},setDensity:function(density){this._fixtureDef.density=density},setFriction:function(friction){this._fixtureDef.friction=friction*GS_TO_BOX2D},setRestitution:function(restitution){this._fixtureDef.restitution=restitution},setIsSensor:function(isSensor){this._fixtureDef.isSensor=isSensor},addCollisionMaskCategory:function(category){var userData=this._fixtureDef.userData;userData.addCollisionMaskCategory(category)}};var sharedFixtureDef=new Physics.FixtureDef;Physics.GetFixtureDef=function(){return sharedFixtureDef};var sharedb2CircleShape=new Box2D.Collision.Shapes.b2CircleShape(0);Physics.GetCircleShape=function(radius){sharedb2CircleShape.m_radius=radius*GS_TO_BOX2D;return sharedb2CircleShape};var sharedb2PolygonBoxShape=new Box2D.Collision.Shapes.b2PolygonShape;Physics.GetPolygonShapeAsBox=function(halfWidth,halfHeight){sharedb2PolygonBoxShape.SetAsBox(halfWidth*GS_TO_BOX2D,halfHeight*GS_TO_BOX2D);return sharedb2PolygonBoxShape};Physics.GetPolygonShapes=function(halfWidth,halfHeight,polygons,aspectRatioY){var shapes=[];var yScale=(aspectRatioY||1)*2;const scaledHalfWidth=GS_TO_BOX2D*halfWidth;const scaledHalfHeight=GS_TO_BOX2D*halfHeight;for(var p=0;p&lt;polygons.length;p++){var vertices=polygons[p].map(function(v){var vert=Box2D.Common.Math.b2Vec2.Get();vert.x=scaledHalfWidth*(v[0]*2-1),vert.y=scaledHalfHeight*(v[1]*yScale-1);return vert});var b2Poly=Box2D.Collision.Shapes.b2PolygonShape.Get();b2Poly.SetAsArray(vertices);shapes.push(b2Poly)}return shapes};return Physics}();gs.CollisionController=gs.GameSaladObject.subclass("CollisionController");gs.CollisionController.init=function(){gs.GameSaladObject.init.call(this);if(this){this.collidableActors=gs.sparseArray.create();this.sensorRegistrations=gs.Map.provide();this.collisionRegistrations=gs.Map.provide()}return this};gs.CollisionController.getActorFromActorID=function(actorID){return this.collidableActors[actorID]};gs.CollisionController.addCollidableActor=function(actor){return this.collidableActors.addItem(actor)};gs.CollisionController.removeCollidableActorForIndex=function(index){this.collidableActors.removeItemAtIndex(index)};gs.CollisionController.actorsMatchingCategoryResult=[];gs.CollisionController.actorsMatchingCategory=function(categoryObject){var result=gs.CollisionController.actorsMatchingCategoryResult;result.length=0;var collidableActors=this.collidableActors;var nnn=collidableActors.n;for(var i=0;i&lt;nnn;++i){var actor=collidableActors[i];if(actor&amp;&amp;actor.matchesCategory(categoryObject)){result.push(actor)}}return result};gs.CollisionController.sensorRegistrationCountForCategory=function(category){var result=0;var sensorRegistrations=this.sensorRegistrations;for(var actorKey in sensorRegistrations){var registrations=sensorRegistrations[actorKey];var delegates=registrations[category];if(delegates){result=result+delegates.length}}return result};gs.CollisionController.collisionRegistrationCountForCategory=function(category){var result=0;var collisionRegistrations=this.collisionRegistrations;for(var actorKey in collisionRegistrations){result=result+collisionRegistrations[actorKey].countOfObject(category)}return result};gs.CollisionController.addActorSensor=function(actor,category,collisionDelegate){var actorKey=actor._objectKey;actor.aspects.addAspect("collisionSensor");var sensorRegistrations=this.sensorRegistrations;var registrations=sensorRegistrations[actorKey];if(!registrations){registrations=gs.Map.provide();sensorRegistrations[actorKey]=registrations}var delegates=registrations[category];if(!delegates){delegates=gs.array.provide();registrations[category]=delegates;var categoryIndex=actor.game().collisionCategoryManager.categoryIndexForObject(category);actor.aspects.collisionSensor.addCollisionMaskCategory(categoryIndex)}delegates.push(collisionDelegate);var actorsInCategory=this.actorsMatchingCategory(category);var actorCount=actorsInCategory.length;for(var i=0;i&lt;actorCount;++i){var matchingActor=actorsInCategory[i];var receivedSensors=matchingActor.receivedSensors;if(receivedSensors===0){matchingActor.aspects.addAspect("collisionSensor")}matchingActor.receivedSensors=receivedSensors+1}};gs.CollisionController.removeActorSensor=function(actor,category,collisionDelegate){var actorKey=actor._objectKey;var sensorRegistrations=this.sensorRegistrations;var registrations=sensorRegistrations[actorKey];if(!registrations){return}var delegates=registrations[category];if(!delegates){return}var index=delegates.indexOf(collisionDelegate);if(index&gt;-1){delegates.splice(index,1);if(delegates.length===0){delete registrations[category];var categoryIndex=actor.game().collisionCategoryManager.categoryIndexForObject(category);actor.aspects.collisionSensor.removeCollisionMaskCategory(categoryIndex);var tablesize=0;for(var property in registrations){++tablesize;break}if(tablesize===0){delete sensorRegistrations[actorKey];if(actor.receivedSensors===0){actor.aspects.removeAspect("collisionSensor")}}}}var actorsInCategory=this.actorsMatchingCategory(category);var actorCount=actorsInCategory.length;for(var i=0;i&lt;actorCount;++i){var matchingActor=actorsInCategory[i];var receivedSensors=Math.max(matchingActor.receivedSensors-1,0);var regs=sensorRegistrations[matchingActor._objectKey];if(receivedSensors===0&amp;&amp;regs===null){matchingActor.aspects.removeAspect("collisionSensor");matchingActor.receivedSensors=receivedSensors}}};gs.CollisionController.delegatesForActorCollidingWithActor=function(actor1,actor2,result){var actorKey=actor1._objectKey;var registrations=this.sensorRegistrations[actorKey];if(!registrations){return result}var actorCategories=actor2.tags();for(var i=0,end=actorCategories.length;i&lt;end;++i){var category=actorCategories[i];var delegates=registrations[category];if(delegates){var delegatesCount=delegates.length;for(var jj=0;jj&lt;delegatesCount;++jj){var delegate=delegates[jj];if(result.indexOf(delegate)===-1){result.push(delegate)}}}}var category=actor2._prototypeID;delegates=registrations[category];if(delegates){delegatesCount=delegates.length;for(jj=0;jj&lt;delegatesCount;++jj){delegate=delegates[jj];if(result.indexOf(delegate)===-1){result.push(delegate)}}}return result};gs.CollisionController.delegatesForActorCollisionPairResult=new Set;gs.CollisionController.collectDelegatesForKey=function(registrations,key){var result=gs.CollisionController.delegatesForActorCollisionPairResult;var delegates=registrations[key];if(delegates){delegates.forEach(function(delegate){result.add(delegate)})}};gs.CollisionController.delegatesForActorCollisionPair=function(actor1,actor2){var result=gs.CollisionController.delegatesForActorCollisionPairResult;result.clear();var collectDelegatesForKey=gs.CollisionController.collectDelegatesForKey;var registrations=this.sensorRegistrations[actor1._objectKey];if(registrations){var prototypeID=actor2._prototypeID;collectDelegatesForKey(registrations,prototypeID);var tags=actor2.tags()||[];for(var i=0;i&lt;tags.length;i++){collectDelegatesForKey(registrations,tags[i])}}registrations=this.sensorRegistrations[actor2._objectKey];if(registrations){var prototypeID=actor1._prototypeID;collectDelegatesForKey(registrations,prototypeID);var tags=actor1.tags()||[];for(var i=0;i&lt;tags.length;i++){collectDelegatesForKey(registrations,tags[i])}}return Array.from(result)};gs.CollisionController.addActorCollision=function(actor,category){var actorKey=actor._objectKey;var collisionRegistrations=this.collisionRegistrations;var registrations=collisionRegistrations[actorKey];if(!registrations){registrations=new gs.MultiSet;collisionRegistrations[actorKey]=registrations;actor.aspects.addAspect("collisionShape");actor.aspects.motion._body.setAwake(true)}registrations.addObject(category);if(registrations.countOfObject(category)===1){var categoryIndex=actor.game().collisionCategoryManager.categoryIndexForObject(category);actor.aspects.collisionShape.addCollisionMaskCategory(categoryIndex)}var actorsInCategory=this.actorsMatchingCategory(category);var actorCount=actorsInCategory.length;for(var i=0;i&lt;actorCount;++i){var matchingActor=actorsInCategory[i];var receivedCollisions=matchingActor.receivedCollisions;if(receivedCollisions===0){matchingActor.aspects.addAspect("collisionShape");matchingActor.aspects.motion._body.setAwake(true)}matchingActor.receivedCollisions=receivedCollisions+1}};gs.CollisionController.removeActorCollision=function(actor,category){var actorKey=actor._objectKey;var collisionRegistrations=this.collisionRegistrations;var registrations=collisionRegistrations[actorKey];if(!registrations){return}registrations.removeObject(category);if(registrations.countOfObject(category)===0){var categoryIndex=actor.game().collisionCategoryManager.categoryIndexForObject(category);actor.aspects.collisionShape.removeCollisionMaskCategory(categoryIndex);var tablesize=0;for(var property in registrations){++tablesize;break}if(tablesize===0){delete collisionRegistrations[actorKey];if(actor.receivedCollisions===0){actor.aspects.removeAspect("collisionShape")}}}var actorsInCategory=this.actorsMatchingCategory(category);var actorCount=actorsInCategory.length;for(var i=0;i&lt;actorCount;++i){var matchingActor=actorsInCategory[i];var receivedCollisions=Math.max(matchingActor.receivedCollisions-1,0);if(receivedCollisions===0&amp;&amp;!collisionRegistrations[matchingActor._objectKey]){matchingActor.aspects.removeAspect("collisionShape")}matchingActor.receivedCollisions=receivedCollisions}};gs.CollisionCategoryManager=function(){this.collisionCategories=gs.array.provide();this.reverseCollisionCategories=gs.Map.provide()};gs.CollisionCategoryManager.prototype.resetCollisionCategories=function(){this.collisionCategories=gs.array.provide();this.reverseCollisionCategories=gs.Map.provide()};gs.CollisionCategoryManager.prototype.addCollisionCategory=function(category){var collisionCategories=this.collisionCategories;var newIndex=collisionCategories.length;collisionCategories[newIndex]=category;this.reverseCollisionCategories[category]=newIndex};gs.CollisionCategoryManager.prototype.categoryIndexForObject=function(categoryObject){return this.reverseCollisionCategories[categoryObject]};gs.CustomShape=gs.GameSaladObject.subclass("CustomShape");gs.CustomShape.init=function(rescale,polygons,shallowPolygons){this._objectKey="_customShape";gs.GameSaladObject.init.call(this);this.rescale=!!rescale;if(shallowPolygons){this.polygons=polygons}else{this.polygons=this.clonePolygons(polygons)}return this};gs.CustomShape.clone=function(){var other=gs.CustomShape.create();other.init(this.rescale,this.polygons,true);return other};gs.CustomShape.clonePolygons=function(polygons){polygons=polygons||this.polygons;var newPolys=[];for(var i=0;i&lt;polygons.length;i++){var origPoly=polygons[i];var newPoly=[];for(var j=0;j&lt;origPoly.length;j++){newPoly.push([origPoly[j][0],origPoly[j][1]])}newPolys.push(newPoly)}return newPolys};gs.Game.primeInitialPools=function(){gs.Layer.primePool(8);gs.Timebase.primePool(64);gs.SGWebGLImage.primePool(64);gs.EventCenterRegistration.primePool(128);gs.SGParticleSystemNode.primePool(32);gs.InternalParticle.primePool(256);gs.SGClearNode.primePool(2);gs.SGColorNode.primePool(2);gs.SGOrtho2DSpace.primePool(8);gs.SGSpace.primePool(64);gs.SGSpriteNode.primePool(64);gs.SGWrapNode.primePool(64)};gs.Game.primePoolsPerScene=function(){gs.array.primePool(128)};gs.Game.primeBox2D=function(){var i;var bodyCount=64;var collideBodyCount=8;var vectorCount=256;var world=new gs.physicsLib.World(0,0,true);world._world.SetContactFilter({ShouldCollide:function(){return true}});var bodies=gs.array.provide();var boxFixtures=gs.array.provide();var circleFixtures=gs.array.provide();var bodyDef=gs.physicsLib.GetBodyDef();bodyDef.setType(gs.physicsLib.DYNAMIC_BODY);var fixtureDef=gs.physicsLib.GetFixtureDef();fixtureDef.setDensity(1);var boxShape=gs.physicsLib.GetPolygonShapeAsBox(1,1);var circleShape=gs.physicsLib.GetCircleShape(1);var force=[1,1];for(i=0;i&lt;bodyCount;i++){var body=world.createBody(bodyDef);bodies.push(body);fixtureDef.setShape(boxShape);fixtureDef.setIsSensor(false);var boxFixture=body.createFixture(fixtureDef);boxFixtures.push(boxFixture);fixtureDef.setShape(circleShape);fixtureDef.setIsSensor(true);var circleFixture=body.createFixture(fixtureDef);circleFixtures.push(circleFixture);var center=body.getWorldCenter();body.applyForce(force,center)}for(i=collideBodyCount;i&lt;bodyCount;i++){bodies[i].destroyFixture(boxFixtures[i]);bodies[i].destroyFixture(circleFixtures[i]);world.destroyBody(bodies[i])}world.step(1,10,10);world.clearForces();for(i=0;i&lt;collideBodyCount;i++){bodies[i].destroyFixture(boxFixtures[i]);bodies[i].destroyFixture(circleFixtures[i]);world.destroyBody(bodies[i])}var otherWorld=new gs.physicsLib.World(0,0,true);otherWorld.recycleThis();world.recycleThis();for(i=0;i&lt;vectorCount;i++){var v=new Box2D.Common.Math.b2Vec2(0,0);Box2D.Common.Math.b2Vec2.Free(v)}};gs.AutoplayOption={NONE:"NONE",ENGINE:"ENGINE",LOAD:"LOAD",PLAY:"PLAY"};gs.AudioOption={STANDARD:"STANDARD",EXTENSION:"EXTENSION",DETECT:"DETECT"};gs.LoadStrategyOption={NONE:"NONE",INITIAL:"INITIAL",LATENCY:"LATENCY",STRICT:"STRICT",SAFE:"SAFE",SCENE:"SCENE",GAME:"GAME"};gs.RendererOption={CANVAS:"CANVAS",WEBGL:"WEBGL",DETECT:"DETECT"};gs.SceneOption={FIRST:"first",LAST:"last",NEXT:"next",PREVIOUS:"prev"};gs.EngineOptions=function(){this.gamePath=null;this.defaultPath="game/default";this.autoplay=gs.AutoplayOption.PLAY;this.scene=gs.SceneOption.FIRST;this.loadStrategy=gs.LoadStrategyOption.SAFE;this.renderer=gs.RendererOption.DETECT;this.width=0;this.height=0;this.zoom=1;this.viewportReference=gs.ViewportReference.FRAME;this.viewportFit=gs.ViewportFit.LETTERBOX;this.viewportScale=gs.ViewportScale.RESIZE;this.viewportFactor=1;this.drawFactor=1;this.drawFirst=false;this.audio=gs.AudioOption.DETECT;this.targetRate=0;this.minFrameDeltaMS=4;this.maxFrameDeltaMS=1e3/30;this.maxFrameDebtMS=16;this.idealFrameMS=16;this.hitchFrameMS=1e3/15;this.hitchWindowMS=2*1e3;this.logLevel=gs.Log.LogLevel.ALL};gs.EngineOptions.prototype={setOption:function(key,value){key=this.getCanonicalKey(key);if(key&amp;&amp;key in this.obfuscationLookup){key=this.obfuscationLookup[key];this[key]=value}},normalize:function(){this.loadStrategy=this.loadStrategy.toUpperCase()},getCanonicalKey:function(key){if(key in this.obfuscationLookup){return key}switch(key){case"game":return"gamePath"}var indexOfHyphen=key.indexOf("-");var nextChar;while(indexOfHyphen!==-1){nextChar=key.charAt(indexOfHyphen+1);key=key.substring(0,indexOfHyphen)+nextChar.toUpperCase()+key.substring(indexOfHyphen+2);indexOfHyphen=key.indexOf("-")}if(key in this.obfuscationLookup){return key}return null},loadObject:function(optionsObject){for(var key in optionsObject){this.setOption(key,optionsObject[key])}},loadJSONString:function(JSONString){var map=JSON.parse(JSONString);this.loadObject(map)},loadURLString:function(URLString){var map=gs.util.createMapFromURLString(URLString,"game");if(map.options){this.loadJSONString(map.options)}this.loadObject(map)},obfuscationLookup:gs.util.createObfuscationLookup({autoplay:"autoplay",defaultPath:"defaultPath",gamePath:"gamePath",height:"height",loadStrategy:"loadStrategy",logLevel:"logLevel",audio:"audio",renderer:"renderer",scene:"scene",viewportFit:"viewportFit",viewportReference:"viewportReference",viewportScale:"viewportScale",viewportFactor:"viewportFactor",targetRate:"targetRate",drawFactor:"drawFactor",drawFirst:"drawFirst",minFrameDeltaMS:"minFrameDeltaMS",maxFrameDeltaMS:"maxFrameDeltaMS",maxFrameDebtMS:"maxFrameDebtMS",hitchFrameMS:"hitchFrameMS",hitchWindowMS:"hitchWindowMS",width:"width",zoom:"zoom"})};gs.RenderContext=function(){this.viewport=new gs.html5.Viewport;this.renderer=gs.RendererOption.DETECT;this.window=window;this.windowInnerWidth=0;this.windowInnerHeight=0;this.init()};gs.RenderContext.prototype={init:function(){var that=this;this.window.addEventListener("resize",function(event){gs.RenderContext.prototype.onWindowResize.call(that,event)},false)},getViewport:function(){return this.viewport},setFrame:function(frameElementOrId){var frameElement=gs.dom.getElement(frameElementOrId);this.viewport.setFrame(frameElement)},setCanvas:function(canvasElementOrId){var canvasElement=gs.dom.getElement(canvasElementOrId);this.viewport.setCanvas(canvasElement)},loadOptions:function(options){this.renderer=options.renderer.toUpperCase();this.viewport.reference=options.viewportReference.toUpperCase();this.viewport.fit=options.viewportFit.toUpperCase();this.viewport.scale=options.viewportScale.toUpperCase();this.viewport.factor=parseFloat(options.viewportFactor)},getRenderer:function(){return this.renderer},onWindowResize:function(event){this.updateWindowSize();this.viewport.relayout()},updateWindowSize:function(){this.windowInnerWidth=this.window.innerWidth;this.windowInnerHeight=this.window.innerHeight;this.viewport.updateWindowSize(this.windowInnerWidth,this.windowInnerHeight)},onGameDimensionsKnown:function(width,height){this.updateWindowSize();this.viewport.updateGameSize(width,height)},redetect:function(){this.updateWindowSize();this.viewport.relayout();this.viewport.show()}};gs.RenderContext.prototype["onGameDimensionsKnown"]=gs.RenderContext.prototype.onGameDimensionsKnown;gs.EngineState={ENGINE_READY:"ENGINE_READY",GAME_LOADING:"GAME_LOADING",GAME_READY:"GAME_READY",SCENE_LOADING:"SCENE_LOADING",PLAYING:"PLAYING",PAUSED:"PAUSED",SUSPENDED:"SUSPENDED",HALTED:"HALTED"};gs.EngineContext=function(){this.options=new gs.EngineOptions;this.state=gs.EngineState.ENGINE_READY;this.delegate=new gs.api.Delegate;this.renderContext=new gs.RenderContext;this.previousSystemTimeMS=Date.now();this.frameDebtMS=0;this.frameCount=0;this.project=null;this.game=null;this.promiseGameReady=new gs.Promise;this.promiseFirstPlay=new gs.Promise;gs.EngineContext.current=this;gs.Log.delegate=this.delegate;this.appendDelegate(gs.LegacyDelegate);this.appendDelegate(this.renderContext);if(gs.debug.profile){this.log=new gs.LogVisualizer;this.renderContext.viewport.appendOverlay(this.log.root);this.appendDelegate(this.log);this.profiler=new gs.ProfilerVisualizer;this.renderContext.viewport.appendOverlay(this.profiler.root);this.appendDelegate(this.profiler)}if(gs.debug.fps){this.fps=new gs.FrameRateVisualizer;this.renderContext.viewport.appendOverlay(this.fps.root);this.appendDelegate(this.fps)}};gs.EngineContext.instance=function(){if(!gs.EngineContext.current){gs.EngineContext.current=new gs.EngineContext}return gs.EngineContext.current};gs.EngineContext.prototype={getRenderContext:function(){return this.renderContext},setGamePath:function(gamePath){this.options.gamePath=gamePath},setRenderFrame:function(elementOrId){this.renderContext.setFrame(elementOrId)},setOptions:function(options){this.options.loadObject(options)},loadOptionsFromURL:function(){var URLString=window.location.search||window.location.hash;this.options.loadURLString(URLString)},appendDelegate:function(delegate){this.delegate.appendDelegate(delegate)},getState:function(){return this.state},changeState:function(newState){this.state=newState},load:function(gamePath){if(this.state===gs.EngineState.ENGINE_READY){if(gamePath!==null&amp;&amp;gamePath!==undefined){this.setGamePath(gamePath)}this.beginLoading();var that=this;this.project.promiseGameReady.then(function(){that.game=gs.Game.instance;that.changeState(gs.EngineState.GAME_READY);that.promiseGameReady.resolve()})}return this.promiseGameReady},beginLoading:function(){this.options.normalize();this.renderContext.loadOptions(this.options);gs.AudioManager.init(this.options.audio.toUpperCase());this.changeState(gs.EngineState.GAME_LOADING);gs.LocalStorage.setPrefix(gs.LOCAL_STORAGE_KEY_PREFIX);var analyticsService=gs.platform.AnalyticsService.instance();analyticsService.beginSession();var viewport=this.renderContext.getViewport();var renderTarget={canvas:viewport.drawBuffer.canvas,webgl:viewport.drawBuffer.canvas,input:viewport.input};var path;if(this.options.gamePath!==null&amp;&amp;this.options.gamePath!==undefined){path=this.options.gamePath}else{path=this.options.defaultPath}this.project=new gs.Project;this.project.load(path,renderTarget)},play:function(gamePath){var engine=this;switch(this.state){case gs.EngineState.ENGINE_READY:case gs.EngineState.GAME_LOADING:engine.load(gamePath).then(function(){engine.play()});break;case gs.EngineState.GAME_READY:this.relayout();this.project.play();this.changeState(gs.EngineState.PLAYING);this.promiseFirstPlay.resolve();break;case gs.EngineState.PLAYING:break;case gs.EngineState.HALTED:break;case gs.EngineState.SCENE_LOADING:break;case gs.EngineState.PAUSED:return this.unpause();break;case gs.EngineState.SUSPENDED:return this.unsuspend();break;default:break}return this.promiseFirstPlay},pause:function(){var promise=new gs.Promise;var state=this.getState();if(state!==gs.EngineState.PAUSED&amp;&amp;state!==gs.EngineState.SUSPENDED){this.game.interceptKeyEvents=false;this.game.eventCenter.postEvent("systemPause",null);this.project.stopGameLoop();this.changeState(gs.EngineState.PAUSED)}promise.resolve();return promise},unpause:function(){var promise=new gs.Promise;var state=this.getState();if(state===gs.EngineState.PAUSED){this.project.play();this.changeState(gs.EngineState.PLAYING)}promise.resolve();return promise},suspend:function(){var promise=new gs.Promise;var state=this.getState();if(state!==gs.EngineState.SUSPENDED){this.endSession()}this.pause();this.changeState(gs.EngineState.SUSPENDED);promise.resolve();return promise},unsuspend:function(){var promise=new gs.Promise;var state=this.getState();if(state===gs.EngineState.SUSPENDED){this.beginSession();this.project.play();this.changeState(gs.EngineState.PLAYING)}promise.resolve();return promise},relayout:function(){try{this.renderContext.redetect();if(this.game){this.game.redetectInputCoordinates();this.game.updateGraphicsDimensions()}}catch(exception){}},halt:function(){var promise=new gs.Promise;if(this.game.gameTimebase){this.game.stop(this.game.gameTimebase.nextTimestamp(gs.TIME_STEP_MS));if(this.project.gameLoopIsRunning()){this.project.stopGameLoop()}this.game.gameTimebase=null;this.game.isPlaying=false}promise.resolve();return promise},reset:function(){var promise=new gs.Promise;this.game.eventCenter.postEvent("resetGame",null);this.project.play();promise.resolve();return promise},resetLocalStorage:function(){var storedData=gs.LocalStorage.getAll();for(var key in storedData){gs.LocalStorage.setString(key,null)}},resetScene:function(){var promise=new gs.Promise;promise.resolve();return promise},changeScene:function(scene){var promise=new gs.Promise;var project=this.project;if(!project._readyToPlay){project._changeSceneQueued=scene}else{var game=project.game;var currentScene=game.getCurrentScene();var currentSceneIndex=0;if(currentScene){currentSceneIndex=game.scenes.indexAndKey(currentScene._objectKey)}var lastSceneIndex=game.scenes.numberOfScenes()-1;var newSceneIndex;if(typeof scene==="number"){scene=game.scenes.keyForScene(scene)}else if(scene==="first"){scene=game.scenes.keyForScene(0)}else if(scene==="next"){newSceneIndex=currentSceneIndex+1;if(newSceneIndex&gt;lastSceneIndex){newSceneIndex=0}scene=game.scenes.keyForScene(newSceneIndex)}else if(scene==="prev"){newSceneIndex=currentSceneIndex-1;if(newSceneIndex&lt;0){newSceneIndex=lastSceneIndex}scene=game.scenes.keyForScene(newSceneIndex)}game.eventCenter.postEvent("changeToScene",null,scene,false);project.play()}promise.resolve();return promise},postEvent:function(name){this.project.game.eventCenter.postEvent.apply(this.project.game.eventCenter,arguments)},getCurrentSceneKey:function(){if(!this.game){return null}return this.game.getCurrentSceneKey()},beginSession:function(){var analyticsService=gs.platform.AnalyticsService.instance();analyticsService.beginSession()},endSession:function(){var analyticsService=gs.platform.AnalyticsService.instance();analyticsService.endSession()},update:function(){var game=this.game;if(game.isWaitingOnKeyboardInput){return}var systemTimeMS=this.getSystemTimeMS();var trueDeltaMS=systemTimeMS-this.previousSystemTimeMS;var deltaMS=trueDeltaMS;var lostTimeMS=0;if(deltaMS&lt;this.options.minFrameDeltaMS){return}if(deltaMS&gt;this.options.hitchFrameMS){var idealMS=this.options.idealFrameMS;lostTimeMS=deltaMS-idealMS;game.gameTimebase.base+=lostTimeMS;deltaMS=idealMS;if(this.fps&amp;&amp;!game.loadingFlag&amp;&amp;!game.firstFrameAfterLoading){this.fps.hitch(lostTimeMS,this.options.hitchWindowMS)}}else if(deltaMS&gt;this.options.maxFrameDeltaMS){this.frameDebtMS+=deltaMS-this.options.maxFrameDeltaMS;if(this.frameDebtMS&gt;this.options.maxFrameDebtMS){lostTimeMS=this.options.maxFrameDeltaMS-this.frameDebtMS;this.frameDebtMS=this.options.maxFrameDebtMS;game.gameTimebase.base+=lostTimeMS}deltaMS=this.options.maxFrameDeltaMS}else{var disposableIncomeMS=this.options.maxFrameDeltaMS-deltaMS;if(disposableIncomeMS&lt;this.frameDebtMS){deltaMS+=disposableIncomeMS;this.frameDebtMS-=disposableIncomeMS}else{deltaMS+=this.frameDebtMS;this.frameDebtMS=0}}if(this.fps){this.fps.deltaMS=deltaMS;this.fps.trueDeltaMS=trueDeltaMS}var deltaS=deltaMS/1e3;this.previousSystemTimeMS=systemTimeMS;if(game.gameTimebase){game.frameProfiler.frame.tick();game.frameProfiler.engine.enter();game.entityCounter.reset();if(this.options.drawFirst){this.draw();this.simulate(deltaS)}else{this.simulate(deltaS);this.draw()}this.frameCount++;game.entityCounter.contacts.set(gs.ContactListener.getContactCount());game.entityCounter.textures.set(gs.AssetManager.current.getImageCount());game.frameProfiler.engine.exit();game.frameProfiler.profile.enter();this.delegate.onProfilerFrame(game.frameProfiler.getReading(),game.entityCounter.getReading(),game.project.gameLoadProfiler.getReading(),game.sceneLoadProfiler.getReading());game.frameProfiler.profile.exit();if(gs.afterNextFrameCallbacks){for(var i=0,end=gs.afterNextFrameCallbacks.length;i&lt;end;i++){var callback=gs.afterNextFrameCallbacks[i];callback&amp;&amp;callback.call(null)}gs.afterNextFrameCallbacks.length=0}}},draw:function(){var game=this.game;game.frameProfiler.render.enter();if(gs.debug.render){if(this.frameCount%this.options.drawFactor===0){game.render()}}game.frameProfiler.render.exit()},simulate:function(deltaS){var game=this.game;if(gs.debug.evaluate){game.evaluate(game.gameTimebase.nextTimestamp(deltaS))}},resetFrameTime:function(){var systemTimeMS=this.getSystemTimeMS();var gameTimebase=this.game.gameTimebase;if(gameTimebase){var gameTimeS=gameTimebase.currentTimeStamp.time;gameTimebase.base=systemTimeMS/1e3-gameTimeS;gameTimebase.currentTimeStamp.base=gameTimebase.base;gameTimebase.currentTimeStamp.dt=0}this.frameDebtMS=0;this.previousSystemTimeMS=systemTimeMS},getSystemTimeMS:function(){return Date.now()},getSimulationTimeS:function(){return(this.getSystemTimeMS()-this.frameDebtMS)/1e3},waitAfterNextFrame:function(){var promise=new gs.Promise;if(!gs.afterNextFrameCallbacks){gs.afterNextFrameCallbacks=[]}gs.afterNextFrameCallbacks.push(function(){promise.resolve()});return promise},getVolume:function(){return gs.AudioManager.current.getMasterVolume()},setVolume:function(volume){gs.AudioManager.current.setMasterVolume(volume)},zoom:function(factor){var viewport=this.renderContext.getViewport();viewport.setZoom(factor)},showOverlay:function(){var viewport=this.renderContext.getViewport();viewport.showOverlayLayer()},hideOverlay:function(){var viewport=this.renderContext.getViewport();viewport.hideOverlayLayer()},getMetadataForAllScenes:function(){var promise=new gs.Promise;var project=this.project;project.preloadAllScenes(function(scenes){var metadatas=[];scenes.forEach(function(scene){var sceneKey=scene.id;var metadata={id:sceneKey,key:sceneKey,name:scene.label||sceneKey,screenshot:project.pathResolver.getSceneScreenshotPathByID(sceneKey)};metadatas.push(metadata)});promise.resolve(metadatas)});return promise}};gs.EngineContext.prototype["appendDelegate"]=gs.EngineContext.prototype.appendDelegate;gs.EngineContext.prototype["changeScene"]=gs.EngineContext.prototype.changeScene;gs.EngineContext.prototype["getMetadataForAllScenes"]=gs.EngineContext.prototype.getMetadataForAllScenes;gs.EngineContext.prototype["getVolume"]=gs.EngineContext.prototype.getVolume;gs.EngineContext.prototype["halt"]=gs.EngineContext.prototype.halt;gs.EngineContext.prototype["load"]=gs.EngineContext.prototype.load;gs.EngineContext.prototype["loadOptionsFromURL"]=gs.EngineContext.prototype.loadOptionsFromURL;gs.EngineContext.prototype["pause"]=gs.EngineContext.prototype.pause;gs.EngineContext.prototype["play"]=gs.EngineContext.prototype.play;gs.EngineContext.prototype["reset"]=gs.EngineContext.prototype.reset;gs.EngineContext.prototype["resetScene"]=gs.EngineContext.prototype.resetScene;gs.EngineContext.prototype["setRenderCanvas"]=gs.EngineContext.prototype.setRenderCanvas;gs.EngineContext.prototype["setRenderFrame"]=gs.EngineContext.prototype.setRenderFrame;gs.EngineContext.prototype["setVolume"]=gs.EngineContext.prototype.setVolume;gs.EngineContext.prototype["suspend"]=gs.EngineContext.prototype.suspend;gs.EngineContext.prototype["unpause"]=gs.EngineContext.prototype.unpause;gs.EngineContext.prototype["unsuspend"]=gs.EngineContext.prototype.unsuspend;gs.EngineContext.prototype["waitAfterNextFrame"]=gs.EngineContext.prototype.waitAfterNextFrame;gs.EngineContext.prototype["zoom"]=gs.EngineContext.prototype.zoom;gs.EngineContext.prototype["resetLocalStorage"]=gs.EngineContext.prototype.resetLocalStorage;gs.platform.xport=gs.platform;gs.platform.xport.HashService=function(){this.salt=""};gs.platform.xport.HashService.prototype={init:function(gameData){this.salt=gameData.hash+"691008759"},host:function(url){return true},hash:function(str){var h=0;for(var i=0;i&lt;str.length;i++){var c=str.charCodeAt(i);h=(h&lt;&lt;5)-h+c;h=h&amp;h}return h&amp;2147483647},id:function(hash,id){var h=this.hash(id+this.salt);return h===hash?id:h}};gs.singleton(gs.platform.xport.HashService);gs.platform.xport.PurchaseService=function(){};gs.platform.xport.PurchaseService.prototype={purchaseItem:function(itemInfo){var purchasePromise=gs.EngineContext.current.delegate.onIAPBuyItem(itemInfo);if(purchasePromise){purchasePromise.then(function(resp){if(resp.purchaseComplete){gs.Game.current.eventCenter.postEvent("IAPSuccess")}else if(!resp.purchaseComplete&amp;&amp;resp.buyerCancelled){gs.Game.current.eventCenter.postEvent("IAPCancelled")}else{gs.Game.current.eventCenter.postEvent("IAPFailure",null,response.error)}}).catch(function(err){gs.Game.current.eventCenter.postEvent("IAPFailure",null,err)})}else{gs.Game.current.eventCenter.postEvent("IAPSuccess")}},restoreItems:function(){var restorePromise=gs.EngineContext.current.delegate.onIAPRestoreItems();if(restorePromise){restorePromise.then(function(purchases){gs.Game.current.eventCenter.postEvent("IAPRestoreSuccess",null,purchases)}).catch(function(err){gs.Game.current.eventCenter.postEvent("IAPRestoreFailure",null,err)})}else{var emptyList=gs.array.provide();gs.Game.current.eventCenter.postEvent("IAPRestoreSuccess",null,emptyList)}},consumeItem:function(itemID){var consumePromise=gs.EngineContext.current.delegate.onIAPConsumeItem(itemID);if(consumePromise){consumePromise.then(function(){gs.Game.current.eventCenter.postEvent("IAPConsumeItemSuccess")}).catch(function(err){gs.Game.current.eventCenter.postEvent("IAPConsumeItemFailure",null,err)})}else{gs.Game.current.eventCenter.postEvent("IAPConsumeItemSuccess")}},requestPurchaseData:function(){var itemDataPromise=gs.EngineContext.current.delegate.onIAPRequestPurchaseData();if(itemDataPromise){itemDataPromise.then(function(itemData){gs.Game.current.eventCenter.postEvent("IAPPurchaseDataRequestSuccess",null,itemData)}).catch(function(err){gs.Game.current.eventCenter.postEvent("IAPPurchaseDataRequestFailure",null,err)})}else{var emptyList=gs.array.provide();gs.Game.current.eventCenter.postEvent("IAPPurchaseDataRequestSuccess",null,emptyList)}}};gs.singleton(gs.platform.xport.PurchaseService);(function(global){gs.version.platform="export";gs.Log.level=gs.Log.LogLevel.WARN;gs.globalOptions.format=gs.file.Format.JSONP;gs.globalOptions.crossOriginImageLoading=true;var userAgent=navigator.userAgent;if(/MSIE/.test(userAgent)){gs.globalOptions.forceInputEventsOnCanvas=true}})(window);gs.version.revision="023e5d57131379b16db054bf32719cdb74d3fa04";gs.version.date="2023-05-09T18:32:01";</pre></body></html>