diff --git a/package-lock.json b/package-lock.json index 5bfe9ed6..d5a49e9b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -30,7 +30,7 @@ "devDependencies": { "@babel/core": "^7.18.5", "@babel/eslint-parser": "^7.18.2", - "@types/node": "^17.0.43", + "@types/node": "^18.0.0", "@typescript-eslint/eslint-plugin": "^5.28.0", "@typescript-eslint/parser": "^5.28.0", "cross-env": "^7.0.3", @@ -511,9 +511,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "17.0.43", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.43.tgz", - "integrity": "sha512-jnUpgw8fL9kP2iszfIDyBQtw5Mf4/XSqy0Loc1J9pI14ejL83XcCEvSf50Gs/4ET0I9VCCDoOfufQysj0S66xA==", + "version": "18.0.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", + "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==", "dev": true }, "node_modules/@typescript-eslint/eslint-plugin": { @@ -5334,9 +5334,9 @@ "dev": true }, "@types/node": { - "version": "17.0.43", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.43.tgz", - "integrity": "sha512-jnUpgw8fL9kP2iszfIDyBQtw5Mf4/XSqy0Loc1J9pI14ejL83XcCEvSf50Gs/4ET0I9VCCDoOfufQysj0S66xA==", + "version": "18.0.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", + "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==", "dev": true }, "@typescript-eslint/eslint-plugin": { diff --git a/package.json b/package.json index 71ba4f64..dd21a9f9 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ "devDependencies": { "@babel/core": "^7.18.5", "@babel/eslint-parser": "^7.18.2", - "@types/node": "^17.0.43", + "@types/node": "^18.0.0", "@typescript-eslint/eslint-plugin": "^5.28.0", "@typescript-eslint/parser": "^5.28.0", "cross-env": "^7.0.3", diff --git a/server/ServerConfig.js b/server/ServerConfig.js index aad2233d..340cda1f 100644 --- a/server/ServerConfig.js +++ b/server/ServerConfig.js @@ -14,6 +14,7 @@ var defaultConfig = [ { name: 'TriggerComponent', path: '../src/gameClasses/components/script/TriggerComponent' }, { name: 'ConditionComponent', path: '../src/gameClasses/components/script/ConditionComponent' }, + { name: 'SwitchComponent', path: '../src/gameClasses/components/script/SwitchComponent' }, { name: 'ActionComponent', path: '../src/gameClasses/components/script/ActionComponent' }, { name: 'VariableComponent', path: '../src/gameClasses/components/script/VariableComponent' }, diff --git a/server/server.js b/server/server.js index 42c582e4..8b2bb119 100644 --- a/server/server.js +++ b/server/server.js @@ -498,6 +498,7 @@ var Server = IgeClass.extend({ ige.addComponent(GameTextComponent); ige.addComponent(ScriptComponent); ige.addComponent(ConditionComponent); + ige.addComponent(SwitchComponent); ige.addComponent(ActionComponent); ige.addComponent(AdComponent); ige.addComponent(SoundComponent); diff --git a/src/client.js b/src/client.js index c2777343..989b2d0b 100644 --- a/src/client.js +++ b/src/client.js @@ -911,6 +911,7 @@ const Client = IgeEventingClass.extend({ // ige.addComponent(VariableComponent); // this appears twice ige.addComponent(ScriptComponent); ige.addComponent(ConditionComponent); + ige.addComponent(SwitchComponent); ige.addComponent(ActionComponent); if (typeof mode == 'string' && mode == 'sandbox') { diff --git a/src/game.js b/src/game.js index 7da4f0ff..248b8955 100644 --- a/src/game.js +++ b/src/game.js @@ -1 +1 @@ -function printStackTrace(options){options=options||{guess:true};var ex=options.e||null;var guess=!!options.guess;var p=new printStackTrace.implementation;var result=p.run(ex);var res=guess?p.guessAnonymousFunctions(result):result;for(var k=0;k<4;k++){res.shift()}return res}printStackTrace.implementation=function(){};printStackTrace.implementation.prototype={run:function(ex){ex=ex||this.createException();var mode=this.mode(ex);if(mode==="other"){return this.other(arguments.callee)}else{return this[mode](ex)}},createException:function(){try{this.undef();return null}catch(e){return e}},mode:function(e){if(e.arguments&&e.stack){return this._mode="chrome"}else if(e.message&&typeof window!=="undefined"&&window.opera){return this._mode=e.stacktrace?"opera10":"opera"}else if(e.stack){return this._mode="firefox"}return this._mode="other"},instrumentFunction:function(context,functionName,callback){context=context||window;var original=context[functionName];context[functionName]=function instrumented(){callback.call(this,printStackTrace().slice(4));return context[functionName]._instrumented.apply(this,arguments)};context[functionName]._instrumented=original},deinstrumentFunction:function(context,functionName){if(context[functionName].constructor===Function&&context[functionName]._instrumented&&context[functionName]._instrumented.constructor===Function){context[functionName]=context[functionName]._instrumented}},chrome:function(e){var stack=`${e.stack}\n`.replace(/^\S[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^([^\(]+?)([\n$])/gm,"{anonymous}()@$1$2").replace(/^Object.\s*\(([^\)]+)\)/gm,"{anonymous}()@$1").split("\n");stack.pop();return stack},firefox:function(e){return e.stack.replace(/(?:\n@:0)?\s+$/m,"").replace(/^\(/gm,"{anonymous}(").split("\n")},opera10:function(e){var stack=e.stacktrace;var lines=stack.split("\n");var ANON="{anonymous}";var lineRE=/.*line (\d+), column (\d+) in ((/g,ANON);lines[j++]=`${fnName}@${location}`}}lines.splice(j,lines.length-j);return lines},opera:function(e){var lines=e.message.split("\n");var ANON="{anonymous}";var lineRE=/Line\s+(\d+).*script\s+(http\S+)(?:.*in\s+function\s+(\S+))?/i;var i;var j;var len;for(i=4,j=0,len=lines.length;i-1){this.splice(index,1);return index}else{return-1}};Object.defineProperty(Array.prototype,"pushUnique",{enumerable:false,writable:true,configurable:true});Array.prototype.pushUnique=function(item){var index=this.indexOf(item);if(index===-1){this.push(item);return true}return false};Object.defineProperty(Array.prototype,"each",{enumerable:false,writable:true,configurable:true});Array.prototype.each=function(callback){var len=this.length;var i;for(i=0;i=0;i--){callback(this[i])}};Object.defineProperty(Array.prototype,"destroyAll",{enumerable:false,writable:true,configurable:true});Array.prototype.destroyAll=function(){var arrCount=this.length;var i;for(i=arrCount-1;i>=0;i--){if(typeof this[i].destroy==="function"){this[i].destroy()}}};Object.defineProperty(Array.prototype,"eachIsolated",{enumerable:false,writable:true,configurable:true});Array.prototype.eachIsolated=function(callback){var arr=[];var arrCount=arr.length;var i;for(i=0;i1){if(extensionArray&&extensionArray.length){for(extensionIndex=0;extensionIndex-1){addListener=false}if(addListener){elArr.push(newListener)}return newListener}else{if(eventName.length){multiEvent=[];multiEvent[0]=0;multiEvent[1]=0;multiEvent[3]=function(firedEventName){multiEvent[1]++;if(multiEvent[0]===multiEvent[1]){call.apply(context||self)}};for(eventIndex in eventName){if(eventName.hasOwnProperty(eventIndex)){eventData=eventName[eventIndex];eventObj=eventData[0];multiEventName=eventData[1];multiEvent[0]++;eventObj.on(multiEventName,multiEvent[3],null,true,true)}}}}}else{if(typeof eventName!=="string"){eventName="*Multi-Event*"}this.log(`Cannot register event listener for event "${eventName}" because the passed callback is not a function!`,"error")}},off:function(eventName,evtListener,callback){if(this._eventListeners){if(!this._eventListeners._processing){if(this._eventListeners[eventName]){var evtListIndex=this._eventListeners[eventName].indexOf(evtListener);if(evtListIndex>-1){this._eventListeners[eventName].splice(evtListIndex,1);if(callback){callback(true)}return true}else{this.log(`Failed to cancel event listener for event named "${eventName}" !`,"warning",evtListener)}}else{this.log("Failed to cancel event listener!")}}else{this._eventListeners._removeQueue=this._eventListeners._removeQueue||[];this._eventListeners._removeQueue.push([eventName,evtListener,callback]);return-1}}if(callback){callback(false)}return false},emit:function(eventName,args){if(this._eventListeners){if(this._eventListeners[eventName]){var eventCount=this._eventListeners[eventName].length;var eventCount2=this._eventListeners[eventName].length-1;var finalArgs;var i;var cancelFlag;var eventIndex;var tempEvt;var retVal;if(eventCount){finalArgs=[];if(typeof args==="object"&&args!==null&&args[0]!==null&&args[0]!==undefined){for(i in args){if(args.hasOwnProperty(i)){finalArgs[i]=args[i]}}}else{finalArgs=[args]}cancelFlag=false;this._eventListeners._processing=true;while(eventCount--){eventIndex=eventCount2-eventCount;tempEvt=this._eventListeners[eventName][eventIndex];if(tempEvt.sendEventName){finalArgs=[eventName]}retVal=tempEvt.call.apply(tempEvt.context||this,finalArgs);if(retVal===true){cancelFlag=true}if(tempEvt.oneShot){if(this.off(eventName,tempEvt)===true){eventCount2--}}}if(this._eventListeners){this._eventListeners._processing=false;this._processRemovals()}if(cancelFlag){return 1}}}}},eventList:function(){return this._eventListeners},_processRemovals:function(){if(this._eventListeners){var remArr=this._eventListeners._removeQueue;var arrCount;var item;var result;if(remArr){arrCount=remArr.length;while(arrCount--){item=remArr[arrCount];result=this.off(item[0],item[1]);if(typeof remArr[2]==="function"){remArr[2](result)}}}delete this._eventListeners._removeQueue}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_3}var $i_4=$i_2.extend({classId:"$i_4",init:function(x,y,floor){this.x=x=x!==undefined?x:0;this.y=y=y!==undefined?y:0;this._floor=floor!==undefined;if(this._floor){this.x2=Math.floor(x/2);this.y2=Math.floor(y/2)}else{this.x2=x/2;this.y2=y/2}return this},floor:function(val){if(val!==undefined){this._floor=val;return this}return this._floor},compare:function(point){return point&&this.x===point.x&&this.y===point.y},copy:function(point){this.x=point.x;this.y=point.y;this.z=point.z;return this},toIso:function(){var sx=this.x-this.y;var sy=(this.x+this.y)*0.5;return{x:sx,y:sy}},thisToIso:function(){var val=this.toIso();this.x=val.x;this.y=val.y;return this},to2d:function(){var sx=this.y+this.x/2;var sy=this.y-this.x/2;return{x:sx,y:sy}},thisTo2d:function(){var val=this.to2d();this.x=val.x;this.y=val.y;return this},addPoint:function(point){return new $i_4(this.x+point.x,this.y+point.y)},thisAddPoint:function(point){this.x+=point.x;this.y+=point.y;return this},minusPoint:function(point){return new $i_4(this.x-point.x,this.y-point.y)},thisMinusPoint:function(point){this.x-=point.x;this.y-=point.y;return this},multiply:function(x,y){return new $i_4(this.x*x,this.y*y)},multiplyPoint:function(point){return new $i_4(this.x*point.x,this.y*point.y)},thisMultiply:function(x,y){this.x*=x;this.y*=y;return this},divide:function(x,y){return new $i_4(this.x/x,this.y/y)},dividePoint:function(point){var newX=this.x;var newY=this.y;if(point.x){newX=this.x/point.x}if(point.y){newY=this.y/point.y}return new $i_4(newX,newY)},thisDivide:function(x,y){this.x/=x;this.y/=y;return this},clone:function(){return new $i_4(this.x,this.y)},interpolate:function(endPoint,startTime,currentTime,endTime){var totalX=endPoint.x-this.x;var totalY=endPoint.y-this.y;var totalTime=endTime-startTime;var deltaTime=totalTime-(currentTime-startTime);var timeRatio=deltaTime/totalTime;return new $i_4(endPoint.x-totalX*timeRatio,endPoint.y-totalY*timeRatio)},rotate:function(radians){var s=Math.sin(radians);var c=Math.cos(radians);var x=c*this.x-s*this.y;var y=s*this.x-c*this.y;return new $i_4(x,y)},thisRotate:function(radians){var s=Math.sin(radians);var c=Math.cos(radians);var x=this.x;var y=this.y;this.x=c*x-s*y;this.y=s*x-c*y;return this},toString:function(precision){if(precision===undefined){precision=2}if(this.x==undefined||this.y==undefined){return"0,0"}return`${parseFloat(this.x).toFixed(precision)},${parseFloat(this.y).toFixed(precision)}`}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_4}var $i_5=$i_2.extend({classId:"$i_5",init:function(x,y,z,floor){this.x=x=x!==undefined?x:0;this.y=y=y!==undefined?y:0;this.z=z=z!==undefined?z:0;this._floor=floor!==undefined;if(this._floor){this.x2=Math.floor(x/2);this.y2=Math.floor(y/2);this.z2=Math.floor(z/2)}else{this.x2=x/2;this.y2=y/2;this.z2=z/2}return this},floor:function(val){if(val!==undefined){this._floor=val;return this}return this._floor},compare:function(point){return point&&this.x===point.x&&this.y===point.y&&this.z===point.z},copy:function(point){this.x=point.x;this.y=point.y;this.z=point.z;return this},toIso:function(){var sx=this.x-this.y;var sy=-this.z*1.2247+(this.x+this.y)*0.5;return{x:sx,y:sy}},thisToIso:function(){var val=this.toIso();this.x=val.x;this.y=val.y;return this},to2d:function(){var sx=this.y+this.x/2;var sy=this.y-this.x/2;return{x:sx,y:sy}},thisTo2d:function(){var val=this.to2d();this.x=val.x;this.y=val.y;this.z=0;return this},addPoint:function(point){return new $i_5(this.x+point.x,this.y+point.y,this.z+point.z)},thisAddPoint:function(point){this.x+=point.x;this.y+=point.y;this.z+=point.z;return this},minusPoint:function(point){return new $i_5(this.x-point.x,this.y-point.y,this.z-point.z)},thisMinusPoint:function(point){this.x-=point.x;this.y-=point.y;this.z-=point.z;return this},multiply:function(x,y,z){return new $i_5(this.x*x,this.y*y,this.z*z)},multiplyPoint:function(point){return new $i_5(this.x*point.x,this.y*point.y,this.z*point.z)},thisMultiply:function(x,y,z){this.x*=x;this.y*=y;this.z*=z;return this},divide:function(x,y,z){return new $i_5(this.x/x,this.y/y,this.z/z)},dividePoint:function(point){var newX=this.x;var newY=this.y;var newZ=this.z;if(point.x){newX=this.x/point.x}if(point.y){newY=this.y/point.y}if(point.z){newZ=this.z/point.z}return new $i_5(newX,newY,newZ)},thisDivide:function(x,y,z){this.x/=x;this.y/=y;this.z/=z;return this},clone:function(){return new $i_5(this.x,this.y,this.z)},interpolate:function(endPoint,startTime,currentTime,endTime){var totalX=endPoint.x-this.x;var totalY=endPoint.y-this.y;var totalZ=endPoint.z-this.z;var totalTime=endTime-startTime;var deltaTime=totalTime-(currentTime-startTime);var timeRatio=deltaTime/totalTime;return new $i_5(endPoint.x-totalX*timeRatio,endPoint.y-totalY*timeRatio,endPoint.z-totalZ*timeRatio)},rotate:function(radians){var s=Math.sin(radians);var c=Math.cos(radians);var x=c*this.x-s*this.y;var y=s*this.x-c*this.y;return new $i_5(x,y,this.z)},thisRotate:function(radians){var s=Math.sin(radians);var c=Math.cos(radians);var x=this.x;var y=this.y;this.x=c*x-s*y;this.y=s*x-c*y;return this},toString:function(precision){if(precision===undefined){precision=2}if(this.x==undefined||this.y==undefined||this.z==undefined){return"0,0,0"}return`${parseFloat(this.x).toFixed(precision)},${parseFloat(this.y).toFixed(precision)},${parseFloat(this.z).toFixed(precision)}`}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_5}var $i_6=$i_2.extend({classId:"$i_6",init:function(){this._poly=[];this._scale=new $i_4(1,1)},scale:function(x,y){if(x!==undefined&&y!==undefined){this._scale.x=x;this._scale.y=y;return this}return this._scale},multiply:function(factor){if(factor!==undefined){var polyPoints=this._poly;var pointCount=polyPoints.length;var pointIndex;for(pointIndex=0;pointIndexpoint.y!==polyPoints[oldPointIndex].y>point.y&&point.x<(polyPoints[oldPointIndex].x-polyPoints[pointIndex].x)*(point.y-polyPoints[pointIndex].y)/(polyPoints[oldPointIndex].y-polyPoints[pointIndex].y)+polyPoints[pointIndex].x){c=!c}}return Boolean(c)},xyInside:function(x,y){var polyPoints=this._poly;var pointCount=polyPoints.length;var pointIndex;var oldPointIndex=pointCount-1;var c=0;for(pointIndex=0;pointIndexy!==polyPoints[oldPointIndex].y>y&&x<(polyPoints[oldPointIndex].x-polyPoints[pointIndex].x)*(y-polyPoints[pointIndex].y)/(polyPoints[oldPointIndex].y-polyPoints[pointIndex].y)+polyPoints[pointIndex].x){c=!c}}return Boolean(c)},aabb:function(){var minX;var minY;var maxX;var maxY;var xArr=[];var yArr=[];var arr=this._poly;var arrIndex;var arrCount=arr.length;for(arrIndex=0;arrIndex0},makeClockWiseTriangle:function(){if(!this.clockWiseTriangle()){var p0=this._poly[0];var p1=this._poly[1];var p2=this._poly[2];this._poly[2]=p1;this._poly[1]=p2}},triangulate:function(){var poly=this._poly;var triangles=[];var indices=this.triangulationIndices();var i;var point1;var point2;var point3;var newPoly;for(i=0;i0){for(v=0;v2;){if(count--<=0){return indices}u=v;if(nv<=u){u=0}v=u+1;if(nv<=v){v=0}w=v+1;if(nv<=w){w=0}if(this._snip(u,v,w,nv,V)){a=V[u];b=V[v];c=V[w];indices.push(a);indices.push(b);indices.push(c);m++;s=v;for(t=v+1;t=0&&bCROSScp>=0&&cCROSSap>=0},render:function(ctx,fill){var polyPoints=this._poly;var pointCount=polyPoints.length;var scaleX=this._scale.x;var scaleY=this._scale.y;var i;ctx.beginPath();ctx.moveTo(polyPoints[0].x*scaleX,polyPoints[0].y*scaleY);for(i=1;i=this.x&&y>this.y&&x<=this.x+this.width&&y<=this.y+this.height},pointInside:function(point){return point.x>=this.x&&point.y>this.y&&point.x<=this.x+this.width&&point.y<=this.y+this.height},rectIntersect:function(rect){this.log("rectIntersect has been renamed to \"intersects\". Please update your code. rectIntersect will be removed in a later version of IGE.","warning");return this.intersects(rect)},intersects:function(rect){if(rect){var sX1=this.x;var sY1=this.y;var sW=this.width;var sH=this.height;var dX1=rect.x;var dY1=rect.y;var dW=rect.width;var dH=rect.height;var sX2=sX1+sW;var sY2=sY1+sH;var dX2=dX1+dW;var dY2=dY1+dH;if(sX1dX1&&sY1dY1){return true}}return false},multiply:function(x1,y1,x2,y2){return new $i_7(this.x*x1,this.y*y1,this.width*x2,this.height*y2)},thisMultiply:function(x1,y1,x2,y2){this.x*=x1;this.y*=y1;this.width*=x2;this.height*=y2;return this},clone:function(){return new $i_7(this.x,this.y,this.width,this.height)},toString:function(precision){if(precision===undefined){precision=2}return`${this.x.toFixed(precision)},${this.y.toFixed(precision)},${this.width.toFixed(precision)},${this.height.toFixed(precision)}`},render:function(ctx,fill){ctx.rect(this.x,this.y,this.width,this.height);if(fill){ctx.fill()}ctx.stroke();return this}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_7}var $i_8=function(){this.matrix=[1,0,0,0,1,0,0,0,1];this._rotateOrigin=new $i_5(0,0,0);this._scaleOrigin=new $i_5(0,0,0)};$i_8.prototype={matrix:null,transformCoord:function(point,obj){var x=point.x;var y=point.y;var tm=this.matrix;point.x=x*tm[0]+y*tm[1]+tm[2];point.y=x*tm[3]+y*tm[4]+tm[5];if(isNaN(tm[0])||isNaN(tm[1])||isNaN(tm[2])||isNaN(tm[3])||isNaN(tm[4])||isNaN(tm[5])){ige.script.errorLog("The matrix operation produced a NaN value!")}return point},transformCoordInverse:function(point,obj){var x=point.x;var y=point.y;var tm=this.matrix;point.x=x*tm[0]-y*tm[1]+tm[2];point.y=x*tm[3]+y*tm[4]-tm[5];if(isNaN(tm[0])||isNaN(tm[1])||isNaN(tm[2])||isNaN(tm[3])||isNaN(tm[4])||isNaN(tm[5])){}return point},transform:function(points,obj){var pointIndex;var pointCount=points.length;for(pointIndex=0;pointIndexanim.totalTime){if(!anim.loop){if(self._completeCallback){self._completeCallback.call(self,anim)}self.emit("complete",anim);self.stop()}else{if(anim.loop===-1){multiple=anim.currentDelta/anim.totalTime;if(Math.abs(multiple)>1){anim.currentDelta-=(multiple|0)*anim.totalTime}if(self._loopCallback){self._loopCallback.call(self,anim)}self.emit("loopComplete",anim)}else{anim.currentLoop++;if(anim.loop>0&&anim.currentLoop<=anim.loop){multiple=anim.currentDelta/anim.totalTime;if(Math.abs(multiple)>1){anim.currentDelta-=(multiple|0)*anim.totalTime}if(self._loopCallback){self._loopCallback.call(self,anim)}self.emit("loopComplete",anim)}else{if(self._completeCallback){self._completeCallback.call(self,anim)}self.emit("complete",anim);self.stop()}}}}frame=anim.currentDelta/anim.frameTime|0;if(frame>=anim.frameCount){frame=anim.frameCount-1}cell=anim.frames[frame];if(typeof cell==="string"){self._entity.cellById(cell)}else{self._entity.cell(cell)}}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_10}var $i_11=$i_2.extend({classId:"$i_11",componentId:"velocity",init:function(entity,options){this._entity=entity;this._velocity=new $i_5(0,0,0);this._friction=new $i_5(1,1,1);entity.addBehaviour("velocity",this._behaviour)},_behaviour:function(ctx){if(this.velocity!=undefined)this.velocity.tick(ctx)},byAngleAndPower:function(radians,power,relative){var vel=this._velocity;var x=Math.cos(radians)*power;var y=Math.sin(radians)*power;var z=0;if(!relative){vel.x=x;vel.y=y;vel.z=z}else{vel.x+=x;vel.y+=y;vel.z+=z}return this._entity},xyz:function(x,y,z,relative){var vel=this._velocity;if(!relative){vel.x=x;vel.y=y;vel.z=z}else{vel.x+=x;vel.y+=y;vel.z+=z}return this._entity},x:function(x,relative){var vel=this._velocity;if(!relative){vel.x=x}else{vel.x+=x}return this._entity},y:function(y,relative){var vel=this._velocity;if(!relative){vel.y=y}else{vel.y+=y}return this._entity},z:function(z,relative){var vel=this._velocity;if(!relative){vel.z=y}else{vel.z+=z}return this._entity},vector3:function(vector,relative){if(typeof vector.scale!=="number"){vector.scale=1}var vel=this._velocity;var x=vector.x;var y=vector.y;var z=vector.z;if(!relative){vel.x=x;vel.y=y;vel.z=z}else{vel.x+=x;vel.y+=y;vel.z+=z}return this._entity},friction:function(val){var finalFriction=1-val;if(finalFriction<0){finalFriction=0}this._friction=new $i_5(finalFriction,finalFriction,finalFriction);return this._entity},linearForce:function(degrees,power){power/=1000;var radians=degrees*Math.PI/180;var x=Math.cos(radians)*power;var y=Math.sin(radians)*power;var z=x*y;this._linearForce=new $i_5(x,y,z);return this._entity},linearForceXYZ:function(x,y,z){this._linearForce=new $i_5(x,y,z);return this._entity},linearForceVector3:function(vector,power,relative){var force=this._linearForce=this._linearForce||new $i_5(0,0,0);var x=vector.x/1000;var y=vector.y/1000;var z=vector.z/1000;if(!relative){force.x=x||0;force.y=y||0;force.z=z||0}else{force.x+=x||0;force.y+=y||0;force.z+=z||0}return this._entity},_applyLinearForce:function(delta){if(this._linearForce){var vel=this._velocity;vel.x+=this._linearForce.x*delta;vel.y+=this._linearForce.y*delta;vel.z+=this._linearForce.z*delta}},_applyFriction:function(){var vel=this._velocity;var fric=this._friction;vel.x*=fric.x;vel.y*=fric.y;vel.z*=fric.z},tick:function(ctx){var delta=ige._tickDelta;var vel=this._velocity;var x;var y;var z;if(delta){this._applyLinearForce(delta);x=vel.x*delta;y=vel.y*delta;z=vel.z*delta;if(x||y||z){this._entity.translateBy(x,y,z)}}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_11}var $i_12=$i_2.extend({classId:"$i_12",componentId:"tween",init:function(entity,options){this._entity=entity;this._transform=entity.transform;this._tweens=[];entity.addBehaviour("tween",this.update)},start:function(tween){if(tween._startTime>ige._currentTime){this._tweens.push(tween)}else{tween._currentStep=0;if(this._setupStep(tween,false)){this._tweens.push(tween)}}this.enable();return tween},_setupStep:function(tween,newTime){var targetObj=tween._targetObj;var step=tween._steps[tween._currentStep];var propertyNameAndValue;var durationMs;var endTime;var easing;var propertyIndex;var targetData=[];if(step){propertyNameAndValue=step.props}if(targetObj){if(tween._currentStep===0&&!newTime){if(tween._startTime===undefined){tween._startTime=ige._currentTime}}else{tween._startTime=ige._currentTime}durationMs=step.durationMs?step.durationMs:tween._durationMs;tween._selectedEasing=step.easing?step.easing:tween._easing;tween._endTime=tween._startTime+durationMs;for(propertyIndex in propertyNameAndValue){if(propertyNameAndValue.hasOwnProperty(propertyIndex)){targetData.push({targetObj:targetObj,propName:propertyIndex,deltaVal:propertyNameAndValue[propertyIndex]-(step.isDelta?0:targetObj[propertyIndex]),oldDelta:0})}}tween._targetData=targetData;tween._destTime=tween._endTime-tween._startTime;return tween}else{this.log(`Cannot start tweening properties of the specified object "${obj}" because it does not exist!`,"error")}},stop:function(tween){this._tweens.pull(tween);if(!this._tweens.length){this.disable()}return this},stopAll:function(){this.disable();delete this._tweens;this._tweens=[];return this},enable:function(){if(!this._tweening){this._tweening=true}return this},disable:function(){if(this._tweening){this._tweening=false}return this},update:function(ctx){var thisTween=this.tween;if(thisTween._tweens&&thisTween._tweens.length){var currentTime=ige._tickStart;var tweens=thisTween._tweens;var tweenCount=tweens.length;var tween;var deltaTime;var destTime;var easing;var item;var targetProp;var targetPropVal;var targets;var targetIndex;var stepIndex;var stopped;var currentDelta;while(tweenCount--){tween=tweens[tweenCount];stopped=false;if(tween._started||currentTime>=tween._startTime){if(!tween._started){if(tween._currentStep===-1){tween._currentStep=0;thisTween._setupStep(tween,false)}if(typeof tween._beforeTween==="function"){tween._beforeTween(tween);delete tween._beforeTween}if(typeof tween._beforeStep==="function"){if(tween._stepDirection){stepIndex=tween._steps.length-(tween._currentStep+1)}else{stepIndex=tween._currentStep}tween._beforeStep(tween,stepIndex)}tween._started=true}deltaTime=currentTime-tween._startTime;destTime=tween._destTime;easing=tween._selectedEasing;if(deltaTime>=destTime){targets=tween._targetData;for(targetIndex in targets){if(targets.hasOwnProperty(targetIndex)){item=targets[targetIndex];targetProp=item.targetObj;targetPropVal=targetProp[item.propName];if(destTime!==0){currentDelta=thisTween.easing[easing](destTime,item.deltaVal,destTime)}else{currentDelta=item.deltaVal}targetPropVal+=currentDelta-item.oldDelta;var roundingPrecision=Math.pow(10,15-targetPropVal.toFixed(0).toString().length);targetProp[item.propName]=Math.round(targetPropVal*roundingPrecision)/roundingPrecision}}if(typeof tween._afterStep==="function"){if(tween._stepDirection){stepIndex=tween._steps.length-(tween._currentStep+1)}else{stepIndex=tween._currentStep}tween._afterStep(tween,stepIndex)}if(tween._steps.length===tween._currentStep+1){if(tween._repeatMode){if(tween._repeatCount!==-1){tween._repeatedCount++;if(tween._repeatCount===tween._repeatedCount){stopped=true}}if(!stopped){if(tween._repeatMode===1){tween._currentStep=0}if(tween._repeatMode===2){tween._stepDirection=!tween._stepDirection;tween._steps.reverse();tween._currentStep=1}if(typeof tween._stepsComplete==="function"){tween._stepsComplete(tween,tween._currentStep)}if(typeof tween._beforeStep==="function"){if(tween._stepDirection){stepIndex=tween._steps.length-(tween._currentStep+1)}else{stepIndex=tween._currentStep}tween._beforeStep(tween,stepIndex)}thisTween._setupStep(tween,true)}}else{stopped=true}if(stopped){tween.stop();if(typeof tween._afterTween==="function"){tween._afterTween(tween);delete tween._afterTween}}}else{tween._currentStep++;if(typeof tween._beforeStep==="function"){if(tween._stepDirection){stepIndex=tween._steps.length-(tween._currentStep+1)}else{stepIndex=tween._currentStep}tween._beforeStep(tween,stepIndex)}thisTween._setupStep(tween,true)}if(typeof tween._afterChange==="function"){tween._afterChange(tween,stepIndex)}}else{targets=tween._targetData;for(targetIndex in targets){if(targets.hasOwnProperty(targetIndex)){item=targets[targetIndex];var currentDelta=thisTween.easing[easing](deltaTime,item.deltaVal,destTime);item.targetObj[item.propName]+=currentDelta-item.oldDelta;item.oldDelta=currentDelta}}if(typeof tween._afterChange==="function"){tween._afterChange(tween,stepIndex)}}}}}},easing:{none:function(t,c,d){return c*t/d},inQuad:function(t,c,d){return c*(t/=d)*t},outQuad:function(t,c,d){return-c*(t/=d)*(t-2)},inOutQuad:function(t,c,d){if((t/=d/2)<1){return c/2*t*t}return-c/2*(--t*(t-2)-1)},inCubic:function(t,c,d){return c*(t/=d)*t*t},outCubic:function(t,c,d){return c*((t=t/d-1)*t*t+1)},inOutCubic:function(t,c,d){if((t/=d/2)<1){return c/2*t*t*t}return c/2*((t-=2)*t*t+2)},outInCubic:function(t,c,d){if(t0){this._state[this.mouse.wheelUp]=true}else{this._state[this.mouse.wheelDown]=true}this.mouseWheel=event;if(!self.emit("preMouseWheel",[event,mx,my,event.button+1])){this.queueEvent(this,function(){self.emit("mouseWheel",[event,mx,my,event.button+1])})}},_keyDown:function(event){var self=this;this._updateMouseData(event);this._chatHandler(event);if(this._state[event.keyCode]==false){if(ige.game.data.defaultData&&ige.client.selectedUnit){this.lastMovedAt=ige.currentTime()}}this._state[event.keyCode]=true;if(this._debug){console.log("Key Down",event)}if(!self.emit("preKeyDown",[event,event.keyCode])){this.queueEvent(this,function(){self.emit("keyDown",[event,event.keyCode])})}},_chatHandler:function(e){var isChatInputHidden=$("#chat-message-input").css("display")==="none";if(e.keyCode===13){var isModalOpen=$(".modal").hasClass("show");var isMenuVisible=$("#menu-wrapper").is(":visible");if(isChatInputHidden&&!isModalOpen&&!isMenuVisible){var gameData=ige.game&&ige.game.data&&ige.game.data.defaultData;var player=ige.client.myPlayer;if(gameData.allowVerifiedUserToChat&&!player._stats.isUserVerified){$("#message").attr("disabled",true);$("#message").attr("placeholder","Please log in to chat")}$("#chat-message-input").show();setTimeout(function(){$("#message").focus()},0)}else if(!isChatInputHidden&&!isModalOpen){if($("#message").is(":focus")){ige.chat.sendChatMessage()}}else if($("#player-input-field").is(":focus")){$("button#player-input-submit").click()}}else if(e.keyCode===27&&!isChatInputHidden){$("#chat-message-input").hide()}},_keyUp:function(event){var self=this;this._updateMouseData(event);if(this._state[event.keyCode]==true){if(ige.game.data.defaultData&&ige.client.selectedUnit){this.lastMovedAt=ige.currentTime()}}this._state[event.keyCode]=false;if(this._debug){console.log("Key Up",event)}if(!self.emit("preKeyUp",[event,event.keyCode])){this.queueEvent(this,function(){self.emit("keyUp",[event,event.keyCode])})}},_updateMouseData:function(event){if(!event)return;this.lastEvent=event;var resolvedCoordinate={};if(!isNaN(event.igeX)||!isNaN(event.igeY)){this.lastMousePosition.x=event.igeX;this.lastMousePosition.y=event.igeY;resolvedCoordinate.x=event.igeX;resolvedCoordinate.y=event.igeY}else{resolvedCoordinate.x=this.lastMousePosition.x;resolvedCoordinate.y=this.lastMousePosition.y}var arr=ige._children;var arrCount=arr.length;var vp;var vpUpdated;if(ige.client.resolutionQuality=="low"){var mx=resolvedCoordinate.x-ige._bounds2d.x2*2-ige._translate.x;var my=resolvedCoordinate.y-ige._bounds2d.y2*2-ige._translate.y}else{var mx=resolvedCoordinate.x-ige._bounds2d.x2-ige._translate.x;var my=resolvedCoordinate.y-ige._bounds2d.y2-ige._translate.y}ige._mouseAbsoluteTranslation=[event.clientX,event.clientY];ige._mousePos.x=mx;ige._mousePos.y=my;return vpUpdated},mapAction:function(actionName,eventCode){this._controlMap[actionName]=eventCode},actionVal:function(actionName){return this._state[this._controlMap[actionName]]},actionState:function(actionName){var val=this._state[this._controlMap[actionName]];return!!val},val:function(inputId){return this._state[inputId]},state:function(inputId){return!!this._state[inputId]},stopPropagation:function(){this._eventControl._cancelled=true;return this},queueEvent:function(context,ev,data){if(ev!==undefined){this._eventQueue.push([context,ev,data])}return this},tick:function(){var arr=this._eventQueue;var arrCount=arr.length;var evc=this._eventControl;while(arrCount--){arr[arrCount][1].apply(arr[arrCount][0],[evc,arr[arrCount][2]]);if(evc._cancelled){break}}this._eventQueue=[];this._eventControl._cancelled=false;this.dblClick=false;this.mouseMove=false;this.mouseDown=false;this.mouseUp=false;this.mouseWheel=false},emit:function(eventName,args){if(this._eventListeners){if(this._eventListeners[eventName]){var eventCount=this._eventListeners[eventName].length;var eventCount2=this._eventListeners[eventName].length-1;var evc=this._eventControl;var finalArgs;var i;var cancelFlag;var eventIndex;var tempEvt;var retVal;if(eventCount){finalArgs=[];if(typeof args==="object"&&args!==null&&args[0]!==null){for(i in args){if(args.hasOwnProperty(i)){finalArgs[i]=args[i]}}}else{finalArgs=[args]}cancelFlag=false;this._eventListeners._processing=true;while(eventCount--){if(evc._cancelled){break}eventIndex=eventCount2-eventCount;tempEvt=this._eventListeners[eventName][eventIndex];if(tempEvt.sendEventName){finalArgs=[eventName]}retVal=tempEvt.call.apply(tempEvt.context||this,finalArgs);if(retVal===true||evc._cancelled===true){cancelFlag=true}if(tempEvt.oneShot){this.off(eventName,tempEvt)}}this._eventListeners._processing=false;this._processRemovals();if(cancelFlag){return 1}}}}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_14}var $i_18=$i_2.extend({classId:"$i_18",componentId:"tiled",init:function(entity,options){this._entity=entity;this._options=options},loadJson:function(url,callback){var self=this;var scriptElem;if(typeof url==="string"){if(ige.isClient){scriptElem=document.createElement("script");scriptElem.src=url;scriptElem.onload=function(){self.log("Tiled data loaded, processing...");self._processData(tiled,callback)};document.getElementsByTagName("head")[0].appendChild(scriptElem)}else{$i_18.prototype.log("URL-based Tiled data is only available client-side. If you want to load Tiled map data on the server please include the map file in your ServerConfig.js file and then specify the map's data object instead of the URL.","error")}}else{self._processData(url,callback)}},_processData:function(data,callback){if(ige.isServer&&(data==undefined||data.layers==undefined)){$i_18.prototype.log("layer doesn't exist. unpublishing...");ige.server.unpublish("$i_18#51")}var mapClass=ige.isServer===true?$i_63:$i_50Map;var mapWidth=data.width;var mapHeight=data.height;var layerArray=data.layers;var layerCount=layerArray?layerArray.length:0;var layer;var layerType;var layerData;var layerDataCount;var maps=[];var layersById={};var tileSetArray=data.tilesets;var tileSetCount=tileSetArray?tileSetArray.length:0;var tileSetItem;var tileSetsTotal=tileSetCount;var tileSetsLoaded=0;var textureCellLookup=[];var currentTexture;var currentCell;var onLoadFunc;var image;var textures=[];var allTexturesLoadedFunc;var i;var k;var x;var y;var z;var ent;if(ige.isClient){ige.layersById=layersById}allTexturesLoadedFunc=function(){for(i=0;i0&&layerData[z]!==2147483712){maps[i].occupyTile(x,y,1,1,layerData[z])}}}}if(layerType==="objectgroup"){maps[i]=layer;layersById[layer.name]=maps[i]}}callback(maps,layersById)};if(ige.isClient){onLoadFunc=function(textures,tileSetCount,tileSetItem){return function(){var i,cc;var imageUrl=tileSetItem.image;var scaleFactor=ige.scaleMapDetails.scaleFactor;if(imageUrl.includes("tilesheet")||tileSetCount===0){tileSetItem.tilewidth=ige.scaleMapDetails.originalTileWidth;tileSetItem.tileheight=ige.scaleMapDetails.originalTileHeight}var cs=new $i_51(imageUrl,this.width*scaleFactor.x/tileSetItem.tilewidth,this.height*scaleFactor.y/tileSetItem.tileheight,ige.scaleMapDetails.shouldScaleTilesheet).id(tileSetItem.name).on("loaded",function(){if(ige.scaleMapDetails.shouldScaleTilesheet&&(imageUrl.includes("tilesheet")||tileSetCount===0)){this.resize(this._sizeX*scaleFactor.x,this._sizeY*scaleFactor.y)}cc=this.cellCount();this._tiledStartingId=tileSetItem.firstgid;for(i=0;ia-b);return arr.length%2!==0?nums[mid]:(nums[mid-1]+nums[mid])/2}};if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_23}var $i_24=$i_3.extend({classId:"$i_24",componentId:"stream",init:function(entity,options){this._entity=entity;this._options=options;var self=this;this._sectionDesignator="\xAC";if(ige.isClient){this._entity.define("_igeStreamCreate",function(){self._onStreamCreate.apply(self,arguments)});this._entity.define("_igeStreamDestroy",function(){self._onStreamDestroy.apply(self,arguments)});this._entity.define("_igeStreamData",function(){self._onStreamData.apply(self,arguments)});this._entity.define("_igeStreamTime",function(){self._onStreamTime.apply(self,arguments)});this._entity.define("_igeStreamCreateSnapshot",function(){self._onStreamCreateSnapshot.apply(self,arguments)})}},renderLatency:function(latency){if(latency!==undefined){ige._renderLatency=latency;return this._entity}return ige._renderLatency},_onStreamTime:function(data){this._streamDataTime=data},_onStreamCreateSnapshot:function(data){console.log(data)},_onStreamCreate:function(data){var classId=data[0];var entityId=data[1];var parentId=data[2];var transformData=data[3];var createData=data[4];var parent=ige.$(parentId);var classConstructor;var ntransdata;var entity;if(transformData){var ntransdata=[parseInt(transformData[0],16),parseInt(transformData[1],16),parseInt(transformData[2],16)/1000]}if(parent){if(!ige.$(entityId)){classConstructor=igeClassStore[classId];if(classConstructor){createData.defaultData={translate:{x:ntransdata[0],y:ntransdata[1]},rotate:ntransdata[2]};entity=new classConstructor(createData,entityId);var body=entity._stats.currentBody;if(entity._category!="item"||body&&body.jointType!="weldJoint"){entity.bypassSmoothing=true;entity.streamSectionData("transform",ntransdata)}if(entity._streamEmitCreated){entity.emit("streamCreated")}this.emit("entityCreated",entity);delete entity.bypassSmoothing}else{ige.network.stop();ige.stop();$i_24.prototype.log(`Network stream cannot create entity with class ${classId} because the class has not been defined! The engine will now stop.`,"error")}}}else{$i_24.prototype.log(`Cannot properly handle network streamed entity with id ${entityId} because it's parent with id ${parentId} does not exist on the scenegraph!`,"warning")}},_onStreamDestroy:function(data){var entity=ige.$(data[1]);var self=this;if(entity){entity.destroy();self.emit("entityDestroyed",entity)}}});function arr2hex(byteArray){return Array.from(byteArray,function(byte){return`0${(byte&255).toString(16)}`.slice(-2)}).join("")}if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_24}var $i_28={};$i_28._debug={_enabled:true,_node:typeof module!=="undefined"&&typeof module.exports!=="undefined",_level:["log","warning","error"],_stacks:false,_throwErrors:true,_trace:{setup:false,enabled:false,match:""},enabled:function(val){if(val!==undefined){this._enabled=val;return this}return this._enabled}};$i_28.Class=$i_2;$i_28.EventingClass=$i_3;$i_28.Client=$i_28.EventingClass.extend({classId:"$i_28.Client",init:function(url,options){this.log("Net.io client starting...");this._options=options||{};this._socket=null;this._state=0;this._debug=false;this._connectionAttempts=0;this._sentBytesSinceLastUpdate=0;this._sentBytesTotal=0;this._receivedBytesSinceLastUpdate=0;this._receivedBytesTotal=0;this._started=new Date;this._lastSentUpdated=new Date;this._lastReceiveUpdated=new Date;this._receiveRate=0;this._sendRate=0;if(this._options.connectionRetry===undefined){this._options.connectionRetry=true}if(this._options.connectionRetryMax===undefined){this._options.connectionRetryMax=10}if(this._options.reconnect===undefined){this._options.reconnect=true}if(url!==undefined){this.connect(url)}},debug:function(val){if(val!==undefined){this._debug=val;return this}return this._debug},connect:function(url){this.log(`Connecting to server at ${url}`);var self=this;this._state=1;this._socket=new WebSocket(`${url}?token=${localStorage.getItem("token")}`,"netio1");this._socket.onopen=function(){self._onOpen.apply(self,arguments)};this._socket.onmessage=function(){self._onData.apply(self,arguments)};this._socket.onclose=function(){self._onClose.apply(self,arguments)};this._socket.onerror=function(){self._onError.apply(self,arguments)}},disconnect:function(reason){this._socket.close(1000,reason);this.emit("_igeStreamDestroy")},send:function(data){if(this._socket.readyState==1){var str=this._encode(data);this._socket.send(str);var sentBytes=str.length;this._sentBytesSinceLastUpdate+=sentBytes;this._sentBytesTotal+=sentBytes;var now=new Date;var elapsedSinceStarted=(now-this._started)*0.001;this._averageSendRate=this._sentBytesTotal/elapsedSinceStarted;var elapsed=(now-this._lastSentUpdated)*0.001;if(elapsed>=1){this._sendRate=this._sentBytesSinceLastUpdate/elapsed;this._lastSentUpdated=now;this._sentBytesSinceLastUpdate=0;if(statsPanels.sent){statsPanels.sent._sentPanel.update(this._sendRate,this._averageSendRate*2)}}}else{this.disconnect()}},_onOpen:function(event){var url=event.target.url;var urlWithoutProtocol=url.split("://")[1];var serverDomain=urlWithoutProtocol.split("/")[0];var serverName=serverDomain.split(":")[0];this._state=2},_onData:function(data){this._decode(data)},_onDecode:function(packet,data){var receivedBytes=data.data&&data.data.length||0;this._receivedBytesSinceLastUpdate+=receivedBytes;this._receivedBytesTotal+=receivedBytes;var now=new Date;var elapsedSinceStarted=(now-this._started)*0.001;this._averageReceiveRate=this._receivedBytesTotal/elapsedSinceStarted;var elapsed=(now-this._lastReceiveUpdated)*0.001;if(elapsed>=1){this._receiveRate=this._receivedBytesSinceLastUpdate/elapsed;this._lastReceiveUpdated=now;this._receivedBytesSinceLastUpdate=0;if(statsPanels.received){statsPanels.received._receivedPanel.update(this._receiveRate,this._averageReceiveRate*2)}var bandwidthUsed=(this._receivedBytesTotal+this._sentBytesTotal)/1024;if(statsPanels.bandwidth){statsPanels.bandwidth._bandwidthPanel.update(bandwidthUsed,bandwidthUsed*2)}}if(this._debug){console.log("Incoming data (event, decoded data):",data,packet)}if(packet._netioCmd){switch(packet._netioCmd){case"id":this.id=packet.data;this._state=3;this.emit("connect",this.id);break;case"close":this._disconnectReason=packet.data;break;}}else{this.emit("message",[packet])}},_onClose:function(event){var wasClean=event.wasClean;var reason=event.reason;var code=event.code;console.log("close event",event,{state:this._state,reason:this._disconnectReason});if(code===1006){var url=event.target.url;var urlWithoutProtocol=url.split("://")[1];var serverDomain=urlWithoutProtocol.split("/")[0]}if(this._state===3){this._state=0;this.emit("disconnect",{reason:this._disconnectReason,wasClean:wasClean,code:code})}if(this._state===2){this._state=0;this.emit("disconnect",{reason:this._disconnectReason,wasClean:wasClean,code:code})}if(this._state===1){this._state=0;this.emit("error",{reason:"Cannot establish connection, is server running?"})}delete this._disconnectReason},_onError:function(){this.log("An error occurred with the net.io socket!","error",arguments);console.log("An error occurred with the net.io socket!","error",arguments);this.emit("error",arguments)},_encode:function(data){return JSON.stringify(data)},_decode:function(data){var self=this;var jsonString=LZString.decompressFromUTF16(data.data);self._onDecode(JSON.parse(jsonString),data)}});var Ige$i_28Client={version:"1.0.0",_initDone:false,_idCounter:0,_requests:{},_state:0,usedServers:[],id:function(){return this._id||""},start:function(server,callback){if(this._state===3){if(typeof callback==="function"){callback(server)}}else{this.artificialDelay=0;this.lagVariance=0;var self=this;var gameId=ige.client.servers[0].gameId;self._startCallback=callback;var sortedServers=[server];var ignoreServerIds=[server.id];while(server=ige.client.getBestServer(ignoreServerIds)){ignoreServerIds.push(server.id);sortedServers.push(server)}sortedServers.reduce(function(p,server){var defer=$.Deferred();p.then(function(){if(self._state<2){if(window.isStandalone){console.log("connecting to a standalone server");url=`ws://${window.location.hostname}:2001`}else{url=server.url}self._url=url;var msg=`Connecting to net.io server at "${self._url}"...`;self.log(msg);console.log(msg);window.connectedServer=server;if(typeof WebSocket!=="undefined"){self.connectToGS(url).done(function(){window.activatePlayGame=true;defer.resolve()}).fail(function(err){console.log("connection failed, retrying...",err||"")})}else{defer.reject("websockets are not available")}}else{defer.resolve()}});return defer},$.when()).done(function(){console.log("final stage",self._state);if(self._state<3){console.log("disconnecting from the server");self._state=0;self._onDisconnectFromServer.apply(self,arguments);if(gameId&&typeof analyticsUrl!=undefined){$.post(`${analyticsUrl}api/game-report/game-access/${gameId}/could-not-connect`).fail(function(xhr){$.post("/api/log",{event:"could-not-connect",game:gameId,status:xhr.status,text:xhr.statusText})})}if($("#menu-wrapper").is(":visible")){$("#play-game-button .content").addClass("bg-danger");$("#play-game-button .content").html(""+"
"+"
"+"Connection Failed"+"
"+"
"+"Please select a different server"+"
"+"
");$("#play-game-button").prop("disabled",false);console.log(ige.client.eventLog);window.activatePlayGame=true}else{ige.menuUi.onDisconnectFromServer("ige$i_28Client #143")}}}).fail(function(error){$.post("/api/log",{event:"could-not-connect",game:gameId,text:error.toString()})})}},connectToGS:function(url){var self=this;var defer=$.Deferred();if(!url){defer.reject("invalid url provided");return defer.promise()}this._io=new $i_28.Client(url);self._state=1;var timer=setTimeout(function(){console.log("connection timed out",url);clearTimeout(timer);self._state=0;self._io.disconnect("Client timed out");defer.reject()},7000);this._io.on("connect",function(clientId){self._state=2;self._id=clientId;self._onConnectToServer.apply(self,arguments)});this._io.on("message",function(data){if(!self._initDone&&data&&data.cmd!="init"){if(!self.dataB4Init){self.dataB4Init=[]}self.dataB4Init.push(arguments)}if(data.cmd){var i;var commandCount=0;if(data.cmd==="init"){clearTimeout(timer);self._initDone=true;self._state=3;self._networkCommandsLookup=data.ncmds;for(i in self._networkCommandsLookup){if(self._networkCommandsLookup.hasOwnProperty(i)){self._networkCommandsIndex[self._networkCommandsLookup[i]]=i;commandCount++}}self.define("_igeRequest",function(){self._onRequest.apply(self,arguments)});self.define("_igeResponse",function(){self._onResponse.apply(self,arguments)});self.define("_igeNetTimeSync",function(){self._onTimeSync.apply(self,arguments)});self.log(`Received network command list with count: ${commandCount}`);ige.timeScale(parseFloat(data.ts));if(typeof self._startCallback==="function"){self._startCallback({url:url});delete self._startCallback}if(self.dataB4Init&&self.dataB4Init.length>0){for(var i=0;inewSnapshotTimeStamp+100||ige._currentTime=0;i--){console.log(`client ${clientId} is leaving the room ${arr[i]}(${i})`);this.clientLeaveRoom(clientId,arr[i])}delete this._clientRooms[clientId];return this._entity}}else{this.log("Cannot remove client from room because no clientId was provided!","warning")}return this._entity},clientRooms:function(clientId){if(clientId!==undefined){return this._clientRooms[clientId]||[]}this.log("Cannot get/set the clientRoom id because no clientId was provided!","warning");return[]},clients:function(roomId){if(roomId!==undefined){return this._socketsByRoomId[roomId]}return this._socketById},socket:function(clientId){return this._socketById[clientId]},acceptConnections:function(val){if(typeof val!=="undefined"){this._acceptConnections=val;if(val){this.log("Server now accepting connections!")}else{this.log("Server no longer accepting connections!")}return this._entity}return this._acceptConnections},send:function(commandName,data,clientId){var self=this;var commandIndex=this._networkCommandsLookup[commandName];var ciEncoded;if(commandIndex!==undefined){ciEncoded=String.fromCharCode(commandIndex);if(!self.sendQueue[clientId])self.sendQueue[clientId]=[];if(!clientId)clientId="undefined";self.sendQueue[clientId].push([ciEncoded,data])}else{this.log(`Cannot send network packet with command "${commandName}" because the command has not been defined!`,"error")}},add:function(commandName,data,clientId){var commandIndex=this._networkCommandsLookup[commandName];var ciEncoded;if(commandIndex!==undefined){ciEncoded=String.fromCharCode(commandIndex);const snapshotData=typeof data==="string"?ciEncoded+data:[ciEncoded,data];this.snapshot.push(snapshotData)}else{this.log(`Cannot send network packet with command "${commandName}" because the command has not been defined!`,"error")}},flush:function(timestamp){var self=this;var commandIndex=this._networkCommandsLookup._snapshot;var ciEncoded=String.fromCharCode(commandIndex);if(commandIndex!==undefined){if(self.sendQueue){for(var clientId in self.sendQueue){if(global.isDev){setTimeout(function(data,id,ci){self._io.send([ci,data],id==="undefined"?undefined:id)},Math.random()*self.lagVariance+self.artificialDelay,self.sendQueue[clientId],clientId,ciEncoded)}else{self._io.send([ciEncoded,self.sendQueue[clientId]],clientId==="undefined"?undefined:clientId)}}self.sendQueue={}}if(this.snapshot.length==0){return}self.snapshot.push([String.fromCharCode(this._networkCommandsLookup._igeStreamTime),timestamp]);if(global.isDev){setTimeout(function(data,ci){self._io.send([ci,data])},Math.random()*self.lagVariance+self.artificialDelay,self.snapshot,ciEncoded)}else{self._io.send([ciEncoded,self.snapshot])}ige.server.lastSnapshot=self.snapshot;this.snapshot=[]}else{this.log("_snapshot error @ flush")}},request:function(commandName,data,callback){var req={id:this.newIdHex(),cmd:commandName,data:data,callback:callback,timestamp:new Date().getTime()};this._requests[req.id]=req;this.send("_igeRequest",{id:req.id,cmd:commandName,data:req.data})},response:function(requestId,data){var req=this._requests[requestId];if(req){this.send("_igeResponse",{id:requestId,cmd:req.commandName,data:data},req.clientId);delete this._requests[requestId]}},newIdHex:function(){this._idCounter++;return(this._idCounter+(Math.random()*Math.pow(10,17)+Math.random()*Math.pow(10,17)+Math.random()*Math.pow(10,17)+Math.random()*Math.pow(10,17))).toString(16)},_originIsAllowed:function(origin){return true},_onClientConnect:function(socket){var self=this;var remoteAddress=socket._remoteAddress;console.log("client is attempting to connect",remoteAddress);var reason="";var bannedIps=ige.server.bannedIps;var playerIsBanned=false;for(index in bannedIps){if(bannedIps[remoteAddress]!=undefined){console.log(`banned player detected! IP ${remoteAddress}`);playerIsBanned=true;reason+=" player is banned."}}const playerCount=ige.$$("player").filter(function(player){return player._stats.controlledBy=="human"}).length;var clientRejectReason=[];if(this._acceptConnections!=true)clientRejectReason.push("server not accepting connections");if(playerCount>ige.server.maxPlayers)clientRejectReason.push("server is full");if(playerIsBanned)clientRejectReason.push("player ",socket._remoteAddress," is banned");if(clientRejectReason.length==0){if(!this.emit("connect",socket)){this.log(`Accepted connection with socket id ${socket.id} ip ${remoteAddress}`);this._socketById[socket.id]=socket;this.clientIds.push(socket.id);self._socketById[socket.id].start=Date.now();ige.server.socketConnectionCount.connected++;this._clientRooms[socket.id]=this._clientRooms[socket.id]||[];socket.on("message",function(data){if(data.type==="ping"){socket.send({type:"pong",clientSentAt:data.sentAt,serverSentAt:Date.now(),timeTookToReceive:Date.now()-data.sentAt});return}self._onClientMessage.apply(self,[data,socket.id])});socket.on("disconnect",function(data){var isClient=self.clientIds.includes(socket.id);if(isClient){var end=Date.now();ige.server.socketConnectionCount.disconnected++;if(end-self._socketById[socket.id].start<3000){ige.server.socketConnectionCount.immediatelyDisconnected++}}self._onClientDisconnect.apply(self,[data,socket])});socket.send({cmd:"init",ncmds:this._networkCommandsLookup,ts:ige._timeScale,ct:ige._currentTime});this._sendTimeSync(socket.id)}else{var reason="cannot connect to socket this.emit(\"connect\", socket)";console.log(reason);socket.close(reason)}}else{console.log("rejecting connection",clientRejectReason);socket.close(clientRejectReason)}},_onClientMessage:function(data,clientId){if(typeof data[0]==="string"){if(data[0].charCodeAt(0)!=undefined){var ciDecoded=data[0].charCodeAt(0);var commandName=this._networkCommandsIndex[ciDecoded];if(this._networkCommands[commandName]){this._networkCommands[commandName](data[1],clientId)}this.emit(commandName,[data[1],clientId])}}},_onRequest:function(data,clientId){data.clientId=clientId;this._requests[data.id]=data;if(this.debug()){console.log("onRequest",data);console.log("emitting",data.cmd,[data.id,data.data]);this._debugCounter++}if(this._networkCommands[data.cmd]){this._networkCommands[data.cmd](data.data,clientId,data.id)}this.emit(data.cmd,[data.id,data.data,clientId])},_onResponse:function(data,clientId){id=data.id;req=this._requests[id];if(this.debug()){console.log("onResponse",data);this._debugCounter++}if(req){req.callback(req.cmd,[data.data,clientId]);delete this._requests[id]}},_onClientDisconnect:function(data,socket){this.log(`Client disconnected with id ${socket.id}`);this.emit("disconnect",socket.id);this.clientLeaveAllRooms(socket.id);delete ige.server.clients[socket.id];delete this._socketById[socket.id];let indexToRemove=this.clientIds.findIndex(function(id){if(id===socket.id)return true});if(indexToRemove>-1){this.clientIds.splice(indexToRemove,1)}}};if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=Ige$i_28Server}var Ige$i_28Component=$i_3.extend([{extension:$i_23,overwrite:false}],{classId:"Ige$i_28Component",componentId:"network",init:function(entity,options){this._entity=entity;this._options=options;this._networkCommands={};this._networkCommandsIndex=[];this._networkCommandsLookup={};this._port=2001;this._debug=false;this._debugCounter=0;this._debugMax=0;this._clientRooms={};this._timeSyncInterval=1000;this._timeSyncLog={};this._latency=0;this.latency=0;this.latencyHistory=[];this.rttSamples=[];this.lastClientTime=0;this.lastServerTime=0;this.totalClientTimeElapsed=[];this.totalServerTimeElapsed=[];if(ige.isClient){this._netio=Ige$i_28Client;this.implement(Ige$i_28Client)}this.log(`Network component initiated with Net.IO version: ${this._netio.version}`)},debug:function(val){if(val!==undefined){this._debug=val;return this._entity}if(this._debugMax>0&&this._debugCounter>=this._debugMax){this._debug=false;this._debugCounter=0}return this._debug},debugMax:function(val){if(val!==undefined){this._debugMax=val;return this._entity}return this._debugMax}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=Ige$i_28Component}var openChatBubble={};var $i_32={joinRoom:function(roomId){ige.network.send("igeChatJoinRoom",roomId)},sendToRoom:function(roomId,message,to){if(roomId!==undefined&&message!==undefined){msg={roomId:roomId,text:message,to:to};ige.network.send("igeChatMsg",msg)}},_onMessageFromServer:function(data){var self=ige.chat;var player=ige.game.getPlayerByClientId(data.from);var isPlayerMuted=ige.client.myPlayer&&ige.client.myPlayer._stats&&ige.client.myPlayer._stats.mutedUsers&&ige.client.myPlayer._stats.mutedUsers.indexOf(player._stats.userId)>-1;if(!player||isPlayerMuted){return}var isChatHidden=$("#chat-box").hasClass("d-none");if(!self.emit("messageFromServer",[data])){if(!isChatHidden){var selectedUnit=player.getSelectedUnit();if(selectedUnit&&selectedUnit.gluedEntities){for(var i=0;i80){msg.text=msg.text.substr(0,80)}if(to){if(room.users.indexOf(to)>-1){ige.network.send("igeChatMsg",msg,to)}else{self.log(`Cannot send to user because specified user is not in room: ${to}`)}}else{ige.network.send("igeChatMsg",msg)}}else{self.log("Cannot send message to room with blank message!")}}else{self.log(`Cannot send message to room with id "${roomId}" because it does not exist!`)}},isSpamming:function(from,message){now=new Date;if(this.lastMessageSentAt[from]==undefined){this.lastMessageSentAt[from]=now;this.sentMessages[from]=[];return false}this.lastMessageSentAt[from]=now;this.sentMessages[from].push({time:new Date,message:message});var returnValue=false;if(this.sentMessages[from].length>4){var timeElapsed=0;var charCount=0;timeElapsed=now-this.sentMessages[from][0].time;for(i in this.sentMessages[from]){charCount+=this.sentMessages[from][i].message.length}if(timeElapsed<=2000){returnValue=true}if(timeElapsed<=4000&&charCount>80){returnValue=true}this.sentMessages[from].shift()}return returnValue},_onMessageFromClient:function(msg,clientId){var self=ige.chat;var room;if(typeof msg.text!="string"||self.regexUnicode.test(msg.text)==true){return}if(process.env.ENV!="standalone"){msg.text=self.filter.cleanHacked(msg.text)}if(msg==undefined||msg.text==undefined)return;if(!self.emit("messageFromClient",[msg,clientId])){var player=ige.game.getPlayerByClientId(clientId);if(player){var playerName=player._stats&&self.xssFilters.inHTMLData(player._stats.name);ige.devLog(`Message from client: (${playerName}): ${msg.text}`);player.lastMessageSent=msg.text;ige.trigger.fire("playerSendsMessage",{playerId:player.id()})}if(msg.roomId&&typeof msg.roomId=="string"||typeof msg.roomId=="number"){room=self._rooms[msg.roomId];if(room){if(room.users.indexOf(clientId)>-1){var text=msg.text;if(text){self.sendToRoom(msg.roomId,msg.text,msg.to,clientId)}else{}}else{ige.devLog("User tried to send message to room they are not joined in!",msg)}}else{ige.devLog("User tried to send message to room that doesn't exist!",msg)}}else{ige.devLog("User tried to send message to room but didn't specify room id!",msg)}}},_onJoinRoomRequestFromClient:function(roomId,clientId){var self=ige.chat;if(!self.emit("clientJoinRoomRequest",[roomId,clientId])){var room=self._rooms[roomId];self.log(`Client wants to join room: (${clientId})`,roomId);if(room){if(!room.users[clientId]){room.users.push(clientId);ige.network.send("igeChatJoinRoom",{roomId:roomId,joined:true},clientId)}else{}}else{}}},_onLeaveRoomRequestFromClient:function(roomId,clientId){if(!self.emit("clientLeaveRoomRequest",[roomId,clientId])){console.log(`Client wants to leave room: (${clientId})`,roomId)}},_onClientWantsRoomList:function(data,clientId){if(!self.emit("clientRoomListRequest",[data,clientId])){console.log(`Client wants the room list: (${clientId})`,data)}},_onClientWantsRoomUserList:function(roomId,clientId){if(!self.emit("clientRoomUserListRequest",[roomId,clientId])){console.log(`Client wants the room user list: (${clientId})`,roomId)}}};if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_33}var $i_34=$i_3.extend({classId:"$i_34",componentId:"chat",init:function(entity,options){var self=this;this._options=options;this._rooms={};this.lastMessageSentAt=[];this.sentMessages=[];if(ige.isClient){this.implement($i_32);ige.network.define("igeChatMsg",this._onMessageFromServer);ige.network.define("igeChatJoinRoom",this._onJoinedRoom);ige.network.define("igeChatLeaveRoom",this._onLeftRoom);ige.network.define("igeChatRoomList",this._onServerSentRoomList);ige.network.define("igeChatRoomUserList",this._onServerSentRoomUserList);ige.network.define("igeChatRoomCreated",this._onRoomCreated);ige.network.define("igeChatRoomRemoved",this._onRoomRemoved);$("#send-message").on("click",function(){self.sendChatMessage()});$("#hide-chat").on("click",function(){$("#show-chat").removeClass("d-none");$("#chat-box").addClass("d-none")});$("#show-chat").on("click",function(){$("#show-chat").addClass("d-none");$("#chat-box").removeClass("d-none")})}this.log("Chat component initiated!")},sendChatMessage:function(){if(ige.isClient){var player=ige.client.myPlayer;var gameData=ige.game&&ige.game.data&&ige.game.data.defaultData;var message=$("#message").val();if(message.length>80)message=message.substr(0,80);if(ige.env!="local"&&player&&(player._stats.banChat||gameData&&gameData.allowVerifiedUserToChat&&!player._stats.isUserVerified)){}else{ige.network.send("igeChatMsg",{text:message,roomId:"1"})}$("#message").blur();$("#message").val("");$("#chat-message-input").hide()}},escapeOutput:function(str){return str.replace(/\&/g,"&").replace(/\/g,">").replace(/\"/g,""").replace(/\'/g,"'").replace(/\//g,"/")},postMessage:function(msgData){ige.devLog("message received",msgData);if(ige.isClient){var msgDiv="";if(msgData.from){var player=ige.game.getPlayerByClientId(msgData.from);var playerName=this.escapeOutput(player._stats.name);if(player&&player._stats){msgDiv=$("
:
");$(msgDiv).find(".author").text(player._stats.name);$(msgDiv).find(".msg").text(msgData.text)}}else{msgDiv=$("
",{style:"color: yellow"});if(msgData.isHtml){msgDiv.append(`* ${msgData.text} *`)}else{msgDiv.text(`* ${msgData.text} *`)}}$("#chat-history").each(function(){messageCount=$(this).find("div").length;if(messageCount>50){$(this).find("div:first-child").remove()}var scrollDifference=Math.abs(parseInt(this.scrollTop+this.clientHeight)-parseInt(this.scrollHeight));var shouldScroll=parseInt($(this).scrollTop+$(this).clientHeight)===parseInt($(this).scrollHeight)||scrollDifference<2;$(this).append(msgDiv);if(shouldScroll){$(this).scrollTop(this.scrollHeight)}})}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_34}var $i_39=$i_3.extend({classId:"$i_39",componentId:"cocoonJs",init:function(){this.detected=typeof ext!=="undefined"&&typeof ext.IDTK_APP!=="undefined";if(this.detected){this.log("CocoonJS support enabled!")}},showInputDialog:function(title,message,initialValue,type,cancelText,okText){if(this.detected){title=title||"";message=message||"";initialValue=initialValue||"";type=type||"text";cancelText=cancelText||"Cancel";okText=okText||"OK";ext.IDTK_APP.makeCall("showTextDialog",title,message,initialValue,type,cancelText,okText)}else{this.log("Cannot open CocoonJS input dialog! CocoonJS is not detected!","error")}},showWebView:function(url){if(this.detected){ext.IDTK_APP.makeCall("forward",`ext.IDTK_APP.makeCall('loadPath', '${url}')`);ext.IDTK_APP.makeCall("forward","ext.IDTK_APP.makeCall('show');")}},hideWebView:function(){if(this.detected){ext.IDTK_APP.makeCall("forward","ext.IDTK_APP.makeCall('hide');")}}});var $i_40={left:function(px,noUpdate){if(px!==undefined){if(px===null){delete this._uiLeft;delete this._uiLeftPercent}else{delete this._uiCenter;delete this._uiCenterPercent;if(typeof px==="string"){this._uiLeftPercent=px;var parentWidth;var val=parseInt(px,10);var newVal;if(this._parent){parentWidth=this._parent._bounds2d.x}else{parentWidth=ige._bounds2d.x}newVal=parentWidth/100*val|0;this._uiLeft=newVal}else{this._uiLeft=px;delete this._uiLeftPercent}}if(!noUpdate){this._updateUiPosition()}return this}return this._uiLeft},right:function(px,noUpdate){if(px!==undefined){if(px===null){delete this._uiRight;delete this._uiRightPercent}else{delete this._uiCenter;delete this._uiCenterPercent;if(typeof px==="string"){this._uiRightPercent=px;var parentWidth;var val=parseInt(px,10);var newVal;if(this._parent){parentWidth=this._parent._bounds2d.x}else{parentWidth=ige._bounds2d.x}newVal=parentWidth/100*val|0;this._uiRight=newVal}else{this._uiRight=px;delete this._uiRightPercent}}if(!noUpdate){this._updateUiPosition()}return this}return this._uiRight},center:function(px,noUpdate){if(px!==undefined){if(px===null){delete this._uiCenter;delete this._uiCenterPercent}else{delete this._uiLeft;delete this._uiLeftPercent;delete this._uiRight;delete this._uiRightPercent;if(typeof px==="string"){this._uiCenterPercent=px;var parentWidth;var val=parseInt(px,10);var newVal;if(this._parent){parentWidth=this._parent._bounds2d.x2}else{parentWidth=ige._bounds2d.x2}newVal=parentWidth/100*val|0;this._uiCenter=newVal}else{this._uiCenter=px;delete this._uiCenterPercent}}if(!noUpdate){this._updateUiPosition()}return this}return this._uiCenter},top:function(px,noUpdate){if(px!==undefined){if(px===null){delete this._uiTop;delete this._uiTopPercent}else{delete this._uiMiddle;delete this._uiMiddlePercent;if(typeof px==="string"){this._uiTopPercent=px;var parentHeight;var val=parseInt(px,10);var newVal;if(this._parent){parentHeight=this._parent._bounds2d.y}else{parentHeight=ige._bounds2d.y}newVal=parentHeight/100*val|0;this._uiTop=newVal}else{this._uiTop=px;delete this._uiTopPercent}}if(!noUpdate){this._updateUiPosition()}return this}return this._uiTop},bottom:function(px,noUpdate){if(px!==undefined){if(px===null){delete this._uiBottom;delete this._uiBottomPercent}else{delete this._uiMiddle;delete this._uiMiddlePercent;if(typeof px==="string"){this._uiBottomPercent=px;var parentHeight;var val=parseInt(px,10);var newVal;if(this._parent){parentHeight=this._parent._bounds2d.y}else{parentHeight=ige._bounds2d.y}newVal=parentHeight/100*val|0;this._uiBottom=newVal}else{this._uiBottom=px;delete this._uiBottomPercent}}if(!noUpdate){this._updateUiPosition()}return this}return this._uiBottom},middle:function(px,noUpdate){if(px!==undefined){if(px===null){delete this._uiMiddle;delete this._uiMiddlePercent}else{delete this._uiTop;delete this._uiTopPercent;delete this._uiBottom;delete this._uiBottomPercent;if(typeof px==="string"){this._uiMiddlePercent=px;var parentWidth;var val=parseInt(px,10);var newVal;if(this._parent){parentWidth=this._parent._bounds2d.y2}else{parentWidth=ige._bounds2d.y2}newVal=parentWidth/100*val|0;this._uiMiddle=newVal}else{this._uiMiddle=px;delete this._uiMiddlePercent}}if(!noUpdate){this._updateUiPosition()}return this}return this._uiMiddle},width:function(px,lockAspect,modifier,noUpdate){if(px!==undefined){if(px===null){delete this._uiWidth;this._bounds2d.x=0;this._bounds2d.x2=0}else{this._uiWidth=px;this._widthModifier=modifier!==undefined?modifier:0;if(typeof px==="string"){if(this._parent){var parentWidth=this._parent._bounds2d.x;var val=parseInt(px,10);var newVal;var ratio;newVal=parentWidth/100*val+this._widthModifier|0;if(lockAspect){ratio=newVal/this._bounds2d.x;this.height(this._bounds2d.y/ratio,false,0,noUpdate)}this._bounds2d.x=newVal;this._bounds2d.x2=Math.floor(this._bounds2d.x/2)}else{var parentWidth=ige._bounds2d.x;var val=parseInt(px,10);this._bounds2d.x=parentWidth/100*val+this._widthModifier|0;this._bounds2d.x2=Math.floor(this._bounds2d.x/2)}}else{if(lockAspect){var ratio=px/this._bounds2d.x;this.height(this._bounds2d.y*ratio,false,0,noUpdate)}this._bounds2d.x=px;this._bounds2d.x2=Math.floor(this._bounds2d.x/2)}}if(!noUpdate){this._updateUiPosition()}return this}return this._bounds2d.x},height:function(px,lockAspect,modifier,noUpdate){if(px!==undefined){if(px===null){delete this._uiHeight;this._bounds2d.y=0;this._bounds2d.y2=0}else{this._uiHeight=px;this._heightModifier=modifier!==undefined?modifier:0;if(typeof px==="string"){if(this._parent){var parentHeight=this._parent._bounds2d.y;var val=parseInt(px,10);var newVal;var ratio;newVal=parentHeight/100*val+this._heightModifier|0;if(lockAspect){ratio=newVal/this._bounds2d.y;this.width(this._bounds2d.x/ratio,false,0,noUpdate)}this._bounds2d.y=newVal;this._bounds2d.y2=Math.floor(this._bounds2d.y/2)}else{var parentHeight=ige._bounds2d.y;var val=parseInt(px,10);this._bounds2d.y=parentHeight/100*val+this._heightModifier|0;this._bounds2d.y2=Math.floor(this._bounds2d.y/2)}}else{if(lockAspect){var ratio=px/this._bounds2d.y;this.width(this._bounds2d.x*ratio,false,0,noUpdate)}this._bounds2d.y=px;this._bounds2d.y2=Math.floor(this._bounds2d.y/2)}}if(!noUpdate){this._updateUiPosition()}return this}return this._bounds2d.y},autoScaleX:function(val,lockAspect){if(val!==undefined){this._autoScaleX=val;this._autoScaleLockAspect=lockAspect;this._updateUiPosition();return this}return this._autoScaleX},autoScaleY:function(val,lockAspect){if(val!==undefined){this._autoScaleY=val;this._autoScaleLockAspect=lockAspect;this._updateUiPosition();return this}return this._autoScaleY},updateUiChildren:function(){var arr=this._children;var arrCount;var arrItem;if(arr){arrCount=arr.length;while(arrCount--){arrItem=arr[arrCount];if(arrItem._updateUiPosition){arrItem._updateUiPosition()}if(typeof arrItem.updateUiChildren==="function"){arrItem.updateUiChildren()}}}return this},_updateUiPosition:function(){if(this._parent){var parentGeom=this._parent._bounds2d;var geomScaled=this._bounds2d.multiplyPoint(this._scale);var percent;var newVal;var ratio;if(this._autoScaleX){percent=parseInt(this._autoScaleX,10);newVal=parentGeom.x/100*percent;ratio=newVal/this._bounds2d.x;this._scale.x=ratio;if(this._autoScaleLockAspect){this._scale.y=ratio}}if(this._autoScaleY){percent=parseInt(this._autoScaleY,10);newVal=parentGeom.y/100*percent;ratio=newVal/this._bounds2d.y;this._scale.y=ratio;if(this._autoScaleLockAspect){this._scale.x=ratio}}if(this._uiWidth){this.width(this._uiWidth,false,this._widthModifier,true)}if(this._uiHeight){this.height(this._uiHeight,false,this._heightModifier,true)}if(this._uiCenterPercent){this.center(this._uiCenterPercent,true)}if(this._uiMiddlePercent){this.middle(this._uiMiddlePercent,true)}if(this._uiLeftPercent){this.left(this._uiLeftPercent,true)}if(this._uiRightPercent){this.right(this._uiRightPercent,true)}if(this._uiTopPercent){this.top(this._uiTopPercent,true)}if(this._uiBottomPercent){this.bottom(this._uiBottomPercent,true)}if(this._uiCenter!==undefined){this._translate.x=Math.floor(this._uiCenter)}else{if(this._uiLeft!==undefined&&this._uiRight!==undefined){this.width(parentGeom.x-this._uiLeft-this._uiRight,false,0,true);this._translate.x=Math.floor(this._uiLeft+geomScaled.x2-parentGeom.x2)}else{if(this._uiLeft!==undefined){this._translate.x=Math.floor(this._uiLeft+geomScaled.x2-parentGeom.x2)}if(this._uiRight!==undefined){this._translate.x=Math.floor(parentGeom.x2-geomScaled.x2-this._uiRight)}}}if(this._uiMiddle!==undefined){this._translate.y=Math.floor(this._uiMiddle)}else{if(this._uiTop!==undefined&&this._uiBottom!==undefined){this.height(parentGeom.y-this._uiTop-this._uiBottom,false,0,true);this._translate.y=Math.floor(this._uiTop+geomScaled.y2-parentGeom.y2)}else{if(this._uiTop!==undefined){this._translate.y=Math.floor(this._uiTop+geomScaled.y2-parentGeom.y2)}if(this._uiBottom!==undefined){this._translate.y=Math.floor(parentGeom.y2-geomScaled.y2-this._uiBottom)}}}this.emit("uiUpdate");this.cacheDirty(true)}}};if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_40}var $i_41={color:function(color){if(color!==undefined){this._color=color;this.cacheDirty(true);return this}return this._color},backgroundImage:function(texture,repeatType){if(texture&&texture.image){if(!repeatType){repeatType="no-repeat"}this._patternRepeat=repeatType;this._patternTexture=texture;if(this._backgroundSize){texture.resize(this._backgroundSize.x,this._backgroundSize.y);this._patternWidth=this._backgroundSize.x;this._patternHeight=this._backgroundSize.y}else{this._patternWidth=texture.image.width;this._patternHeight=texture.image.height}if(this._cell>1){var canvas=document.createElement("canvas");var ctx=canvas.getContext("2d");var cellData=texture._cells[this._cell];canvas.width=cellData[2];canvas.height=cellData[3];ctx.drawImage(texture.image,cellData[0],cellData[1],cellData[2],cellData[3],0,0,cellData[2],cellData[3]);this._patternFill=ige._ctx.createPattern(canvas,repeatType)}else{this._patternFill=ige._ctx.createPattern(texture.image,repeatType)}texture.restoreOriginal();this.cacheDirty(true);return this}return this._patternFill},backgroundSize:function(x,y){if(x!==undefined&&y!==undefined){if(typeof x==="string"&&x!=="auto"){x=this._bounds2d.x/100*parseInt(x,10)}if(typeof y==="string"&&y!=="auto"){y=this._bounds2d.y/100*parseInt(y,10)}if(x==="auto"&&y==="auto"){this.log("Cannot set background x and y both to auto!","error");return this}else if(x==="auto"){if(this._patternTexture&&this._patternTexture.image){x=this._patternTexture.image.width*(y/this._patternTexture.image.height)}else{x=this._bounds2d.x*(y/this._bounds2d.y)}}else if(y==="auto"){if(this._patternTexture&&this._patternTexture.image){y=this._patternTexture.image.height*(x/this._patternTexture.image.width)}else{y=this._bounds2d.y*(x/this._bounds2d.x)}}if(x!==0&&y!==0){this._backgroundSize={x:x,y:y};if(this._patternTexture&&this._patternRepeat){this.backgroundImage(this._patternTexture,this._patternRepeat)}this.cacheDirty(true)}else{this.log("Cannot set background to zero-sized x or y!","error")}return this}return this._backgroundSize},backgroundColor:function(color){if(color!==undefined){this._backgroundColor=color;this.cacheDirty(true);return this}return this._backgroundColor},backgroundPosition:function(x,y){if(x!==undefined&&y!==undefined){this._backgroundPosition={x:x,y:y};this.cacheDirty(true);return this}return this._backgroundPosition},borderColor:function(color){if(color!==undefined){this._borderColor=color;this._borderLeftColor=color;this._borderTopColor=color;this._borderRightColor=color;this._borderBottomColor=color;this.cacheDirty(true);return this}return this._borderColor},borderLeftColor:function(color){if(color!==undefined){this._borderLeftColor=color;this.cacheDirty(true);return this}return this._borderLeftColor},borderTopColor:function(color){if(color!==undefined){this._borderTopColor=color;this.cacheDirty(true);return this}return this._borderTopColor},borderRightColor:function(color){if(color!==undefined){this._borderRightColor=color;this.cacheDirty(true);return this}return this._borderRightColor},borderBottomColor:function(color){if(color!==undefined){this._borderBottomColor=color;this.cacheDirty(true);return this}return this._borderBottomColor},borderWidth:function(px){if(px!==undefined){this._borderWidth=px;this._borderLeftWidth=px;this._borderTopWidth=px;this._borderRightWidth=px;this._borderBottomWidth=px;this.cacheDirty(true);return this}return this._borderWidth},borderLeftWidth:function(px){if(px!==undefined){this._borderLeftWidth=px;this.cacheDirty(true);return this}return this._borderLeftWidth},borderTopWidth:function(px){if(px!==undefined){this._borderTopWidth=px;this.cacheDirty(true);return this}return this._borderTopWidth},borderRightWidth:function(px){if(px!==undefined){this._borderRightWidth=px;this.cacheDirty(true);return this}return this._borderRightWidth},borderBottomWidth:function(px){if(px!==undefined){this._borderBottomWidth=px;this.cacheDirty(true);return this}return this._borderBottomWidth},borderRadius:function(px){if(px!==undefined){this._borderRadius=px;this._borderTopLeftRadius=px;this._borderTopRightRadius=px;this._borderBottomRightRadius=px;this._borderBottomLeftRadius=px;this.cacheDirty(true);return this}return this._borderRadius},padding:function(left,top,right,bottom){this._paddingLeft=left;this._paddingTop=top;this._paddingRight=right;this._paddingBottom=bottom;this.cacheDirty(true);return this},paddingLeft:function(px){if(px!==undefined){this._paddingLeft=px;this.cacheDirty(true);return this}return this._paddingLeft},paddingTop:function(px){if(px!==undefined){this._paddingTop=px;this.cacheDirty(true);return this}return this._paddingTop},paddingRight:function(px){if(px!==undefined){this._paddingRight=px;this.cacheDirty(true);return this}return this._paddingRight},paddingBottom:function(px){if(px!==undefined){this._paddingBottom=px;this.cacheDirty(true);return this}return this._paddingBottom}};if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_41}var nullMethod=function(){};var $i_45=function(){this.dummy=true;this.width=0;this.height=0};$i_45.prototype.getContext=function(){return $i_46};if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_45}var nullMethod=function(){};var $i_46={dummy:true,save:nullMethod,restore:nullMethod,translate:nullMethod,rotate:nullMethod,scale:nullMethod,drawImage:nullMethod,fillRect:nullMethod,strokeRect:nullMethod,stroke:nullMethod,fill:nullMethod,rect:nullMethod,moveTo:nullMethod,lineTo:nullMethod,arc:nullMethod,clearRect:nullMethod,beginPath:nullMethod,clip:nullMethod,transform:nullMethod,setTransform:nullMethod,fillText:nullMethod};if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_46}var $i_49=$i_2.extend({classId:"$i_49",init:function(targetObj,propertyObj,durationMs,options){this._targetObj=targetObj;this._steps=[];this._currentStep=-1;if(propertyObj!==undefined){this.stepTo(propertyObj)}this._durationMs=durationMs!==undefined?durationMs:0;this._started=false;this._stepDirection=false;if(options&&options.easing){this.easing(options.easing)}else{this.easing("none")}if(options&&options.startTime!==undefined){this.startTime(options.startTime)}if(options&&options.beforeTween!==undefined){this.beforeTween(options.beforeTween)}if(options&&options.afterTween!==undefined){this.afterTween(options.afterTween)}},targetObj:function(targetObj){if(targetObj!==undefined){this._targetObj=targetObj}return this},properties:function(propertyObj){if(propertyObj!==undefined){this._steps=[];this._currentStep=-1;this.stepTo(propertyObj)}return this},repeatMode:function(val,count){if(val!==undefined){this._repeatMode=val;this.repeatCount(count);return this}return this._repeatMode},repeatCount:function(val){if(val!==undefined){this._repeatCount=val;this._repeatedCount=0;return this}return this._repeatCount},step:function(propertyObj,durationMs,easing){this.log("The step method has been renamed to stepTo(). Please update your code as the step() method will soon be removed.","warning");this.stepTo(propertyObj,durationMs,easing);return this},stepTo:function(propertyObj,durationMs,easing,delta){if(propertyObj!==undefined){this._steps.push({props:propertyObj,durationMs:durationMs,easing:easing,isDelta:delta})}return this},stepBy:function(propertyObj,durationMs,easing){this.stepTo(propertyObj,durationMs,easing,true);return this},duration:function(durationMs){if(durationMs!==undefined){this._durationMs=durationMs}return this},beforeTween:function(callback){if(callback!==undefined){this._beforeTween=callback}return this},afterTween:function(callback){if(callback!==undefined){this._afterTween=callback}return this},beforeStep:function(callback){if(callback!==undefined){this._beforeStep=callback}return this},afterStep:function(callback){if(callback!==undefined){this._afterStep=callback}return this},afterChange:function(callback){if(callback!==undefined){this._afterChange=callback}return this},targetObject:function(){return this._targetObj},easing:function(methodName){if(methodName!==undefined){if(ige.tween.easing[methodName]){this._easing=methodName}else{this.log("The easing method you have selected does not exist, please use a valid easing method. For a list of easing methods please inspect ige.tween.easing from your console.","error",ige.tween.easing)}}return this},startTime:function(timeMs){if(timeMs!==undefined){this._startTime=timeMs}return this},start:function(timeMs){if(timeMs!==undefined){this.startTime(timeMs+ige._currentTime)}ige.tween.start(this);this._targetObj._tweenArr=this._targetObj._tweenArr||[];this._targetObj._tweenArr.push(this);return this},stop:function(){ige.tween.stop(this);if(this._targetObj._tweenArr){this._targetObj._tweenArr.pull(this)}return this},startAll:function(){if(this._targetObj._tweenArr){this._targetObj._tweenArr.eachReverse(function(tweenItem){tweenItem.start()})}return this},stopAll:function(){if(this._targetObj._tweenArr){this._targetObj._tweenArr.eachReverse(function(tweenItem){tweenItem.stop()})}return this}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_49}var $i_50=$i_3.extend({classId:"$i_50",$i_50:true,init:function(urlOrObject,callback){this._loaded=false;this._cells=[];this._smoothing=ige._globalSmoothing;this.callback=callback;this._applyFilters=[];this._applyFiltersData=[];this._preFilters=[];this._preFiltersData=[];var type=typeof urlOrObject;if(type==="string"){if(urlOrObject){this.url(urlOrObject)}}if(type==="object"){this.assignSmartTextureImage(urlOrObject)}},id:function(id){if(id!==undefined){if(ige._register[id]){if(ige._register[id]===this){return this}this.log(`Cannot set ID of object to "${id}" because that ID is already in use by another object!`,"error")}else{if(this._id&&ige._register[this._id]){ige.unRegister(this)}this._id=id;ige.register(this);return this}}if(!this._id){if(this._url){this._id=ige.newIdFromString(this._url)}else{this._id=ige.newIdHex()}ige.register(this)}return this._id},url:function(url){if(url!==undefined){this._url=url;if(url.substr(url.length-2,2)==="js"){this._loadScript(url)}else{this._loadImage(url)}return this}return this._url},_loadImage:function(imageUrl){var image;var self=this;if(ige.isClient){ige.textureLoadStart(imageUrl,this);if(!ige._textureImageStore[imageUrl]){image=ige._textureImageStore[imageUrl]=this.image=this._originalImage=new Image;image._igeTextures=image._igeTextures||[];image._igeTextures.push(this);image.onload=function(){image._loaded=true;ige.devLog(`Texture image (${imageUrl}) loaded successfully`);var arr=image._igeTextures;var arrCount=arr.length;var i;var item;for(i=0;i0&&this._textureCtx){this._textureCtx.clearRect(0,0,this._textureCanvas.width,this._textureCanvas.height);this._textureCtx.drawImage(this._originalImage,0,0);var self=this;this._applyFilters.forEach(function(method,index){self._textureCtx.save();method(self._textureCanvas,self._textureCtx,self._originalImage,self,self._applyFiltersData[index]);self._textureCtx.restore()});this._preFilters.forEach(function(method,index){self._textureCtx.save();method(self._textureCanvas,self._textureCtx,self._originalImage,self,self._preFiltersData[index]);self._textureCtx.restore()})}ctx.drawImage(this.image,cell[0],cell[1],cell[2],cell[3],poly.x,poly.y,geom.x,geom.y);ige._drawCount++}else{this.log(`Cannot render texture using cell ${entity._cell} because the cell does not exist in the assigned texture!`,"error")}}if(this._mode===1){ctx.save();this.script.render(ctx,entity,this);ctx.restore();ige._drawCount++}}},removeFilter:function(method){var i;while((i=this._preFilters.indexOf(method))>-1){this._preFilters[i]=undefined;this._preFiltersData[i]=undefined}while((i=this._applyFilters.indexOf(method))>-1){this._applyFilters[i]=undefined;this._applyFiltersData[i]=undefined}this._preFilters=this._preFilters.clean();this._preFiltersData=this._preFiltersData.clean();this._applyFilters=this._applyFilters.clean();this._applyFiltersData=this._applyFiltersData.clean();this._rerenderFilters()},removeFilters:function(){this._applyFilters=[];this._applyFiltersData=[];this._preFilters=[];this._preFiltersData=[];this._rerenderFilters()},_rerenderFilters:function(){if(!this._textureCanvas)return;this.resize(this._textureCanvas.width,this._textureCanvas.height,false);var self=this;this._applyFilters.forEach(function(method,index){self._textureCtx.save();method(self._textureCanvas,self._textureCtx,self._originalImage,self,self._applyFiltersData[index]);self._textureCtx.restore()})},preFilter:function(method,data){if(method!==undefined){if(this._originalImage){if(!this._textureCtx){this._textureCanvas=document.createElement("canvas");this._textureCanvas.width=this._originalImage.width;this._textureCanvas.height=this._originalImage.height;this._textureCtx=this._textureCanvas.getContext("2d");if(!this._smoothing){this._textureCtx.imageSmoothingEnabled=false;this._textureCtx.webkitImageSmoothingEnabled=false;this._textureCtx.mozImageSmoothingEnabled=false}else{this._textureCtx.imageSmoothingEnabled=true;this._textureCtx.webkitImageSmoothingEnabled=true;this._textureCtx.mozImageSmoothingEnabled=true}}this.image=this._textureCanvas;this._preFilters[this._preFilters.length]=method;this._preFiltersData[this._preFiltersData.length]=!data?{}:data}return this}else{this.log("Cannot use pre-filter, no filter method was passed!","warning")}return this._preFilters[this._preFilters.length-1]},applyFilter:function(method,data){if(this._loaded){if(method!==undefined){if(this._originalImage){if(!this._textureCtx){this._textureCanvas=document.createElement("canvas");this._textureCanvas.width=this._originalImage.width;this._textureCanvas.height=this._originalImage.height;this._textureCtx=this._textureCanvas.getContext("2d");this._textureCtx.clearRect(0,0,this._textureCanvas.width,this._textureCanvas.height);this._textureCtx.drawImage(this._originalImage,0,0);if(!this._smoothing){this._textureCtx.imageSmoothingEnabled=false;this._textureCtx.webkitImageSmoothingEnabled=false;this._textureCtx.mozImageSmoothingEnabled=false}else{this._textureCtx.imageSmoothingEnabled=true;this._textureCtx.webkitImageSmoothingEnabled=true;this._textureCtx.mozImageSmoothingEnabled=true}}this.image=this._textureCanvas;if(this._preFilters.length<=0){this._textureCtx.save();method(this._textureCanvas,this._textureCtx,this._originalImage,this,data);this._textureCtx.restore()}this._applyFilters[this._applyFilters.length]=method;this._applyFiltersData[this._applyFiltersData.length]=!data?{}:data}}else{this.log("Cannot apply filter, no filter method was passed!","warning")}}else{this.log("Cannot apply filter, the texture you are trying to apply the filter to has not yet loaded!","error")}return this},pixelData:function(x,y){if(this._loaded){if(this.image){if(!this._textureCtx){this._textureCanvas=document.createElement("canvas");this._textureCanvas.width=this.image.width;this._textureCanvas.height=this.image.height;this._textureCtx=this._textureCanvas.getContext("2d");if(!this._smoothing){this._textureCtx.imageSmoothingEnabled=false;this._textureCtx.webkitImageSmoothingEnabled=false;this._textureCtx.mozImageSmoothingEnabled=false}else{this._textureCtx.imageSmoothingEnabled=true;this._textureCtx.webkitImageSmoothingEnabled=true;this._textureCtx.mozImageSmoothingEnabled=true}this._textureCtx.drawImage(this.image,0,0)}else{this._textureCtx=this._textureCtx}return this._textureCtx.getImageData(x,y,1,1).data}}else{this.log("Cannot read pixel data, the texture you are trying to read data from has not yet loaded!","error")}return this},clone:function(){return this.textureFromCell(1)},stringify:function(){var str=`new ${this.classId()}('${this._url}')`;str+=this._stringify();return str},_stringify:function(){return""},destroy:function(){delete this._eventListeners;if(this.image&&this.image._igeTextures){this.image._igeTextures.pull(this)}ige._textureStore.pull(this);delete this.image;delete this.script;delete this._textureCanvas;delete this._textureCtx;this._destroyed=true}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_50}var $i_51=$i_50.extend({classId:"$i_51",$i_52:true,init:function(url,horizontalCells,verticalCells,shouldScale,spriteCellSheet,entity){var self=this;self.shouldScale=shouldScale;self.spriteCellSheet=spriteCellSheet;self.horizontalCells(horizontalCells||1);self.verticalCells(verticalCells||1);var callbackIfNotLoaded=function(err){if(err&&entity){var entityType=entity._category==="item"?entity._stats.itemTypeId:entity._stats.type;var defaultUrl=ige.game.getAsset(`${entity._category}Types`,entityType).cellSheet.url;$i_50.prototype.init.call(self,defaultUrl)}};$i_50.prototype.init.call(this,url,spriteCellSheet&&entity?callbackIfNotLoaded:undefined)},_textureLoaded:function(){if(this.image){this._sheetImage=this.image;this._applyCells()}else{this.log("Cannot create cell-sheet because texture has not loaded an image!","error")}$i_50.prototype._textureLoaded.call(this)},cellCount:function(){return this.horizontalCells()*this.verticalCells()},horizontalCells:function(val){if(val!==undefined){this._cellColumns=val;return this}return this._cellColumns},verticalCells:function(val){if(val!==undefined){this._cellRows=val;return this}return this._cellRows},_applyCells:function(){var imgWidth,imgHeight,rows,columns,cellWidth,cellHeight,cellIndex,xPos,yPos;if(this.image){if(this._cellRows&&this._cellColumns){imgWidth=this._sizeX;imgHeight=this._sizeY;if(this.shouldScale){imgWidth=this._sizeX*ige.scaleMapDetails.scaleFactor.x;imgHeight=this._sizeY*ige.scaleMapDetails.scaleFactor.y}rows=this._cellRows;columns=this._cellColumns;cellWidth=this._cellWidth=imgWidth/columns;cellHeight=this._cellHeight=imgHeight/rows;if(cellWidth!==parseInt(cellWidth,10)){this.log(`Cell width is a floating-point number! (Image Width ${imgWidth} / Number of Columns ${columns} = ${cellWidth}) in file: ${this._url}`,"warning")}if(cellHeight!==parseInt(cellHeight,10)){this.log(`Cell height is a floating-point number! (Image Height ${imgHeight} / Number of Rows ${rows} = ${cellHeight}) in file: ${this._url}`,"warning")}if(rows>1||columns>1){for(cellIndex=1;cellIndex<=rows*columns;cellIndex++){yPos=Math.ceil(cellIndex/columns)-1;xPos=cellIndex-columns*yPos-1;this._cells[cellIndex]=[xPos*cellWidth,yPos*cellHeight,cellWidth,cellHeight]}}else{this._cells[1]=[0,0,this._sizeX,this._sizeY]}}}},stringify:function(){var str=`new ${this.classId()}('${this.url()}', ${this.horizontalCells()}, ${this.verticalCells()})`;return str}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_50}var $i_52=$i_50.extend({classId:"$i_52",$i_52:true,init:function(url,cells){this._spriteCells=cells;$i_50.prototype.init.call(this,url)},_textureLoaded:function(){if(this.image){this._sheetImage=this.image;var i;var cells=this._spriteCells;if(!cells){this.log("No cell data provided for sprite sheet, attempting to automatically detect sprite bounds...");cells=this.detectCells(this._sheetImage)}for(i=0;i=rect.x&&x<=rect.x+rect.width&&y>=rect.y&&y<=rect.y+rect.height){return true}}return false},_determineRect:function(pixels,x,y){var pixArr=[{x:x,y:y}];var rect={x:x,y:y,width:1,height:1};var currentPixel;while(pixArr.length){currentPixel=pixArr.shift();if(currentPixel.x>rect.x+rect.width){rect.width=currentPixel.x-rect.x+1}if(currentPixel.y>rect.y+rect.height){rect.height=currentPixel.y-rect.y+1}if(currentPixel.ximageData.length){run=false;console.log("Image JSON Decode Error!")}}},lineHeightModifier:function(val){if(typeof val!=="undefined"){this._lineHeightModifier=val}},measureTextWidth:function(text){if(this._loaded){var characterIndex;var charCodeMap=this._charCodeMap;var measuredWidthMap=this._measuredWidthMap;var charIndex;var lineArr=[];var lineIndex;var measuredWidth;var maxWidth=0;if(text.indexOf("\n")>-1){lineArr=text.split("\n")}else{lineArr.push(text)}for(lineIndex=0;lineIndexmaxWidth){maxWidth=measuredWidth}}return measuredWidth}return-1},render:function(ctx,entity){if(entity._renderText&&this._loaded){var _ctx=ctx;var text=entity._renderText;var lineText;var lineArr=[];var lineIndex;var characterIndex;var charCodeMap=this._charCodeMap;var charPosMap=this._charPosMap;var measuredWidthMap=this._measuredWidthMap;var pixelWidthMap=this._pixelWidthMap;var renderX=0;var renderY=0;var renderStartX=0;var renderStartY=0;var masterX=0;var masterY=0;var lineWidth=[];var lineHeight=this._sizeY-2;var singleLineWidth=0;var totalWidth=0;var totalHeight;var charIndex;if(text.indexOf("\n")>-1){lineArr=text.split("\n")}else{lineArr.push(text)}totalHeight=lineHeight*lineArr.length;switch(entity._textAlignY){case 0:renderStartY=-(lineHeight*lineArr.length/2)-entity._textLineSpacing*((lineArr.length-1)/2);break;case 1:renderStartY=-(lineHeight*lineArr.length/2)-entity._textLineSpacing*((lineArr.length-1)/2);break;case 2:renderStartY=-(lineHeight*lineArr.length/2)-entity._textLineSpacing*((lineArr.length-1)/2);break;}for(lineIndex=0;lineIndextotalWidth){totalWidth=singleLineWidth}singleLineWidth=0}switch(entity._textAlignX){case 0:renderStartX=-entity._bounds2d.x2;break;case 1:renderStartX=-totalWidth/2;break;case 2:renderStartX=entity._bounds2d.x2-totalWidth;break;}for(lineIndex=0;lineIndex-1){lineArr=text.split("\n")}else{lineArr.push(text)}ctx.font=entity._nativeFont;ctx.textBaseline="middle";if(entity._nativeStroke){ctx.lineWidth=entity._nativeStroke;if(entity._nativeStrokeColor){ctx.strokeStyle=entity._nativeStrokeColor}else{ctx.strokeStyle=entity._colorOverlay}}for(lineIndex=0;lineIndexmaxWidth){maxWidth=measuredWidth}}return maxWidth}return-1},render:function(ctx,entity){if(entity._nativeFont&&entity._renderText){var text=entity._renderText;var lineArr=[];var textSize;var renderStartY;var renderY;var lineHeight;var i;ctx.font=entity._nativeFont;ctx.textBaseline="middle";if(entity._colorOverlay){ctx.fillStyle=entity._colorOverlay}if(entity._textAlignX===0){ctx.textAlign="left";ctx.translate(-entity._bounds2d.x2,0)}if(entity._textAlignX===1){ctx.textAlign="center"}if(entity._textAlignX===2){ctx.textAlign="right";ctx.translate(entity._bounds2d.x2,0)}if(entity._nativeStroke){ctx.lineWidth=entity._nativeStroke;if(entity._nativeStrokeColor){ctx.strokeStyle=entity._nativeStrokeColor}else{ctx.strokeStyle=entity._colorOverlay}}if(text.indexOf("\n")>-1){lineArr=text.split("\n")}else{lineArr.push(text)}lineHeight=Math.floor(entity._bounds2d.y/lineArr.length);renderStartY=-((lineHeight+entity._textLineSpacing)/2)*(lineArr.length-1);for(i=0;i-1){return true}}}}else{return this._groups&&this._groups.indexOf(groupName)>-1}return false},groups:function(){return this._groups||[]},groupCount:function(){return this._groups?this._groups.length:0},removeGroup:function(){if(this._groups){var arrCount=arguments.length;var groupName;var groupNameCount;while(arrCount--){groupName=arguments[arrCount];if(groupName instanceof Array){groupNameCount=groupName.length;while(groupNameCount--){this._groups.pull(groupName[groupNameCount]);ige.groupUnRegister(this,groupName[groupNameCount])}}else{this._groups.pull(groupName);ige.groupUnRegister(this,groupName)}}}return this},removeAllGroups:function(){if(this._groups){var arr=this._groups;var arrCount=arr.length;while(arrCount--){ige.groupUnRegister(this,arr[arrCount])}delete this._groups}return this},addBehaviour:function(id,behaviour,duringTick){if(typeof id==="string"){if(typeof behaviour==="function"){if(duringTick){this._tickBehaviours=this._tickBehaviours||[];this._tickBehaviours.push({id:id,method:behaviour})}else{this._updateBehaviours=this._updateBehaviours||[];this._updateBehaviours.push({id:id,method:behaviour})}return this}else{this.log("The behaviour you passed is not a function! The second parameter of the call must be a function!","error")}}else{this.log("Cannot add behaviour to object because the specified behaviour id is not a string. You must provide two parameters with the addBehaviour() call, an id:String and a behaviour:Function. Adding a behaviour with an id allows you to remove it by it's id at a later stage!","error")}return false},removeBehaviour:function(id,duringTick){if(id!==undefined){var arr,arrCount;if(duringTick){arr=this._tickBehaviours}else{arr=this._updateBehaviours}if(arr){arrCount=arr.length;while(arrCount--){if(arr[arrCount].id===id){arr.splice(arrCount,1);return this}}}}return false},hasBehaviour:function(id,duringTick){if(id!==undefined){var arr,arrCount;if(duringTick){arr=this._tickBehaviours}else{arr=this._updateBehaviours}if(arr){arrCount=arr.length;while(arrCount--){if(arr[arrCount].id===id){return true}}}}return false},drawBounds:function(val){if(val!==undefined){this._drawBounds=val;return this}return this._drawBounds},drawBoundsData:function(val){if(val!==undefined){this._drawBoundsData=val;return this}return this._drawBoundsData},drawMouse:function(val){if(val!==undefined){this._drawMouse=val;return this}return this._drawMouse},drawMouseData:function(val){if(val!==undefined){this._drawMouseData=val;return this}return this._drawMouseData},$:function(id){var obj=ige.$(id);if(obj._parent===this){return obj}else{var ancestor=obj.parent(this.id());if(ancestor){return obj}else{return undefined}}},$$:function(categoryName){var objArr=ige.$$(categoryName);var arrCount=objArr.length;var obj;var finalArr=[];var thisId=this.id();while(arrCount--){obj=objArr[arrCount];if(obj._parent===this||obj.parent(thisId)){finalArr.push(obj)}}return finalArr},parent:function(id){if(!id){return this._parent}if(this._parent){if(this._parent.id()===id){return this._parent}else{return this._parent.parent(id)}}return undefined},children:function(){return this._children},mount:function(obj){if(obj){if(obj===this){this.log("Cannot mount an object to itself!","error");return this}if(ige.isClient){ige.client.emit("mount",{entity:this,parent:obj})}if(obj._children){this.id();if(this._parent){if(this._parent===obj){return this}else{this.unMount()}}this._parent=obj;if(ige.isClient&&ige.$("baseScene")._orphans){delete ige.$("baseScene")._orphans[this._id]}if(!this._ignoreCamera&&this._parent._ignoreCamera){this._ignoreCamera=this._parent._ignoreCamera}if(this._parent._streamRoomId){this._streamRoomId=this._parent._streamRoomId}obj._children.push(this);this._parent._childMounted(this);if(obj.updateTransform){obj.updateTransform();obj.aabb(true)}if(obj._compositeCache){this._compositeParent=true}else{delete this._compositeParent}this._mounted(this._parent);this.emit("mounted",this._parent);return this}else{this.log("Cannot mount object because it has no _children array! If you are mounting to a custom class, ensure that you have called the prototype.init() method of your super-class during the init of your custom class.","warning");return false}}else{this.log("Cannot mount non-existent object!","error")}},unMount:function(){if(ige.isClient){ige.client.emit("unMount",this)}if(this._parent){var childArr=this._parent._children;var index=childArr.indexOf(this);var oldParent=this._parent;if(index>-1){childArr.splice(index,1);this._parent._childUnMounted(this);this._parent=null;this._unMounted(oldParent);return this}else{return false}}else{return false}},hasParent:function(parentId,fresh){var bool=false;if(!fresh&&this._hasParent&&this._hasParent[parentId]!==undefined){return this._hasParent[parentId]}if(this._parent){if(this._parent.id()===parentId){bool=true}else{bool=this._parent.hasParent(parentId,fresh)}}this._hasParent=this._hasParent||{};this._hasParent[parentId]=bool;return bool},clone:function(options){if(options===undefined){options={}}if(options.id===undefined){options.id=false}if(options.mount===undefined){options.mount=false}if(options.transform===undefined){options.transform=true}var newObject=eval(this.stringify(options));return newObject},mode:function(val){if(val!==undefined){this._mode=val;return this}return this._mode},isometric:function(val){if(val===true){this._mode=1;return this}if(val===false){this._mode=0;return this}return this._mode===1},isometricMounts:function(val){if(val===true){this._mountMode=1;return this}if(val===false){this._mountMode=0;return this}return this._mountMode===1},indestructible:function(val){if(typeof val!=="undefined"){this._indestructible=val;return this}return this._indestructible},layer:function(val){if(val!==undefined){this._layer=val;if(ige.isClient)ige.client.emit("setLayer",{entity:this,layer:val});return this}return this._layer},depth:function(val){if(val!==undefined){this._depth=val;if(ige.isClient)ige.client.emit("setDepth",{entity:this,depth:val});return this}return this._depth},destroyChildren:function(){var arr=this._children;var arrCount;if(arr){arrCount=arr.length;while(arrCount--){arr[arrCount].destroy()}}this._children=[];return this},destroyBehaviours:function(){delete this._updateBehaviours;delete this._tickBehaviours},destroyComponents:function(){var arr=this._components;var arrCount;if(arr){arrCount=arr.length;while(arrCount--){if(arr[arrCount].destroy){arr[arrCount].destroy()}}}delete this._components;return this},depthSortMode:function(val){if(val!==undefined){this._depthSortMode=val;return this}return this._depthSortMode},depthSortChildren:function(){if(this._depthSortMode!==-1){var arr=this._children;var arrCount;var sortObj;var i;var j;if(arr){arrCount=arr.length;if(arrCount>1){if(this._mountMode===1){if(this._depthSortMode===0){sortObj={adj:[],c:[],p:[],order:[],order_ind:arrCount-1};for(i=0;i-1){copyObj[i]=`{ref:${refIndex}}`;this.log(`Possible circular reference for property ${i}`)}else{ref.push(obj[i]);copyObj[i]=this._objSaveReassign(obj[i],ref)}}else{specProp=this.saveSpecialProp(obj,i);if(specProp){if(typeof specProp==="object"&&!(specProp instanceof Array)){for(specPropKey in specProp){if(specProp.hasOwnProperty(specPropKey)){copyObj[specPropKey]=specProp[specPropKey]}}}else{copyObj[i]=specProp}}}}else{copyObj[i]=obj[i]}}}return copyObj}else{return obj}},_objLoadReassign:function(obj,newProps){var specialKeys=this._specialProp;var specProp;var specPropKey;var i;for(i in newProps){if(newProps.hasOwnProperty(i)){if(specialKeys.indexOf(i)===-1){if(typeof newProps[i]==="object"&&obj[i]){this._objLoadReassign(obj[i],newProps[i])}else{obj[i]=newProps[i]}}else{specProp=this.loadSpecialProp(newProps,i);if(specProp){if(typeof specProp==="object"&&!(specProp instanceof Array)){for(specPropKey in specProp){if(specProp.hasOwnProperty(specPropKey)){obj[specPropKey]=specProp[specPropKey]}}}else{obj[i]=specProp}}}}}},stringify:function(options){if(options===undefined){options={}}var str=`new ${this.classId()}()`;if(options.id!==false){str+=`.id('${this.id()}')`}if(options.mount!==false&&this.parent()){str+=`.mount(ige.$('${this.parent().id()}'))`}str+=this._stringify(options);return str},_stringify:function(options){if(options===undefined){options={}}var str="";var i;for(i in this){if(this.hasOwnProperty(i)&&this[i]!==undefined){switch(i){case"_category":str+=`.category(${this.category()})`;break;case"_drawBounds":str+=`.drawBounds(${this.drawBounds()})`;break;case"_drawBoundsData":str+=`.drawBoundsData(${this.drawBoundsData()})`;break;case"_drawMouse":str+=`.drawMouse(${this.drawMouse()})`;break;case"_mode":str+=`.mode(${this.mode()})`;break;case"_isometricMounts":str+=`.isometricMounts(${this.isometricMounts()})`;break;case"_indestructible":str+=`.indestructible(${this.indestructible()})`;break;case"_layer":str+=`.layer(${this.layer()})`;break;case"_depth":str+=`.depth(${this.depth()})`;break;}}}return str}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_55}var $i_56=$i_55.extend({classId:"$i_56",init:function(defaultData={}){$i_55.prototype.init.call(this);var translateX=defaultData.translate&&defaultData.translate.x?defaultData.translate.x:0;var translateY=defaultData.translate&&defaultData.translate.y?defaultData.translate.y:0;var rotate=defaultData.rotate||0;this._specialProp.push("_texture");this._specialProp.push("_eventListeners");this._specialProp.push("_aabb");this._anchor=new $i_4(0,0);this._renderPos={x:0,y:0};this._computedOpacity=1;this._opacity=1;this._cell=1;this._flip=0;this._deathTime=undefined;this._bornTime=ige._currentTime;this._translate=new $i_5(translateX,translateY,rotate);this._oldTranform=[];this._hasMoved=true;this._rotate=new $i_5(0,0,rotate);this._scale=new $i_5(1,1,1);this._origin=new $i_5(0.5,0.5,0.5);this._bounds2d=new $i_4(40,40);this._bounds3d=new $i_5(0,0,0);this._oldBounds2d=new $i_4(40,40);this._oldBounds3d=new $i_5(0,0,0);this._highlight=false;this._mouseEventsActive=false;this._velocity=new $i_5(0,0,0);this._localMatrix=new $i_8;this._worldMatrix=new $i_8;this._oldWorldMatrix=new $i_8;this._lastSeenBy={};this._inView=true;this._hidden=false;this._stats={};this._streamDataQueued=[];this._isBeingRemoved=false;this._keyFrames=[];this.prevKeyFrame=[ige.now,[this._translate.x,this._translate.y,this._rotate.z]];this._lastTransformAt=null;this.lastServerStreamedPosition=null;this.lastTeleportedAt=0;if(ige.isClient){this.anchorOffset={x:0,y:0,rotate:0};this.addComponent(TweenComponent)}this.streamSections(["transform"])},show:function(){var self=this;if(ige.isServer){this.streamUpdateData([{isHidden:false}])}else if(ige.isClient){self._hidden=false;ige.client.emit("show",this)}return this},setState:function(stateId,defaultData){var self=this;if(stateId==undefined||self._stats.states==undefined||self._stats.states[stateId]==undefined){stateId=this.getDefaultStateId()}var newState=self._stats.states&&self._stats.states[stateId]||{};if(newState&&newState.body){self._stats.currentBody=self._stats.bodies[newState.body]}if(ige.isServer){self.streamUpdateData([{stateId:stateId}])}else if(ige.isClient){self._stats.stateId=stateId;if(newState.sound){for(var soundId in newState.sound){var sound=newState.sound[soundId];ige.sound.playSound(sound,this._translate,soundId)}}}self.previousState=newState;self.updateBody(defaultData)},hide:function(){var self=this;if(ige.isServer){this.streamUpdateData([{isHidden:true}])}else if(ige.isClient){self._hidden=true;ige.client.emit("hide",this);self.texture("")}return this},isHidden:function(){return this._hidden===true},shouldBeInvisible:function(playerA,playerB){return playerA&&playerB&&(playerA.isHostileTo(playerB)&&this._stats.isInvisible==true||playerA.isFriendlyTo(playerB)&&this._stats.isInvisibleToFriendly==true||playerA.isNeutralTo(playerB)&&this._stats.isInvisibleToNeutral==true)},imageUrlToHash:function(url){var hash=0;if(url.length==0){return hash}for(var i=0;i0||val===null){this._cell=val;return this}return this._cell},cellById:function(val){if(val!==undefined){if(this._texture){var i;var tex=this._texture;var cells=tex._cells;for(i=1;i10000){$i_56.prototype.log("$i_56 1255");break}rect.thisCombineRect(arr[arrCount].compositeAabb(inverse))}}return rect},compositeStream:function(val){if(val!==undefined){this._compositeStream=val;return this}return this._compositeStream},_childMounted:function(child){if(this.compositeStream()){child.compositeStream(true);child.streamMode(this.streamMode());child.streamControl(this.streamControl())}$i_55.prototype._childMounted.call(this,child);if(this.compositeCache()){this.cacheDirty(true)}},_swapVars:function(x,y){return[y,x]},_internalsOverlap:function(x0,x1,y0,y1){var tempSwap;if(x0>x1){tempSwap=this._swapVars(x0,x1);x0=tempSwap[0];x1=tempSwap[1]}if(y0>y1){tempSwap=this._swapVars(y0,y1);y0=tempSwap[0];y1=tempSwap[1]}if(x0>y0){tempSwap=this._swapVars(x0,y0);x0=tempSwap[0];y0=tempSwap[1];tempSwap=this._swapVars(x1,y1);x1=tempSwap[0];y1=tempSwap[1]}return y0otherX+otherY+otherObject._translate.z},mouseEventsActive:function(val){if(val!==undefined){this._mouseEventsActive=val;return this}return this._mouseEventsActive},ignoreCameraComposite:function(val){var i;var arr=this._children;var arrCount=arr.length;this._ignoreCamera=val;for(i=0;i=this._bornTime){delete this._streamDataCache;if(!isForOrphans&&ige.gameLoopTickHasExecuted){this._processUpdateBehaviours(ctx,tickDelta)}this._frameAlternatorCurrent=ige._frameAlternator}else{if(this._parent){this._birthMount=this._parent.id()}this.unMount();ige.spawnQueue(this)}}if(!isForOrphans){$i_55.prototype.update.call(this,ctx,tickDelta)}},parseEntityObject:function(stats){var self=this;if(typeof stats==="object"){for(var key in stats){if(typeof stats[key]==="object"){self.parseEntityObject(stats[key])}else if(/^-?\d+$/.test(stats[key])){stats[key]=parseFloat(stats[key])}}}},tick:function(ctx,dontTransform){if(this._inView)ige.inViewCount++;if(!this._hidden&&this._inView&&(!this._parent||this._parent._inView)||mode!="play"){ige.tickCount++;this._processTickBehaviours(ctx);if(this._mouseEventsActive){if(this._processTriggerHitTests()){ige.input.queueEvent(this,this._mouseInTrigger,null)}else{if(ige.input.mouseMove){this._handleMouseOut(ige.input.mouseMove)}}}if(!this._dontRender){if(this._cache||this._compositeCache){if(this._cacheDirty){this._refreshCache(dontTransform)}this._renderCache(ctx)}else{if(!dontTransform){this._transformContext(ctx)}this._renderEntity(ctx,dontTransform)}}if(this._streamMode===1||this._streamMode===2){this.streamSync()}if(this._compositeCache){if(this._cacheDirty){$i_55.prototype.tick.call(this,this._cacheCtx);this._renderCache(ctx);this._cacheDirty=false}}else{$i_55.prototype.tick.call(this,ctx)}}},playEffect:function(type){if(this._stats&&this._stats.effects&&this._stats.effects[type]){var effect=this._stats.effects[type];if(ige.isServer){if(type=="move"||type=="idle"||type=="none"){this.streamUpdateData([{effect:type}])}}else if(ige.isClient){if(this._pixiContainer&&this._pixiContainer._destroyed){return}var position=this._translate;if(this._category==="item"&&this._stats.currentBody&&(this._stats.currentBody.type==="spriteOnly"||this._stats.currentBody.type==="none")){var ownerUnit=this.getOwnerUnit();position=ownerUnit&&ownerUnit._pixiContainer||position}if(effect.animation!=undefined&&effect.animation!="none"&&effect.animation!=""){this.applyAnimationById(effect.animation)}if(effect.projectileType){var projectile=ige.game.getAsset("projectileTypes",effect.projectileType);if(projectile){var position=ige.game.lastProjectileHitPosition||this.body&&this.body.getPosition()||this._translate;if(this.body){position.x*=this._b2dRef._scaleRatio;position.y*=this._b2dRef._scaleRatio}projectile.defaultData={translate:{x:position.x,y:position.y},rotate:this._rotate.z};new Projectile(projectile)}}var shouldRepeat=type==="move";var isAlreadyPlaying=false;if(this.isPlayingSound){this.isPlayingSound.loop=shouldRepeat;if(shouldRepeat){isAlreadyPlaying=true;this.isPlayingSound.play()}}if(effect.sound){for(var soundKey in effect.sound){if(!isAlreadyPlaying){this.isPlayingSound=ige.sound.playSound(effect.sound[soundKey],position,soundKey,shouldRepeat);if(this.isPlayingSound){this.isPlayingSound.effect=effect.sound[soundKey]}}}}var angle=this._rotate.z;if(type=="attacked"){var attacker=this.lastAttackedBy;if(attacker){angle=Math.atan2(attacker._translate.y-this._translate.y,attacker._translate.x-this._translate.x)+Math.radians(90)}}this.tween.start(effect.tween,angle)}else if(ige.isServer){if(effect.runScript){ige.script.runScript(effect.runScript,{})}}}},_processTriggerHitTests:function(){var mp,mouseTriggerPoly;if(ige._currentViewport){if(!this._mouseAlwaysInside){mp=this.mousePosWorld();if(mp){if(this._triggerPolygon&&this[this._triggerPolygon]){mouseTriggerPoly=this[this._triggerPolygon](mp)}else{if(this._parent&&this._parent._mountMode===1){mouseTriggerPoly=this.bounds3dPolygon()}else{mouseTriggerPoly=this.aabb()}}return mouseTriggerPoly.xyInside(mp.x,mp.y)}}else{return true}}return false},_refreshCache:function(dontTransform){var _canvas=this._cacheCanvas;var _ctx=this._cacheCtx;if(this._compositeCache){var aabbC=this.compositeAabb(true);this._compositeAabbCache=aabbC;if(aabbC.width>0&&aabbC.height>0){_canvas.width=Math.ceil(aabbC.width);_canvas.height=Math.ceil(aabbC.height)}else{_canvas.width=2;_canvas.height=2}_ctx.translate(-aabbC.x,-aabbC.y);this.emit("compositeReady")}else{if(this._bounds2d.x>0&&this._bounds2d.y>0){_canvas.width=this._bounds2d.x;_canvas.height=this._bounds2d.y}else{_canvas.width=1;_canvas.height=1}_ctx.translate(this._bounds2d.x2,this._bounds2d.y2);this._cacheDirty=false}if(!dontTransform){this._transformContext(_ctx)}this._renderEntity(_ctx,dontTransform)},flip:function(flip){if(ige.isServer){if(flip!=this._stats.flip){this.streamUpdateData([{flip:flip}])}}else if(ige.isClient){if(this._stats.flip!=flip){var entity=this._pixiTexture;if(entity){var x=Math.abs(entity.scale.x);var y=Math.abs(entity.scale.y);if(flip==0){entity.scale.set(x,y)}if(flip==1){entity.scale.set(-x,y)}if(flip==2){entity.scale.set(x,-y)}if(flip==3){entity.scale.set(-x,-y)}}}}this._stats.flip=flip},_renderEntity:function(ctx){if(this._opacity>0){if(this._backgroundPattern){if(!this._backgroundPatternFill){if(ctx){this._backgroundPatternFill=ctx.createPattern(this._backgroundPattern.image,this._backgroundPatternRepeat)}}if(this._backgroundPatternFill){ctx.save();ctx.fillStyle=this._backgroundPatternFill;ctx.translate(-this._bounds2d.x2,-this._bounds2d.y2);ctx.rect(0,0,this._bounds2d.x,this._bounds2d.y);if(this._backgroundPatternTrackCamera){ctx.translate(-ige._currentCamera._translate.x,-ige._currentCamera._translate.y);ctx.scale(ige._currentCamera._scale.x,ige._currentCamera._scale.y)}ctx.fill();ige._drawCount++;if(this._backgroundPatternIsoTile){ctx.translate(-Math.floor(this._backgroundPattern.image.width)/2,-Math.floor(this._backgroundPattern.image.height/2));ctx.fill();ige._drawCount++}ctx.restore()}}var texture=this._texture;if(texture&&texture._loaded){if(this._stats.flip==1){ctx.save();ctx.scale(-1,1)}if(this._stats.flip==2){ctx.save();ctx.scale(1,-1)}if(this._stats.flip==3){ctx.save();ctx.scale(-1,-1)}texture.render(ctx,this,ige._tickDelta);if(this._stats.flip>0){ctx.restore()}if(this._highlight){ctx.globalCompositeOperation="lighter";texture.render(ctx,this)}}if(this._compositeCache&&ige._currentViewport._drawCompositeBounds){ctx.fillStyle="rgba(0, 0, 255, 0.3)";ctx.fillRect(-this._bounds2d.x2,-this._bounds2d.y2,this._bounds2d.x,this._bounds2d.y);ctx.fillStyle="#ffffff";ctx.fillText("Composite Entity",-this._bounds2d.x2,-this._bounds2d.y2-15);ctx.fillText(this.id(),-this._bounds2d.x2,-this._bounds2d.y2-5)}}},_renderCache:function(ctx){ctx.save();if(this._compositeCache){var aabbC=this._compositeAabbCache;ctx.translate(this._bounds2d.x2+aabbC.x,this._bounds2d.y2+aabbC.y);if(this._parent&&this._parent._ignoreCamera){var cam=ige._currentCamera}}ctx.drawImage(this._cacheCanvas,-this._bounds2d.x2,-this._bounds2d.y2);if(ige._currentViewport._drawCompositeBounds){ctx.fillStyle="rgba(0, 255, 0, 0.5)";ctx.fillRect(-this._bounds2d.x2,-this._bounds2d.y2,this._cacheCanvas.width,this._cacheCanvas.height);ctx.fillStyle="#ffffff";ctx.fillText("Composite Cache",-this._bounds2d.x2,-this._bounds2d.y2-15);ctx.fillText(this.id(),-this._bounds2d.x2,-this._bounds2d.y2-5)}ige._drawCount++;if(this._highlight){ctx.globalCompositeOperation="lighter";ctx.drawImage(this._cacheCanvas,-this._bounds2d.x2,-this._bounds2d.y2);ige._drawCount++}ctx.restore()},_transformPoint:function(point){if(this._parent){var tempMat=new $i_8;tempMat.copy(this._parent._worldMatrix);tempMat.multiply(this._localMatrix);tempMat.getInverse().transformCoord(point,this)}else{this._localMatrix.transformCoord(point,this)}return point},_transformPoints:function(points){var point;var pointCount=points.length;var x=0;while(pointCount--){x++;if(x>10000){$i_56.prototype.log("$i_56 1964");break}point=points[pointCount];if(this._parent){var tempMat=new $i_8;tempMat.copy(this._parent._worldMatrix);tempMat.multiply(this._localMatrix);tempMat.getInverse().transformCoord(point,this)}else{this._localMatrix.transformCoord(point,this)}}},_stringify:function(options){if(options===undefined){options={}}var str=$i_55.prototype._stringify.call(this,options);var i;for(i in this){if(this.hasOwnProperty(i)&&this[i]!==undefined){switch(i){case"_opacity":str+=`.opacity(${this.opacity()})`;break;case"_texture":str+=`.texture(ige.$('${this.texture().id()}'))`;break;case"_cell":str+=`.cell(${this.cell()})`;break;case"_translate":if(options.transform!==false&&options.translate!==false){str+=`.translateTo(${this._translate.x}, ${this._translate.y}, ${this._translate.z})`}break;case"_rotate":if(options.transform!==false&&options.rotate!==false){str+=`.rotateTo(${this._rotate.x}, ${this._rotate.y}, ${this._rotate.z})`}break;case"_scale":if(options.transform!==false&&options.scale!==false){str+=`.scaleTo(${this._scale.x}, ${this._scale.y}, ${this._scale.z})`}break;case"_origin":if(options.origin!==false){str+=`.originTo(${this._origin.x}, ${this._origin.y}, ${this._origin.z})`}break;case"_anchor":if(options.anchor!==false){str+=`.anchor(${this._anchor.x}, ${this._anchor.y})`}break;case"_width":if(typeof this.width()==="string"){str+=`.width('${this.width()}')`}else{str+=`.width(${this.width()})`}break;case"_height":if(typeof this.height()==="string"){str+=`.height('${this.height()}')`}else{str+=`.height(${this.height()})`}break;case"_bounds3d":str+=`.bounds3d(${this._bounds3d.x}, ${this._bounds3d.y}, ${this._bounds3d.z})`;break;case"_deathTime":if(options.deathTime!==false&&options.lifeSpan!==false){str+=`.deathTime(${this.deathTime()})`}break;case"_highlight":str+=`.highlight(${this.highlight()})`;break;}}}return str},destroy:function(destroyOrphan){$i_56.prototype.log(`igeEntity: destroy ${this._category} ${this.id()}`);this._alive=false;if(this.gluedEntities&&this.gluedEntities.length>0){this.gluedEntities.forEach(function(glueEntity){var entity=ige.$(glueEntity.id);if(entity&&(entity._pixiText||entity._pixiTexture)){var texture=entity._pixiText||entity._pixiTexture;entity.unMount();entity.destroy();delete ige.entityTrack.trackEntityById[glueEntity.id]}})}if(ige.isClient){ige.client.emit("destroyTexture",this)}for(var region in ige.regionManager.entitiesInRegion){delete ige.regionManager.entitiesInRegion[region][this.id()]}$i_56.prototype.log(`entity destroyed ${this.id()} category: ${this._category} ${this._stats?this._stats.name:""}`);this.emit("destroyed",this);$i_55.prototype.destroy.call(this);if(ige.isClient&&ige.$("baseScene")._orphans){delete ige.$("baseScene")._orphans[this._id]}},clearAllPointers:function(){var keysToDelete=["ability","animation","attribute","attributeBarsContainer","fadingTextContainer","inventory","minimapUnit","unitNameLabel","unitUi","_aabb","_bounds2d","_bounds3d","_rotate","_velocity"];for(var i=0;i=rect2.x2||rect2.x1>=rect1.x2){return false}if(rect1.y1>=rect2.y2||rect2.y1>=rect1.y2){return false}return true},translateToPoint:function(point){if(point!==undefined){this._translate.x=point.x;this._translate.y=point.y;this._translate.z=point.z}else{$i_56.prototype.log("translateToPoint() called with a missing or undefined point parameter!","error")}return this._entity||this},translateToTile:function(x,y,z){if(this._parent&&this._parent._tileWidth!==undefined&&this._parent._tileHeight!==undefined){var finalZ;if(z!==undefined){finalZ=z*this._parent._tileWidth}else{finalZ=this._translate.z}this.translateTo(x*this._parent._tileWidth+this._parent._tileWidth/2,y*this._parent._tileHeight+this._parent._tileWidth/2,finalZ)}else{$i_56.prototype.log("Cannot translate to tile because the entity is not currently mounted to a tile map or the tile map has no tileWidth or tileHeight values.","warning")}return this},translate:function(){if(arguments.length){$i_56.prototype.log("You called translate with arguments, did you mean translateTo or translateBy instead of translate?","warning")}this.x=this._translateAccessorX;this.y=this._translateAccessorY;this.z=this._translateAccessorZ;return this._entity||this},_translateAccessorX:function(val){if(val!==undefined){this._translate.x=val;return this._entity||this}return this._translate.x},_translateAccessorY:function(val){if(val!==undefined){this._translate.y=val;return this._entity||this}return this._translate.y},_translateAccessorZ:function(val){if(val!==undefined){this._translate.z=val;return this._entity||this}return this._translate.z},rotateBy:function(x,y,z){if(!isNaN(x)&&!isNaN(y)&&!isNaN(z)&&x!==undefined&&y!==undefined&&z!==undefined){this._rotate.x+=x;this._rotate.y+=y;this._rotate.z+=z;this.transformTexture(0,0,z,"rotateBy")}else{$i_56.prototype.log("rotateBy() called with a missing or undefined x, y or z parameter!","error")}return this._entity||this},rotateTo:function(x,y,z){if(!isNaN(x)&&!isNaN(y)&&!isNaN(z)&&x!==undefined&&y!==undefined&&z!==undefined){this._rotate.x=x;this._rotate.y=y;this._rotate.z=z}else{$i_56.prototype.log("rotateTo() called with a missing or undefined x, y or z parameter!","error")}return this._entity||this},rotate:function(){if(arguments.length){$i_56.prototype.log("You called rotate with arguments, did you mean rotateTo or rotateBy instead of rotate?","warning")}this.x=this._rotateAccessorX;this.y=this._rotateAccessorY;this.z=this._rotateAccessorZ;return this._entity||this},_rotateAccessorX:function(val){if(val!==undefined){this._rotate.x=val;return this._entity||this}return this._rotate.x},_rotateAccessorY:function(val){if(val!==undefined){this._rotate.y=val;return this._entity||this}return this._rotate.y},_rotateAccessorZ:function(val){if(val!==undefined){this._rotate.z=val;return this._entity||this}return this._rotate.z},scaleBy:function(x,y,z){if(x!==undefined&&y!==undefined&&z!==undefined){this._scale.x+=x;this._scale.y+=y;this._scale.z+=z}else{$i_56.prototype.log("scaleBy() called with a missing or undefined x, y or z parameter!","error")}return this._entity||this},scaleTo:function(x,y,z){if(ige.isClient)ige.client.emit("scale",{entity:this,x:x,y:y});if(this._scale&&x!==undefined&&y!==undefined&&z!==undefined){this._scale.x=x;this._scale.y=y;this._scale.z=z}else{$i_56.prototype.log("scaleTo() called with a missing or undefined x, y or z parameter!","error")}return this._entity||this},scaleDimensions:function(width,height){if(this._stats.scaleDimensions){var originalWidth=this.width();var originalHeight=this.height();var scaleX=width/originalWidth;var scaleY=height/originalHeight;if(ige.isServer){this.scaleTo(scaleX,scaleY,0);this.updateBody(undefined,false,true)}else{this.height(height);this.width(width)}}},scale:function(){if(arguments.length){$i_56.prototype.log("You called scale with arguments, did you mean scaleTo or scaleBy instead of scale?","warning")}this.x=this._scaleAccessorX;this.y=this._scaleAccessorY;this.z=this._scaleAccessorZ;return this._entity||this},_scaleAccessorX:function(val){if(val!==undefined){this._scale.x=val;return this._entity||this}return this._scale.x},_scaleAccessorY:function(val){if(val!==undefined){this._scale.y=val;return this._entity||this}return this._scale.y},_scaleAccessorZ:function(val){if(val!==undefined){this._scale.z=val;return this._entity||this}return this._scale.z},originBy:function(x,y,z){if(x!==undefined&&y!==undefined&&z!==undefined){this._origin.x+=x;this._origin.y+=y;this._origin.z+=z}else{$i_56.prototype.log("originBy() called with a missing or undefined x, y or z parameter!","error")}return this._entity||this},originTo:function(x,y,z){if(x!==undefined&&y!==undefined&&z!==undefined){this._origin.x=x;this._origin.y=y;this._origin.z=z}else{$i_56.prototype.log("originTo() called with a missing or undefined x, y or z parameter!","error")}return this._entity||this},origin:function(){this.x=this._originAccessorX;this.y=this._originAccessorY;this.z=this._originAccessorZ;return this._entity||this},_originAccessorX:function(val){if(val!==undefined){this._origin.x=val;return this._entity||this}return this._origin.x},_originAccessorY:function(val){if(val!==undefined){this._origin.y=val;return this._entity||this}return this._origin.y},_originAccessorZ:function(val){if(val!==undefined){this._origin.z=val;return this._entity||this}return this._origin.z},_rotatePoint:function(point,radians,origin){var cosAngle=Math.cos(radians);var sinAngle=Math.sin(radians);return{x:origin.x+(point.x-origin.x)*cosAngle+(point.y-origin.y)*sinAngle,y:origin.y-(point.x-origin.x)*sinAngle+(point.y-origin.y)*cosAngle}},updateTransform:function(){ige.updateTransform++;this._localMatrix.identity();if(this._mode===0){this._localMatrix.multiply(this._localMatrix._newTranslate(this._translate.x,this._translate.y))}if(this._mode===1){if(!isNaN(this._translate.x)&&!isNaN(this._translate.y)){var isoPoint=this._translateIso=new $i_5(this._translate.x,this._translate.y,this._translate.z+this._bounds3d.z/2).toIso();if(this._parent&&this._parent._bounds3d.z){isoPoint.y+=this._parent._bounds3d.z/1.6}this._localMatrix.multiply(this._localMatrix._newTranslate(isoPoint.x,isoPoint.y))}else{console.log("localMatrix translate error: ",this._category,this._translate);if(ige.chat)ige.chat.postMessage({text:`localMatrix translate error: ${this._category}${this._stats}`?this._stats.name:""})}}ige.matrixEntityId=this.id();ige.matrixAngle=this._rotate.z;this._localMatrix.rotateBy(this._rotate.z);this._localMatrix.scaleBy(this._scale.x,this._scale.y);if(this._origin.x!==0.5||this._origin.y!==0.5){this._localMatrix.translateBy(this._bounds2d.x*(0.5-this._origin.x),this._bounds2d.y*(0.5-this._origin.y))}if(this._parent){this._worldMatrix.copy(this._parent._worldMatrix);this._worldMatrix.multiply(this._localMatrix)}else{this._worldMatrix.copy(this._localMatrix)}if(!this._worldMatrix.compare(this._oldWorldMatrix)){this._oldWorldMatrix.copy(this._worldMatrix);this._transformChanged=true;this._aabbDirty=true;this._bounds3dPolygonDirty=true}else{this._transformChanged=false}if(!this._oldBounds2d.compare(this._bounds2d)){this._aabbDirty=true;this._oldBounds2d.copy(this._bounds2d)}if(!this._oldBounds3d.compare(this._bounds3d)){this._bounds3dPolygonDirty=true;this._oldBounds3d.copy(this._bounds3d)}return this},disableInterpolation:function(val){if(val!==undefined){this._disableInterpolation=val;return this}return this._disableInterpolation},streamSections:function(sectionArray){if(sectionArray!==undefined){this._streamSections=sectionArray;return this}return this._streamSections},streamSectionsPush:function(sectionName){this._streamSections=this._streamSections||[];this._streamSections.push(sectionName);return this},getPersistentData:function(type){var self=this;var dataToBeSaved={};var variables={};var unit=null;var player=null;var isUnitExists=false;dataToBeSaved[type]={};if(type=="player"){player=self;unit=ige.$(player._stats.selectedUnitId);if(!player||!player._stats)return}else if(type=="unit"){unit=self;player=unit.getOwner();if(!unit||!unit._stats)return}isUnitExists=!!(unit&&unit._stats);var variablesToBeIgnored=["unit","item","player","playerGroup","itemGroup","unitGroup","projectile","region"];for(var variablesId in self.variables){var variable=self.variables[variablesId];if(!variablesToBeIgnored.includes(variable.dataType)){variables[variablesId]=JSON.parse(JSON.stringify(variable))}}if(isUnitExists){unit._stats.itemIds.forEach(function(itemId){if(itemId){var item=ige.$(itemId);if(item._stats.bonus&&item._stats.bonus.passive){if(item._stats.slotIndexitem.toString(16));this._streamSectionData=buffArr}}break;case"depth":if(data!==undefined){if(ige.isClient){this.depth(parseInt(data))}}else{return String(this.depth())}break;case"layer":if(data!==undefined){if(ige.isClient){this.layer(parseInt(data))}}else{return String(this.layer())}break;case"bounds2d":if(data!==undefined){if(ige.isClient){var geom=data.split(",");this.bounds2d(parseFloat(geom[0]),parseFloat(geom[1]))}}else{return String(`${this._bounds2d.x},${this._bounds2d.y}`)}break;case"bounds3d":if(data!==undefined){if(ige.isClient){var geom=data.split(",");this.bounds3d(parseFloat(geom[0]),parseFloat(geom[1]),parseFloat(geom[2]))}}else{return String(`${this._bounds3d.x},${this._bounds3d.y},${this._bounds3d.z}`)}break;case"hidden":if(data!==undefined){if(ige.isClient){if(data=="true"){this.hide()}else{this.show()}}}else{return String(this.isHidden())}break;case"mount":if(data!==undefined){if(ige.isClient){if(data){var newParent=ige.$(data);if(newParent){this.mount(newParent)}}else{this.unMount()}}}else{var parent=this.parent();if(parent){return this.parent().id()}else{return""}}break;case"origin":if(data!==undefined){if(ige.isClient){var geom=data.split(",");this.origin(parseFloat(geom[0]),parseFloat(geom[1]),parseFloat(geom[2]))}}else{return String(`${this._origin.x},${this._origin.y},${this._origin.z}`)}break;case"props":var newData,changed,i;if(data!==undefined){if(ige.isClient){var props=JSON.parse(data);for(i in props){changed=false;if(props.hasOwnProperty(i)){if(this._streamProperty[i]!=props[i]){changed=true}this._streamProperty[i]=props[i];this.emit("streamPropChange",[i,props[i]])}}}}else{newData={};for(i in this._streamProperty){if(this._streamProperty.hasOwnProperty(i)){newData[i]=this._streamProperty[i]}}return JSON.stringify(newData)}break;}},getQueuedStreamData:function(){return this._streamDataQueued},streamMode:function(val){if(val!==undefined){this._streamMode=val;return this}return this._streamMode},streamControl:function(method){if(method!==undefined){this._streamControl=method;return this}return this._streamControl},streamSyncInterval:function(val,sectionId){if(val!==undefined){if(!sectionId){if(val<16){delete this._streamSyncInterval}else{this._streamSyncDelta=0;this._streamSyncInterval=val}}else{this._streamSyncSectionInterval=this._streamSyncSectionInterval||{};this._streamSyncSectionDelta=this._streamSyncSectionDelta||{};if(val<16){delete this._streamSyncSectionInterval[sectionId]}else{this._streamSyncSectionDelta[sectionId]=0;this._streamSyncSectionInterval[sectionId]=val}}return this}return this._streamSyncInterval},streamFloatPrecision:function(val){if(val!==undefined){this._streamFloatPrecision=val;var i;var floatRemove="\\.";for(i=0;i-1){keys.splice(keys.indexOf("cellSheet"),1);keys=keys.concat(["rotation","type","density","friction","restitution","rotation","y","x"])}else if(this._category==="region"){keys=keys.concat("value")}const statKeys=Object.keys(this._stats);const data={};statKeys.forEach(key=>{if(!keys.includes(key)){data[key]=this._stats[key]}});return data}},streamEmitCreated:function(val){if(val!==undefined){this._streamEmitCreated=val;return this}return this._streamEmitCreated},streamSync:function(clientId){if(this._streamMode===1||this._streamMode===2){if(this._streamSyncInterval){this._streamSyncDelta+=ige._tickDelta;if(this._streamSyncDelta=this._streamSyncSectionInterval[sectionId]){this.streamSectionData(sectionId);this._streamSyncSectionDelta[sectionId]=0}}else{this.streamSectionData(sectionId)}}if(this._streamSectionData!==undefined){streamData=this.encodedStreamData();this._streamDataCache=streamData;return streamData}}}},encodedStreamData:function(){var data=this.id();return[data].concat(this._streamSectionData).join("&")},interpolateValue:function(startValue,endValue,startTime,currentTime,endTime){var totalValue=endValue-startValue;var dataDelta=endTime-startTime;var offsetDelta=currentTime-startTime;var deltaTime=offsetDelta/dataDelta;if(deltaTime<0){deltaTime=0}return totalValue*deltaTime+startValue},reconcileValue:function(startValue,endValue,startTime,currentTime,endTime){var totalValue=endValue-startValue;var dataDelta=endTime-startTime;var offsetDelta=currentTime-startTime;var t=Math.abs(offsetDelta/dataDelta);var deltaTime=t<0.5?2*t*t:-1+(4-2*t)*t;return totalValue*deltaTime+startValue},_processTransform:function(){if(this._lastTransformAt==ige._currentTime||this._translate==undefined||this._stats.currentBody==undefined||this._stats.currentBody&&this._stats.currentBody.type=="spriteOnly"&&(this.getOwnerUnit&&this.getOwnerUnit())==ige.client.selectedUnit){return}var x=this._translate.x;var y=this._translate.y;var rotate=this._rotate.z;var prevKeyFrame=null;var nextKeyFrame=null;if(ige.nextSnapshot){var nextTransform=ige.nextSnapshot[1][this.id()];if(nextTransform){nextKeyFrame=[ige.nextSnapshot[0],nextTransform]}}if(ige.prevSnapshot){var prevTransform=ige.prevSnapshot[1][this.id()];if(prevTransform){prevKeyFrame=[ige.prevSnapshot[0],prevTransform]}}if(ige.physics&&(ige.game.cspEnabled&&ige.client.selectedUnit==this||this._category=="projectile"&&this._stats.sourceItemId!=undefined&&!this._streamMode)){if(this.nextPhysicsFrame){if(this.prevPhysicsFrame){x=this.interpolateValue(this.prevPhysicsFrame[1][0],this.nextPhysicsFrame[1][0],this.prevPhysicsFrame[0],ige._currentTime,this.nextPhysicsFrame[0]);y=this.interpolateValue(this.prevPhysicsFrame[1][1],this.nextPhysicsFrame[1][1],this.prevPhysicsFrame[0],ige._currentTime,this.nextPhysicsFrame[0]);if(this==ige.client.selectedUnit){rotate=this.interpolateValue(this.prevPhysicsFrame[1][2],this.nextPhysicsFrame[1][2],this.prevPhysicsFrame[0],ige._currentTime,this.nextPhysicsFrame[0])}}else{x=this.nextPhysicsFrame[1][0];y=this.nextPhysicsFrame[1][1];rotate=this.nextPhysicsFrame[1][2]}}}if(prevTransform!=undefined&&nextTransform!=undefined&&prevKeyFrame[0]!=nextKeyFrame[0]&&prevKeyFrame[0]Math.PI){if(endValue>startValue)startValue+=Math.PI*2;else startValue-=Math.PI*2}if(this==ige.client.selectedUnit&&this.angleToTarget!=undefined&&!isNaN(this.angleToTarget)&&this._stats.controls&&this._stats.controls.mouseBehaviour.rotateToFaceMouseCursor&&this._stats.currentBody&&!this._stats.currentBody.fixedRotation){targetRotate=this.angleToTarget}else{targetRotate=this.interpolateValue(startValue,endValue,prevKeyFrame[0],ige.renderTime,nextKeyFrame[0])}if(this==ige.client.selectedUnit&&this.lastReconciledAt!=prevKeyFrame[0]){this.lastServerStreamedPosition=[targetX,targetY,targetRotate]}if(ige.physics&&ige.game.cspEnabled&&this!=ige.client.selectedUnit){xDiff=targetX-x;yDiff=targetY-y;x+=xDiff/2;y+=yDiff/2}else if(!ige.physics||!ige.game.cspEnabled||this!=ige.client.selectedUnit){x=targetX;y=targetY}rotate=targetRotate;if(this._debugEntity){this._debugEntity.position.set(targetX,targetY);this._debugEntity.rotation=targetRotate;this._debugEntity.pivot.set(this._debugEntity.width/2,this._debugEntity.height/2)}}if(this==ige.client.selectedUnit){var ownerPlayer=ige.$(this._stats.ownerId);if(ownerPlayer&&ownerPlayer.control&&ownerPlayer.control.input){var mouse=ownerPlayer.control.input.mouse;if(mouse){this.angleToTarget=Math.atan2(mouse.y-this._translate.y,mouse.x-this._translate.x)+Math.radians(90);if(this.angleToTarget!=undefined&&!isNaN(this.angleToTarget)&&this._stats.controls&&this._stats.controls.mouseBehaviour.rotateToFaceMouseCursor&&this._stats.currentBody&&!this._stats.currentBody.fixedRotation){rotate=this.angleToTarget}}}}if(this._stats.isStunned==undefined||this._stats.isStunned!=true){this.rotateTo(0,0,rotate)}this.translateTo(x,y,0);this._lastTransformAt=ige._currentTime},getAttributeBarContainer:function(){var self=this;var attributeContainerId=self._stats&&self._stats.attributeBarContainer&&self._stats.attributeBarContainer.id;if(attributeContainerId){return ige.$(attributeContainerId)}return null}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_56}var $i_57=$i_56.extend([{extension:$i_41,overwrite:true},{extension:$i_40,overwrite:true}],{classId:"$i_57",init:function(){$i_56.prototype.init.call(this);this._color="#000000";this._borderLeftWidth=0;this._borderTopWidth=0;this._borderRightWidth=0;this._borderBottomWidth=0;this._borderTopLeftRadius=0;this._borderTopRightRadius=0;this._borderBottomRightRadius=0;this._borderBottomLeftRadius=0;this._backgroundPosition={x:0,y:0};this._paddingLeft=0;this._paddingTop=0;this._paddingRight=0;this._paddingBottom=0},disabled:function(val){if(val!==undefined){this._disabled=val;return this}return this._disabled},overflow:function(val){if(val!==undefined){this._overflow=val;return this}return this._overflow},_renderBackground:function(ctx){var geom=this._bounds2d;var left;var top;var width;var height;if(this._backgroundColor||this._patternFill){left=-(geom.x/2)|0;top=-(geom.y/2)|0;width=geom.x;height=geom.y;ctx.save();ctx.beginPath();if(!this._borderTopRightRadius&&!this._borderBottomRightRadius&&!this._borderBottomLeftRadius&&!this._borderTopLeftRadius){ctx.rect(left,top,width,height)}else{ctx.moveTo(left+this._borderTopLeftRadius,top);ctx.lineTo(left+width-this._borderTopRightRadius,top);if(this._borderTopRightRadius>0){ctx.arcTo(left+width,top,left+width,top+this._borderTopRightRadius,this._borderTopRightRadius)}ctx.lineTo(left+width,top+height-this._borderBottomRightRadius);if(this._borderBottomRightRadius>0){ctx.arcTo(left+width,top+height,left+width-this._borderBottomRightRadius,top+height,this._borderBottomRightRadius)}ctx.lineTo(left+this._borderBottomLeftRadius,top+height);if(this._borderBottomLeftRadius>0){ctx.arcTo(left,top+height,left,top+height-this._borderBottomLeftRadius,this._borderBottomLeftRadius)}ctx.lineTo(left,top+this._borderTopLeftRadius);if(this._borderTopLeftRadius>0){ctx.arcTo(left,top,left+this._borderTopLeftRadius,top,this._borderTopLeftRadius)}ctx.clip()}if(this._backgroundColor){ctx.fillStyle=this._backgroundColor;ctx.fill()}if(this._patternFill){ctx.translate(-(width/2|0)+this._backgroundPosition.x,-(height/2|0)+this._backgroundPosition.y);ctx.fillStyle=this._patternFill;ctx.fill()}ctx.restore()}},_renderBorder:function(ctx){var rad;var geom=this._bounds2d;var left=(-geom.x2|0)+0.5;var top=(-geom.y2|0)+0.5;var width=geom.x-1;var height=geom.y-1;if(!this._borderTopRightRadius&&!this._borderBottomRightRadius&&!this._borderBottomLeftRadius&&!this._borderTopLeftRadius&&this._borderLeftWidth===this._borderWidth&&this._borderTopWidth===this._borderWidth&&this._borderRightWidth===this._borderWidth&&this._borderBottomWidth===this._borderWidth){ctx.strokeStyle=this._borderColor;ctx.lineWidth=this._borderWidth;ctx.strokeRect(left,top,width,height)}else{var startNewStroke=function(){ctx.stroke();ctx.beginPath()};rad=Math.PI/180;ctx.beginPath();if(this._borderTopWidth){ctx.strokeStyle=this._borderTopColor;ctx.lineWidth=this._borderTopWidth;if(this._borderTopLeftRadius>0){ctx.arc(left+this._borderTopLeftRadius,top+this._borderTopLeftRadius,this._borderTopLeftRadius,225*rad,270*rad)}ctx.moveTo(left+this._borderTopLeftRadius,top);ctx.lineTo(left+width-this._borderTopRightRadius,top);if(this._borderTopRightRadius>0){ctx.arc(left+width-this._borderTopRightRadius,top+this._borderTopRightRadius,this._borderTopRightRadius,-90*rad,-44*rad)}}if(!this._borderRightWidth||this._borderTopColor!=this._borderRightColor||this._borderTopWidth!=this._borderRightWidth)startNewStroke();if(this._borderRightWidth){ctx.strokeStyle=this._borderRightColor;ctx.lineWidth=this._borderRightWidth;if(this._borderTopRightRadius>0){ctx.arc(left+width-this._borderTopRightRadius,top+this._borderTopRightRadius,this._borderTopRightRadius,-45*rad,0)}ctx.moveTo(left+width,top+this._borderTopRightRadius);ctx.lineTo(left+width,top+height-this._borderBottomRightRadius);if(this._borderBottomRightRadius>0){ctx.arc(left+width-this._borderBottomRightRadius,top+height-this._borderBottomRightRadius,this._borderTopRightRadius,0,46*rad)}}if(!this._borderBottomWidth||this._borderRightColor!=this._borderBottomColor||this._borderRightWidth!=this._borderBottomWidth)startNewStroke();if(this._borderBottomWidth){ctx.strokeStyle=this._borderBottomColor;ctx.lineWidth=this._borderBottomWidth;if(this._borderBottomRightRadius>0){ctx.arc(left+width-this._borderBottomRightRadius,top+height-this._borderBottomRightRadius,this._borderBottomRightRadius,45*rad,90*rad)}ctx.moveTo(left+width-this._borderBottomRightRadius,top+height);ctx.lineTo(left+this._borderBottomLeftRadius,top+height);if(this._borderBottomLeftRadius>0){ctx.arc(left+this._borderBottomLeftRadius,top+height-this._borderBottomLeftRadius,this._borderBottomLeftRadius,90*rad,136*rad)}}if(!this._borderLeftWidth||this._borderBottomColor!=this._borderLeftColor||this._borderBottomWidth!=this._borderLeftWidth)startNewStroke();if(this._borderLeftWidth){ctx.strokeStyle=this._borderLeftColor;ctx.lineWidth=this._borderLeftWidth;if(this._borderBottomLeftRadius>0){ctx.arc(left+this._borderBottomLeftRadius,top+height-this._borderBottomLeftRadius,this._borderBottomLeftRadius,135*rad,180*rad)}ctx.moveTo(left,top+height-this._borderBottomLeftRadius);ctx.lineTo(left,top+this._borderTopLeftRadius);if(this._borderTopLeftRadius>0){ctx.arc(left+this._borderTopLeftRadius,top+this._borderTopLeftRadius,this._borderTopLeftRadius,180*rad,226*rad)}}ctx.stroke()}},cell:function(val){var ret=$i_56.prototype.cell.call(this,val);if(ret===this&&this._patternTexture){this.backgroundImage(this._patternTexture,this._patternRepeat)}return ret},mount:function(obj){var ret=$i_56.prototype.mount.call(this,obj);if(this._parent){if(this._updateUiPosition){this._updateUiPosition()}if(this._children.length){this.updateUiChildren()}if(this._updateStyle){this._updateStyle()}}return ret},tick:function(ctx,dontTransform){if(ige.isClient&&!ige.client.uiEntityRenderEnabled)return;if(!this._hidden&&this._inView&&(!this._parent||this._parent._inView)&&!this._streamJustCreated){if(!dontTransform){this._transformContext(ctx)}this._renderBackground(ctx);this._renderBorder(ctx);if(this._overflow==="hidden"){var geom=this._bounds2d;var left=-(geom.x/2)+this._paddingLeft|0;var top=-(geom.y/2)+this._paddingTop|0;var width=geom.x+this._paddingRight;var height=geom.y+this._paddingBottom;ctx.rect(left,top,width,height);ctx.clip()}ctx.translate(this._paddingLeft,this._paddingTop);$i_56.prototype.tick.call(this,ctx,true)}},_resizeEvent:function(event){if(this._updateUiPosition){this._updateUiPosition()}else{debugger}if(this._updateStyle){this._updateStyle()}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_57}var $i_59=$i_57.extend({classId:"$i_59",init:function(){$i_57.prototype.init.call(this);this._renderText=undefined;this._text=undefined;this._textAlignX=1;this._textAlignY=1;this._textLineSpacing=0;this._nativeMode=false;this.cache(true)},width:function(val,lockAspect,modifier,noUpdate){if(val!==undefined){if(this._bounds2d.x!==val){this.clearCache()}}var retVal=$i_57.prototype.width.call(this,val,lockAspect,modifier,noUpdate);if(this._autoWrap){this._applyAutoWrap()}return retVal},height:function(val,lockAspect,modifier,noUpdate){if(val!==undefined){if(this._bounds2d.y!==val){this.clearCache()}}return $i_57.prototype.height.call(this,val,lockAspect,modifier,noUpdate)},text:function(text){if(text!==undefined){var wasDifferent=false;text=String(text);if(this._text!==text){this.clearCache();wasDifferent=true}this._text=text;if(this._autoWrap&&wasDifferent){this._applyAutoWrap()}else{this._renderText=text}return this}return this._text},bindData:function(obj,propName,preText,postText){if(obj!==undefined&&propName!==undefined){this._bindDataObject=obj;this._bindDataProperty=propName;this._bindDataPreText=preText||"";this._bindDataPostText=postText||""}return this},textAlignX:function(val){if(val!==undefined){if(this._textAlignX!==val){this.clearCache()}this._textAlignX=val;return this}return this._textAlignX},textAlignY:function(val){if(val!==undefined){if(this._textAlignY!==val){this.clearCache()}this._textAlignY=val;return this}return this._textAlignY},textLineSpacing:function(val){if(val!==undefined){if(this._textLineSpacing!==val){this.clearCache()}this._textLineSpacing=val;return this}return this._textLineSpacing},colorOverlay:function(val){if(val!==undefined){if(this._colorOverlay!==val){this.clearCache()}this._colorOverlay=val;return this}return this._colorOverlay},color:function(val){return this.colorOverlay(val)},clearCache:function(){if(this._cache){this.cacheDirty(true)}if(this._texture&&this._texture._caching&&this._texture._cacheText[this._renderText]){delete this._texture._cacheText[this._renderText]}},nativeFont:function(val){if(val!==undefined){if(this._nativeFont!==val){this.clearCache()}this._nativeFont=val;var tex=new $i_50($i_54);this.texture(tex);this._nativeMode=true;return this}return this._nativeFont},nativeStroke:function(val){if(val!==undefined){if(this._nativeStroke!==val){this.clearCache()}this._nativeStroke=val;return this}return this._nativeStroke},nativeStrokeColor:function(val){if(val!==undefined){if(this._nativeStrokeColor!==val){this.clearCache()}this._nativeStrokeColor=val;return this}return this._nativeStrokeColor},autoWrap:function(val){if(val!==undefined){this._autoWrap=val;if(this._text){this._applyAutoWrap();this.clearCache()}return this}return this._autoWrap},_applyAutoWrap:function(){if(this._text){var oneLineText=this._text.replace(/\n/g," ");var words;var wordIndex;var textArray=[];var currentTextLine="";var lineWidth;words=oneLineText.split(" ");for(wordIndex=0;wordIndex=this._bounds2d.x){currentTextLine=words[wordIndex];textArray.push(`\n${words[wordIndex]}`)}else{textArray.push(words[wordIndex])}}this._renderText=textArray.join(" ")}},measureTextWidth:function(text){text=text||this._text;if(this._texture._mode===0){return this._texture.measureTextWidth(text)}else{return this._texture.script.measureTextWidth(text,this)}},tick:function(ctx){if(this._bindDataObject&&this._bindDataProperty){if(this._bindDataObject._alive===false){delete this._bindDataObject}else{this.text(this._bindDataPreText+this._bindDataObject[this._bindDataProperty]+this._bindDataPostText)}}$i_57.prototype.tick.call(this,ctx)},_stringify:function(){var str=$i_57.prototype._stringify.call(this);var i;for(i in this){if(this.hasOwnProperty(i)&&this[i]!==undefined){switch(i){case"_text":str+=`.text(${this.text()})`;break;case"_textAlignX":str+=`.textAlignX(${this.textAlignX()})`;break;case"_textAlignY":str+=`.textAlignY(${this.textAlignY()})`;break;case"_textLineSpacing":str+=`.textLineSpacing(${this.textLineSpacing()})`;break;}}}return str}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_59}var $i_60=$i_57.extend({classId:"$i_60",$i_60:true,init:function(){$i_57.prototype.init.call(this);this._currentDelta=0;this._started=false;this._particles=[];this.texture=new $i_50(`${assetsProvider}/assets/particles/Rectangle.js`);this.applyDepthToParticles(true);this.applyLayerToParticles(true);this.quantityTimespan(1000);this.quantityBase(10);this.quantityVariance(0,0);this.translateBaseX(0);this.translateBaseY(0);this.translateBaseZ(0);this.translateVarianceX(0,0);this.translateVarianceY(0,0);this.translateVarianceZ(0,0);this.rotateBase(0);this.rotateVariance(0,1);this.deathRotateBase(0);this.deathRotateVariance(0,0);this.scaleBaseX(1);this.scaleBaseY(1);this.scaleBaseZ(1);this.scaleVarianceX(0,0);this.scaleVarianceY(0,0);this.scaleVarianceZ(0,0);this.scaleLockAspect(false);this.deathScaleBaseX(0);this.deathScaleBaseY(0);this.deathScaleBaseZ(0);this.deathScaleVarianceX(0,0);this.deathScaleVarianceY(0,0);this.deathScaleVarianceZ(0,0);this.deathScaleLockAspect(false);this.opacityBase(1);this.opacityVariance(0,0);this.deathOpacityBase(1);this.deathOpacityVariance(0,0);this.lifeBase(1000);this.lifeVariance(0,0)},particle:function(obj){this._particle=obj;return this},size:function(width,height){this.size={width:width,height:height};return this},color:function(color){this.color=color;return this},particleMountTarget:function(obj){this._particleMountTarget=obj;return this},applyDepthToParticles:function(val){this._applyDepthToParticles=val;return this},applyLayerToParticles:function(val){this._applyLayerToParticles=val;return this},quantityTimespan:function(val){this._quantityTimespan=val;return this},quantityBase:function(val){this._quantityBase=val;return this},quantityVariance:function(a,b){this._quantityVariance=[a,b];return this},quantityMax:function(val){this._quantityMax=val;this._quantityProduced=0;return this},translateBaseX:function(val){this._translateBaseX=val;return this},translateBaseY:function(val){this._translateBaseY=val;return this},translateBaseZ:function(val){this._translateBaseZ=val;return this},translateVarianceX:function(a,b){this._translateVarianceX=[a,b];return this},translateVarianceY:function(a,b){this._translateVarianceY=[a,b];return this},translateVarianceZ:function(a,b){this._translateVarianceZ=[a,b];return this},rotateBase:function(val){this._rotateBase=val;return this},rotateVariance:function(a,b){this._rotateVariance=[a,b];return this},deathRotateBase:function(val){this._deathRotateBase=val;return this},deathRotateVariance:function(a,b){this._deathRotateVariance=[a,b];return this},scaleBaseX:function(val){this._scaleBaseX=val;return this},scaleBaseY:function(val){this._scaleBaseY=val;return this},scaleBaseZ:function(val){this._scaleBaseZ=val;return this},scaleVarianceX:function(a,b){this._scaleVarianceX=[a,b];return this},scaleVarianceY:function(a,b){this._scaleVarianceY=[a,b];return this},scaleVarianceZ:function(a,b){this._scaleVarianceZ=[a,b];return this},scaleLockAspect:function(val){this._scaleLockAspect=val;return this},deathScaleBaseX:function(val){this._deathScaleBaseX=val;return this},deathScaleBaseY:function(val){this._deathScaleBaseY=val;return this},deathScaleBaseZ:function(val){this._deathScaleBaseZ=val;return this},deathScaleVarianceX:function(a,b){this._deathScaleVarianceX=[a,b];return this},deathScaleVarianceY:function(a,b){this._deathScaleVarianceY=[a,b];return this},deathScaleVarianceZ:function(a,b){this._deathScaleVarianceZ=[a,b];return this},deathScaleLockAspect:function(val){this._deathScaleLockAspect=val;return this},opacityBase:function(val){this._opacityBase=val;return this},opacityVariance:function(a,b){this._opacityVariance=[a,b];return this},deathOpacityBase:function(val){this._deathOpacityBase=val;return this},deathOpacityVariance:function(a,b){this._deathOpacityVariance=[a,b];return this},lifeBase:function(val){this._lifeBase=val;return this},lifeVariance:function(a,b){this._lifeVariance=[a,b];return this},velocityVector:function(baseVector,minVector,maxVector){this._velocityVector={base:baseVector,min:minVector,max:maxVector};return this},linearForceVector:function(baseVector,minVector,maxVector){this._linearForceVector={base:baseVector,min:minVector,max:maxVector};return this},start:function(){if(this._particle){this.updateTransform();this._quantityTimespan=this._quantityTimespan!==undefined?this._quantityTimespan:1000;this._maxParticles=this.baseAndVarianceValue(this._quantityBase,this._quantityVariance,true);this._particlesPerTimeVector=this._quantityTimespan/this._maxParticles;this._currentDelta=0;this._quantityProduced=0;this._started=true}else{this.log("Cannot start particle emitter because no particle class was specified with a call to particle()","error")}return this},updateSettings:function(){this._maxParticles=this.baseAndVarianceValue(this._quantityBase,this._quantityVariance,true);this._particlesPerTimeVector=this._quantityTimespan/this._maxParticles},stop:function(){this._started=false;return this},stopAndKill:function(){this._started=false;var arr=this._particles;var arrCount=arr.length;while(arrCount--){arr[arrCount].destroy()}this._particles=[];return this},emitOnce:function(){this.start();this._emitOnce=true},baseAndVarianceValue:function(base,variance,floorIt){base=base||0;variance=variance||[0,0];var variant=0;if(floorIt){variant=Math.floor(variance[0]+Math.random()*(variance[1]-variance[0]))}else{variant=variance[0]+Math.random()*(variance[1]-variance[0])}return base+variant},vectorFromBaseMinMax:function(vectorData){if(vectorData.min&&vectorData.max){var base=vectorData.base;var min=vectorData.min;var max=vectorData.max;var newVector={};newVector.x=base.x+(min.x+Math.random()*(max.x-min.x));newVector.y=base.y+(min.y+Math.random()*(max.y-min.y));newVector.z=base.z+(min.z+Math.random()*(max.z-min.z));return newVector}else{return vectorData.base}},tick:function(ctx){this._currentDelta+=ige._tickDelta;if(this._parent&&this._started){if(!this._quantityMax||this._quantityProducedthis._quantityTimespan){this._currentDelta=this._quantityTimespan}if(this._currentDelta>=this._particlesPerTimeVector){particleCount=this._currentDelta/this._particlesPerTimeVector|0;this._currentDelta-=this._particlesPerTimeVector*particleCount;if(particleCount){while(particleCount--){if(this._quantityMax){this._quantityProduced++;if(this._quantityProduced>=this._quantityMax){this.stop();break}}translateX=this.baseAndVarianceValue(this._translateBaseX,this._translateVarianceX,true);translateY=this.baseAndVarianceValue(this._translateBaseY,this._translateVarianceY,true);translateZ=this.baseAndVarianceValue(this._translateBaseZ,this._translateVarianceZ,true);if(this._velocityVector){velocityVector=this.vectorFromBaseMinMax(this._velocityVector);rotX=velocityVector.x;rotY=velocityVector.y;cosRot=this._worldMatrix.matrix[0];sinRot=this._worldMatrix.matrix[3];newVecX=rotX*cosRot-rotY*sinRot;newVecY=rotY*cosRot+rotX*sinRot;velocityVector.x=newVecX;velocityVector.y=newVecY}scaleX=this.baseAndVarianceValue(this._scaleBaseX,this._scaleVarianceX,false);scaleZ=scaleY=scaleX;if(!this._scaleLockAspect){scaleY=this.baseAndVarianceValue(this._scaleBaseY,this._scaleVarianceY,false);scaleZ=this.baseAndVarianceValue(this._scaleBaseZ,this._scaleVarianceZ,false)}rotate=this.baseAndVarianceValue(this._rotateBase,this._rotateVariance,true);opacity=this.baseAndVarianceValue(this._opacityBase,this._opacityVariance,false);life=this.baseAndVarianceValue(this._lifeBase,this._lifeVariance,true);if(this._linearForceVector){linearForceVector=this.vectorFromBaseMinMax(this._linearForceVector);rotX=linearForceVector.x;rotY=linearForceVector.y;cosRot=this._worldMatrix.matrix[0];sinRot=this._worldMatrix.matrix[3];newVecX=rotX*cosRot-rotY*sinRot;newVecY=rotY*cosRot+rotX*sinRot;linearForceVector.x=newVecX;linearForceVector.y=newVecY}if(typeof this._deathScaleBaseX!=="undefined"){deathScaleX=this.baseAndVarianceValue(this._deathScaleBaseX,this._deathScaleVarianceX,false)}if(typeof this._deathScaleBaseY!=="undefined"&&!this._deathScaleLockAspect){deathScaleY=this.baseAndVarianceValue(this._deathScaleBaseY,this._deathScaleVarianceY,false)}if(typeof this._deathScaleBaseZ!=="undefined"&&!this._deathScaleLockAspect){deathScaleZ=this.baseAndVarianceValue(this._deathScaleBaseZ,this._deathScaleVarianceZ,false)}if(this._deathScaleLockAspect){deathScaleZ=deathScaleY=deathScaleX}if(typeof this._deathRotateBase!=="undefined"){deathRotate=this.baseAndVarianceValue(this._deathRotateBase,this._deathRotateVariance,true)}if(typeof this._deathOpacityBase!=="undefined"){deathOpacity=this.baseAndVarianceValue(this._deathOpacityBase,this._deathOpacityVariance,false)}tempParticle=new this._particle(this,this.color);if(this._ignoreCamera){translateX+=this._translate.x;translateY+=this._translate.y}else{translateX+=this._worldMatrix.matrix[2];translateY+=this._worldMatrix.matrix[5]}translateZ+=this._translate.z;scaleX*=this._scale.x;scaleY*=this._scale.y;scaleZ*=this._scale.z;deathScaleX*=this._scale.x;deathScaleY*=this._scale.y;deathScaleZ*=this._scale.z;tempParticle.translateTo(translateX,translateY,translateZ);tempParticle.rotateTo(0,0,Math.radians(rotate));tempParticle.scaleTo(scaleX,scaleY,scaleZ);tempParticle.opacity(opacity);if(this._applyDepthToParticles){tempParticle.depth(this._depth)}if(this._applyLayerToParticles){tempParticle.layer(this._layer)}if(typeof velocityVector==="object"){tempParticle.velocity.vector3(velocityVector,false)}if(typeof linearForceVector==="object"){tempParticle.velocity.linearForceVector3(linearForceVector,false)}tweens=[];if(typeof deathRotate!=="undefined"){tweens.push(new $i_49().targetObj(tempParticle._rotate).properties({z:Math.radians(deathRotate)}).duration(life))}if(typeof deathOpacity!=="undefined"){tweens.push(new $i_49().targetObj(tempParticle).properties({_opacity:deathOpacity}).duration(life))}scaleProps={};if(typeof deathScaleX!=="undefined"){scaleProps.x=deathScaleX}if(typeof deathScaleY!=="undefined"){scaleProps.y=deathScaleY}if(typeof deathScaleZ!=="undefined"){scaleProps.z=deathScaleZ}if(scaleProps.x||scaleProps.y||scaleProps.z){tweens.push(new $i_49().targetObj(tempParticle._scale).properties(scaleProps).duration(life))}if(typeof life==="number"){tempParticle.lifeSpan(life)}this._particles.push(tempParticle);tempParticle.mount(this._particleMountTarget||this._parent);for(i=0;i=0&&y>=0&&x+width<=this._gridSize.x&&y+height<=this._gridSize.y},hoverColor:function(val){if(val!==undefined){this._hoverColor=val;return this}return this._hoverColor},loadMap:function(map){this.map.mapData(map.data,0,0);return this},saveMap:function(layer){var textures=[];var i;var x;var y;var dataX=0;var dataY=0;var mapData=layer.map._mapData;for(y in mapData){if(mapData.hasOwnProperty(y)){for(x in mapData[y]){if(mapData[y].hasOwnProperty(x)){if(parseInt(x)=0&&mouseTile.y>=0&&mouseTile.x0){if(this._cacheDirty){if(this.allTexturesLoaded()){this._sections=[];this._sectionCtx=[];for(y in mapData){if(mapData.hasOwnProperty(y)){for(x in mapData[y]){if(mapData[y].hasOwnProperty(x)){xInt=parseInt(x);yInt=parseInt(y);if(this._mountMode===0){finalX=xInt;finalY=yInt}if(this._mountMode===1){tx=xInt*this._tileWidth;ty=yInt*this._tileHeight;finalX=(tx-ty)/this._tileWidth;finalY=(tx+ty)*0.5/this._tileHeight}tileData=mapData[y][x];sectionX=Math.floor(finalX/this._autoSection);sectionY=Math.floor(finalY/this._autoSection);this._ensureSectionExists(sectionX,sectionY);_ctx=this._sectionCtx[sectionX][sectionY];if(tileData){regions=this._renderTile(_ctx,xInt,yInt,tileData,tileEntity,null,sectionX,sectionY);if(regions){for(i=0;i=-(viewArea.width/2)&§ionAbsX-this._tileWidth/2<=viewArea.width/2&§ionAbsY+sectionHeight+this._tileHeight/2>=-(viewArea.height/2)&§ionAbsY<=viewArea.height/2){tileData=this._sections[x][y];ctx.drawImage(tileData,0,0,sectionWidth,sectionHeight,sectionRenderX,sectionRenderY,sectionWidth,sectionHeight);ige._drawCount++;if(this._drawSectionBounds){ctx.strokeStyle="#ff00f6";ctx.strokeRect(x*(this._tileWidth*this._autoSection),y*(this._tileHeight*this._autoSection),this._tileWidth*this._autoSection,this._tileHeight*this._autoSection)}}}}}}},_renderTile:function(ctx,x,y,tileData,tileEntity,rect,sectionX,sectionY){var finalX;var finalY;var regions;var xm1;var xp1;var ym1;var yp1;var regObj;var xAdjust=this._mountMode===1?this._tileWidth/2:0;var yAdjust=this._mountMode===1?this._tileHeight/2:0;var tx;var ty;var sx;var sy;var texture;if(this._mountMode===0){finalX=x*this._tileWidth;finalY=y*this._tileHeight}if(this._mountMode===1){tx=x*this._tileWidth;ty=y*this._tileHeight;sx=tx-ty;sy=(tx+ty)*0.5;finalX=sx-this._tileWidth/2;finalY=sy}if(sectionX!==undefined){finalX-=sectionX*this._autoSection*this._tileWidth}if(sectionY!==undefined){finalY-=sectionY*this._autoSection*this._tileHeight}if(rect){if(!rect.xyInside(finalX,finalY)){return}}if(finalX-xAdjust<0){regions=regions||[];regions.push({x:-1});xm1=true;regObj=regObj||{};regObj.x=-1}if(finalX+xAdjust>ctx.canvas.width-this._tileWidth){regions=regions||[];regions.push({x:1});xp1=true;regObj=regObj||{};regObj.x=1}if(finalY-0<0){regions=regions||[];regions.push({y:-1});ym1=true;regObj=regObj||{};regObj.y=-1}if(finalY+0>ctx.canvas.height-this._tileHeight){regions=regions||[];regions.push({y:1});yp1=true;regObj=regObj||{};regObj.y=1}if(xm1||ym1||xp1||yp1){regions.push(regObj)}ctx.save();ctx.translate(finalX,finalY);texture=this._textureList[tileData[0]];tileEntity._cell=tileData[1];if(texture){texture.render(ctx,tileEntity,ige._tickDelta)}ctx.restore();return regions},_newTileEntity:function(){if(this._mountMode===0){return{_cell:1,_bounds2d:{x:this._tileWidth,y:this._tileHeight},_renderPos:{x:-this._tileWidth/2,y:-this._tileHeight/2}}}if(this._mountMode===1){return{_cell:1,_bounds2d:{x:this._tileWidth*2,y:this._tileHeight},_renderPos:{x:-this._tileWidth,y:-this._tileHeight/2}}}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_50Map}var $i_63SmartTexture={render:function(ctx,entity){var tileWidth=entity._tileWidth;var tileHeight=entity._tileHeight;var bounds2d=entity.bounds2d();var gridSize=entity._gridSize;var x=0;var y=0;if(entity._drawGrid){ctx.strokeStyle=entity._gridColor;var gridMaxX=x+tileWidth*gridSize.x;var gridMaxY=y+tileHeight*gridSize.y;var index;var gStart;var gEnd;x=0;y=0;for(index=0;index<=gridSize.y;index++){gStart=new $i_4(x,y+tileHeight*index);gEnd=new $i_4(gridMaxX,y+tileHeight*index);if(entity._mountMode===1){gStart=gStart.toIso();gEnd=gEnd.toIso()}ctx.beginPath();ctx.moveTo(gStart.x,gStart.y);ctx.lineTo(gEnd.x,gEnd.y);ctx.stroke()}for(index=0;index<=gridSize.x;index++){gStart=new $i_4(x+tileWidth*index,y);gEnd=new $i_4(x+tileWidth*index,gridMaxY);if(entity._mountMode===1){gStart=gStart.toIso();gEnd=gEnd.toIso()}ctx.beginPath();ctx.moveTo(gStart.x,gStart.y);ctx.lineTo(gEnd.x,gEnd.y);ctx.stroke()}}if(entity._highlightOccupied){ctx.fillStyle="#ff0000";for(y in entity.map._mapData){if(entity.map._mapData[y]){for(x in entity.map._mapData[y]){if(entity.map._mapData[y][x]){tilePoint=new $i_4(tileWidth*x,tileHeight*y);if(entity._mountMode===0){ctx.fillRect(tilePoint.x,tilePoint.y,tileWidth,tileHeight)}if(entity._mountMode===1){tilePoint.thisToIso();ctx.beginPath();ctx.moveTo(tilePoint.x,tilePoint.y);ctx.lineTo(tilePoint.x+tileWidth,tilePoint.y+tileHeight/2);ctx.lineTo(tilePoint.x,tilePoint.y+tileHeight);ctx.lineTo(tilePoint.x-tileWidth,tilePoint.y+tileHeight/2);ctx.lineTo(tilePoint.x,tilePoint.y);ctx.fill()}}}}}}if(entity._highlightTileRect){ctx.fillStyle="#e4ff00";for(y=entity._highlightTileRect.y;y=0&&mouseTile.y>=0&&mouseTile.x=1?smoothing:0}this._trackTranslateTarget=entity;return this._entity}return this._trackTranslateTarget},trackTranslateSmoothing:function(val){if(val!==undefined){this._trackTranslateSmoothing=val;return this}return this._trackTranslateSmoothing},trackTranslateRounding:function(val){if(val!==undefined){this._trackTranslateRounding=val;return this}return this._trackTranslateRounding},unTrackTranslate:function(){delete this._trackTranslateTarget},trackRotate:function(entity,smoothing){if(entity!==undefined){this.log(`Camera on viewport ${this._entity.id()} is now tracking rotation of target ${entity.id()}`);this._trackRotateSmoothing=smoothing>=1?smoothing:0;this._trackRotateTarget=entity;return this._entity}return this._trackRotateTarget},trackRotateSmoothing:function(val){if(val!==undefined){this._trackRotateSmoothing=val;return this}return this._trackRotateSmoothing},unTrackRotate:function(){delete this._trackRotateTarget},lookAt:function(entity,durationMs,easing){if(entity!==undefined){entity.updateTransform();if(!durationMs){this._translate.x=Math.floor(entity._worldMatrix.matrix[2]);this._translate.y=Math.floor(entity._worldMatrix.matrix[5])}else{this._translate.tween().properties({x:Math.floor(entity._worldMatrix.matrix[2]),y:Math.floor(entity._worldMatrix.matrix[5]),z:0}).duration(durationMs).easing(easing).start()}this.updateTransform()}return this},update:function(ctx){this._processUpdateBehaviours(ctx);if(this._trackTranslateTarget){var targetEntity=this._trackTranslateTarget;var targetMatrix=targetEntity._worldMatrix.matrix;var targetX=targetMatrix[2];var targetY=targetMatrix[5];var sourceX;var sourceY;var distX;var distY;var destinationX;var destinationY;if(!this._trackTranslateSmoothing){this.lookAt(this._trackTranslateTarget)}else{sourceX=this._translate.x;sourceY=this._translate.y;distX=Math.round(targetX-sourceX);distY=Math.round(targetY-sourceY);if(this._trackTranslateRounding){destinationX=this._translate.x+Math.round(distX/this._trackTranslateSmoothing);destinationY=this._translate.y+Math.round(distY/this._trackTranslateSmoothing)}else{destinationX=this._translate.x+distX/this._trackTranslateSmoothing;destinationY=this._translate.y+distY/this._trackTranslateSmoothing}if(this._limit){if(destinationXthis._limit.x+this._limit.width){destinationX=this._limit.x+this._limit.width}if(destinationYthis._limit.y+this._limit.height){destinationY=this._limit.y+this._limit.height}}this._translate.x=destinationX;this._translate.y=destinationY}}if(this._trackRotateTarget){var targetParentRZ=this._trackRotateTarget._parent!==undefined?this._trackRotateTarget._parent._rotate.z:0;var targetZ=-(targetParentRZ+this._trackRotateTarget._rotate.z);var sourceZ;var distZ;if(!this._trackRotateSmoothing){this._rotate.z=targetZ}else{sourceZ=this._rotate.z;distZ=targetZ-sourceZ;this._rotate.z+=distZ/this._trackRotateSmoothing}}this.updateTransform()},tick:function(ctx){if(ige.isClient&&!ige.client.cameraEnabled)return;this._processTickBehaviours(ctx);this._localMatrix.transformRenderingContext(ctx)},updateTransform:function(){if(ige.isServer)return;this._localMatrix.identity();this._localMatrix.multiply(this._localMatrix._newRotate(this._rotate.z));this._localMatrix.multiply(this._localMatrix._newScale(this._scale.x,this._scale.y));this._localMatrix.multiply(this._localMatrix._newTranslate(-this._translate.x,-this._translate.y));if(this._parent){this._worldMatrix.copy(this._parent._worldMatrix);this._worldMatrix.multiply(this._localMatrix)}else{this._worldMatrix.copy(this._localMatrix)}},_stringify:function(){var str=$i_56.prototype._stringify.call(this);var i;for(i in this){if(this.hasOwnProperty(i)&&this[i]!==undefined){switch(i){case"_trackTranslateTarget":str+=`.trackTranslate(ige.$('${this._trackTranslateTarget.id()}'), ${this.trackTranslateSmoothing()})`;break;case"_trackRotateTarget":str+=`.trackRotate(ige.$('${this._trackRotateTarget.id()}'), ${this.trackRotateSmoothing()})`;break;}}}return str}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_67}var $i_68=$i_56.extend([{extension:$i_41,overwrite:true},{extension:$i_40,overwrite:true}],{classId:"$i_68",$i_68:true,init:function(options){var width,height;this._alwaysInView=true;$i_56.prototype.init.call(this);this._mouseAlwaysInside=true;this._mousePos=new $i_5(0,0,0);this._overflow="";this._clipping=true;this._bornTime=undefined;if(options){width=options.width;height=options.height;if(options&&options.scaleToWidth&&options.scaleToHeight){this._lockDimension=new $i_5(options.scaleToWidth,options.scaleToHeight,0)}}this._bounds2d=new $i_5(width||ige._bounds2d.x,height||ige._bounds2d.y,0);this.camera=new $i_67(this);this.camera._entity=this},minimumVisibleArea:function(width,height){this._lockDimension=new $i_5(width,height,0);if(ige.isClient){this._resizeEvent({})}return this},autoSize:function(val){if(typeof val!=="undefined"){this._autoSize=val;return this}return this._autoSize},scene:function(scene){if(typeof scene!=="undefined"){this._scene=scene;return this}return this._scene},mousePos:function(){return this._mousePos.clone()},mousePosWorld:function(){return this._transformPoint(this._mousePos.clone())},viewArea:function(){var aabb=this.aabb();var camTrans=this.camera._translate;var camScale=this.camera._scale;var width=aabb.width*(1/camScale.x);var height=aabb.height*(1/camScale.y);return new $i_7(camTrans.x-width/2,camTrans.y-height/2,width,height)},update:function(ctx,tickDelta){if(this._scene){ige._currentCamera=this.camera;ige._currentViewport=this;this._scene._parent=this;this.camera.update(ctx,tickDelta);$i_56.prototype.update.call(this,ctx,tickDelta);if(this._scene.newFrame()){this._scene.update(ctx,tickDelta)}}},tick:function(ctx,scene){if(this._id=="vpMiniMap"&&ige.isClient&&!ige.client.miniMapEnabled)return;if(this._scene){ige._currentCamera=this.camera;ige._currentViewport=this;this._scene._parent=this;$i_56.prototype.tick.call(this,ctx);ctx.translate(-(this._bounds2d.x*this._origin.x)|0,-(this._bounds2d.y*this._origin.y)|0);if(ige.isClient&&ige.client.clearEveryFrame){ctx.clearRect(0,0,this._bounds2d.x,this._bounds2d.y)}if(ige.isClient&&ige.client.viewportClippingEnabled){if(this._clipping||this._borderColor){ctx.beginPath();ctx.rect(0,0,this._bounds2d.x/ige._scale.x,this._bounds2d.y/ige._scale.x);if(this._borderColor){ctx.strokeStyle=this._borderColor;ctx.stroke()}if(this._clipping){ctx.clip()}}}ctx.translate((this._bounds2d.x/2|0)+ige._translate.x,(this._bounds2d.y/2|0)+ige._translate.y);if(ige._scale.x!==1||ige._scale.y!==1){ctx.scale(ige._scale.x,ige._scale.y)}this.camera.tick(ctx);ctx.save();this._scene.tick(ctx);ctx.restore();if(this._drawGuides&&ctx===ige._ctx){ctx.save();ctx.translate(-this._translate.x,-this._translate.y);this.paintGuides(ctx);ctx.restore()}if(this._drawBounds&&ctx===ige._ctx){ctx.save();ctx.translate(-this._translate.x,-this._translate.y);this.paintAabbs(ctx,this._scene,0);ctx.restore()}if(this._drawMouse&&ctx===ige._ctx){ctx.save();var mp=this.mousePos();var text;var mx;var my;var textMeasurement;ctx.scale(1/this.camera._scale.x,1/this.camera._scale.y);mx=Math.floor(mp.x*this.camera._scale.x);my=Math.floor(mp.y*this.camera._scale.y);ctx.fillStyle="#fc00ff";ctx.fillRect(mx-5,my-5,10,10);text=`${this.id()} X: ${mx}, Y: ${my}`;textMeasurement=ctx.measureText(text);ctx.fillStyle="rgba(0, 0, 0, 0.8)";ctx.fillRect(Math.floor(mx-textMeasurement.width/2-5),Math.floor(my-25),Math.floor(textMeasurement.width+10),14);ctx.fillStyle="#ffffff";ctx.fillText(text,mx-textMeasurement.width/2,my-15);ctx.restore()}if(this._drawViewArea){ctx.save();var va=this.viewArea();ctx.rect(va.x,va.y,va.width,va.height);ctx.stroke();ctx.restore()}}},screenPosition:function(){return new $i_5(Math.floor(this._worldMatrix.matrix[2]+ige._bounds2d.x2),Math.floor(this._worldMatrix.matrix[5]+ige._bounds2d.y2),0)},drawViewArea:function(val){if(val!==undefined){this._drawViewArea=val;return this}return this._drawViewArea},drawBoundsLimitId:function(id){if(id!==undefined){this._drawBoundsLimitId=id;return this}return this._drawBoundsLimitId},drawBoundsLimitCategory:function(category){if(category!==undefined){this._drawBoundsLimitCategory=category;return this}return this._drawBoundsLimitCategory},drawCompositeBounds:function(val){if(val!==undefined){this._drawCompositeBounds=val;return this}return this._drawCompositeBounds},drawGuides:function(val){if(val!==undefined){this._drawGuides=val;return this}return this._drawGuides},paintGuides:function(ctx){var geom=ige._bounds2d;if(this._drawGuides){ctx.strokeStyle="#ffffff";ctx.translate(0.5,0.5);ctx.beginPath();ctx.moveTo(0,-geom.y2);ctx.lineTo(0,geom.y);ctx.stroke();ctx.beginPath();ctx.moveTo(-geom.x2,0);ctx.lineTo(geom.x,0);ctx.stroke()}},paintAabbs:function(ctx,rootObject,index){var arr=rootObject._children;var arrCount;var obj;var aabb;var aabbC;var bounds3dPoly;var ga;var r3d;var xl1;var xl2;var xl3;var xl4;var xl5;var xl6;var bf1;var bf2;var bf3;var bf4;var tf1;var tf2;var tf3;var tf4;if(arr){arrCount=arr.length;while(arrCount--){obj=arr[arrCount];index++;if(obj._shouldRender!==false){if(obj._classId!=="$i_69"&&!this._drawBoundsLimitId&&!this._drawBoundsLimitCategory||this._drawBoundsLimitId&&(this._drawBoundsLimitId instanceof Array?this._drawBoundsLimitId.indexOf(obj.id())>-1:this._drawBoundsLimitId===obj.id())||this._drawBoundsLimitCategory&&this._drawBoundsLimitCategory===obj.category()){if(typeof obj.aabb==="function"){aabb=obj.aabb();if(this._drawCompositeBounds&&obj._compositeCache){aabbC=obj.compositeAabb();ctx.strokeStyle="#ff0000";ctx.strokeRect(aabbC.x,aabbC.y,aabbC.width,aabbC.height)}if(aabb){if(obj._drawBounds||obj._drawBounds===undefined){ctx.strokeStyle="#00deff";ctx.strokeRect(aabb.x,aabb.y,aabb.width,aabb.height);if(obj._parent&&obj._parent._mountMode===1){bounds3dPoly=obj.bounds3dPolygon().aabb();ctx.save();ctx.strokeStyle="#0068b8";ctx.strokeRect(bounds3dPoly.x,bounds3dPoly.y,bounds3dPoly.width,bounds3dPoly.height);ctx.restore();ctx.save();ctx.translate(bounds3dPoly.x+bounds3dPoly.width/2,bounds3dPoly.y+bounds3dPoly.height/2);r3d=obj._bounds3d;xl1=new $i_5(-(r3d.x/2),0,0).toIso();xl2=new $i_5(+(r3d.x/2),0,0).toIso();xl3=new $i_5(0,-(r3d.y/2),0).toIso();xl4=new $i_5(0,+(r3d.y/2),0).toIso();xl5=new $i_5(0,0,-(r3d.z/2)).toIso();xl6=new $i_5(0,0,+(r3d.z/2)).toIso();bf1=new $i_5(-(r3d.x/2),-(r3d.y/2),-(r3d.z/2)).toIso();bf2=new $i_5(+(r3d.x/2),-(r3d.y/2),-(r3d.z/2)).toIso();bf3=new $i_5(+(r3d.x/2),+(r3d.y/2),-(r3d.z/2)).toIso();bf4=new $i_5(-(r3d.x/2),+(r3d.y/2),-(r3d.z/2)).toIso();tf1=new $i_5(-(r3d.x/2),-(r3d.y/2),r3d.z/2).toIso();tf2=new $i_5(+(r3d.x/2),-(r3d.y/2),r3d.z/2).toIso();tf3=new $i_5(+(r3d.x/2),+(r3d.y/2),r3d.z/2).toIso();tf4=new $i_5(-(r3d.x/2),+(r3d.y/2),r3d.z/2).toIso();ga=ctx.globalAlpha;ctx.globalAlpha=1;ctx.strokeStyle="#ff0000";ctx.beginPath();ctx.moveTo(xl1.x,xl1.y);ctx.lineTo(xl2.x,xl2.y);ctx.stroke();ctx.strokeStyle="#00ff00";ctx.beginPath();ctx.moveTo(xl3.x,xl3.y);ctx.lineTo(xl4.x,xl4.y);ctx.stroke();ctx.strokeStyle="#fffc00";ctx.beginPath();ctx.moveTo(xl5.x,xl5.y);ctx.lineTo(xl6.x,xl6.y);ctx.stroke();ctx.strokeStyle="#a200ff";if(obj._highlight){ctx.globalAlpha=0.9}else{ctx.globalAlpha=0.6}ctx.fillStyle="#545454";ctx.beginPath();ctx.moveTo(bf3.x,bf3.y);ctx.lineTo(bf4.x,bf4.y);ctx.lineTo(tf4.x,tf4.y);ctx.lineTo(tf3.x,tf3.y);ctx.lineTo(bf3.x,bf3.y);ctx.fill();ctx.stroke();ctx.fillStyle="#282828";ctx.beginPath();ctx.moveTo(bf3.x,bf3.y);ctx.lineTo(bf2.x,bf2.y);ctx.lineTo(tf2.x,tf2.y);ctx.lineTo(tf3.x,tf3.y);ctx.lineTo(bf3.x,bf3.y);ctx.fill();ctx.stroke();ctx.fillStyle="#676767";ctx.beginPath();ctx.moveTo(tf1.x,tf1.y);ctx.lineTo(tf2.x,tf2.y);ctx.lineTo(tf3.x,tf3.y);ctx.lineTo(tf4.x,tf4.y);ctx.lineTo(tf1.x,tf1.y);ctx.fill();ctx.stroke();ctx.globalAlpha=ga;ctx.restore()}}if(this._drawBoundsData&&(obj._drawBounds||obj._drawBoundsData===undefined)){ctx.globalAlpha=1;ctx.fillStyle="#f6ff00";ctx.fillText(`ID: ${obj.id()} `+`(${obj.classId()}) ${obj.layer()}:${obj.depth().toFixed(0)}`,aabb.x+aabb.width+3,aabb.y+10);ctx.fillText(`X: ${obj._translate.x.toFixed(2)}, `+`Y: ${obj._translate.y.toFixed(2)}, `+`Z: ${obj._translate.z.toFixed(2)}`,aabb.x+aabb.width+3,aabb.y+20);ctx.fillText(`Num Children: ${obj._children.length}`,aabb.x+aabb.width+3,aabb.y+40)}}}}this.paintAabbs(ctx,obj,index)}}}},_resizeEvent:function(event){if(this._autoSize&&this._parent){this._bounds2d=this._parent._bounds2d.clone()}this._updateUiPosition();if(this._scene){this._scene._resizeEvent(event)}if(this._lockDimension){var ratio=1;var tmpX;var tmpY;if(this._bounds2d.x>this._lockDimension.x&&this._bounds2d.y>this._lockDimension.y){tmpX=this._bounds2d.x/this._lockDimension.x;tmpY=this._bounds2d.y/this._lockDimension.y;ratio=tmpXthis._lockDimension.x&&this._bounds2d.ythis._lockDimension.y){ratio=this._bounds2d.x/this._lockDimension.x}if(this._bounds2d.xmaxLifeSpan){lifeSpan=maxLifeSpan}return lifeSpan},getIdleTimeoutMs:function(){var defaultValue=10;var idleTimeoutHours=ige.server.tier=="0"?ige.game.data.defaultData.privateServerIdleTimeout:0;var timeoutMins=idleTimeoutHours?idleTimeoutHours*60:defaultValue;return timeoutMins*60*1000},$:function(item){if(typeof item==="number"&&!isNaN(item)){item=item.toString()}if(typeof item==="string"){return this._register[item]}else if(typeof item==="object"){return item}return undefined},$$:function(categoryName){var returnArray=this._categoryRegister[categoryName]||new $i_75;return returnArray.filter(({_isBeingRemoved})=>{return _isBeingRemoved!=true})},$$$:function(groupName){return this._groupRegister[groupName]||new $i_75},register:function(obj){if(obj!==undefined){if(!this._register[obj.id()]){this._register[obj.id()]=obj;obj._registered=true;return this}else{obj._registered=false;$i_102.prototype.log(`Cannot add object id "${obj.id()}" to scenegraph because there is already another object in the graph with the same ID!`,"error");return false}}return this._register},unRegister:function(obj){if(obj!==undefined){if(this._register[obj.id()]){delete this._register[obj.id()];obj._registered=false}}return this},categoryRegister:function(obj){if(obj!==undefined){this._categoryRegister[obj._category]=this._categoryRegister[obj._category]||new $i_75;this._categoryRegister[obj._category].push(obj);obj._categoryRegistered=true}return this._register},categoryUnRegister:function(obj){if(obj!==undefined){if(this._categoryRegister[obj._category]){this._categoryRegister[obj._category].pull(obj);obj._categoryRegistered=false}}return this},groupRegister:function(obj,groupName){if(obj!==undefined){this._groupRegister[groupName]=this._groupRegister[groupName]||new $i_75;this._groupRegister[groupName].push(obj);obj._groupRegistered=true}return this._register},groupUnRegister:function(obj,groupName){if(obj!==undefined){if(groupName!==undefined){if(this._groupRegister[groupName]){this._groupRegister[groupName].pull(obj);if(!obj.groupCount()){obj._groupRegister=false}}}else{obj.removeAllGroups()}}return this},sync:function(method,attrArr){if(typeof attrArr==="string"){attrArr=[attrArr]}this._syncArr=this._syncArr||[];this._syncArr.push({method:method,attrArr:attrArr});if(this._syncArr.length===1){this._syncIndex=0;this._processSync()}},_processSync:function(){var syncEntry;if(ige._syncIndexthis._dependencyCheckTimeout){$i_102.prototype.log(`Engine start failed because the dependency check timed out after ${this._dependencyCheckTimeout/1000} seconds`,"error");if(typeof callback==="function"){callback(false)}}else{setTimeout(function(){ige.start(callback)},200)}}}},stop:function(){if(this._state){console.trace();$i_102.prototype.log("Stopping engine...");this._state=0;return true}else{return false}},autoSize:function(val){if(val!==undefined){this._autoSize=val;return this}return this._autoSize},pixelRatioScaling:function(val){if(val!==undefined){this._pixelRatioScaling=val;return this}return this._pixelRatioScaling},renderContext:function(contextId){if(contextId!==undefined){this._renderContext=contextId;this._renderMode=this._renderModes[contextId];$i_102.prototype.log(`Rendering mode set to: ${contextId}`);return this}return this._renderContext},createFrontBuffer:function(autoSize,dontScale){var self=this;if(this.isClient){if(!this._canvas){this._createdFrontBuffer=true;this._pixelRatioScaling=!dontScale;this._frontBufferSetup(autoSize,dontScale)}}},_frontBufferSetup:function(autoSize,dontScale){if(ige.isServer){this.canvas(tempCanvas,autoSize);document.getElementById("game-div").appendChild(tempCanvas)}else{var tempCanvas=document.getElementById("igeFrontBuffer");this.canvas(tempCanvas,autoSize)}},getCtx:function(){var alpha=true;if(ige.isClient&&ige.client){alpha=ige.client.ctxAlphaEnabled}var contex=this._canvas.getContext("webgl2",{alpha:alpha})||this._canvas.getContext("webgl",{alpha:alpha})||this._canvas.getContext("2d",{alpha:alpha});this._ctx=contex.canvas},canvas:function(elem,autoSize){if(elem!==undefined){if(!this._canvas){this._canvas=elem;this.getCtx();if(this._pixelRatioScaling){this._devicePixelRatio=window.devicePixelRatio||1;this._backingStoreRatio=this._ctx.webkitBackingStorePixelRatio||this._ctx.mozBackingStorePixelRatio||this._ctx.msBackingStorePixelRatio||this._ctx.oBackingStorePixelRatio||this._ctx.backingStorePixelRatio||1;this._deviceFinalDrawRatio=this._devicePixelRatio/this._backingStoreRatio}else{this._devicePixelRatio=1;this._backingStoreRatio=1;this._deviceFinalDrawRatio=1}if(autoSize){this._autoSize=autoSize}window.addEventListener("resize",this._resizeEvent);this._resizeEvent();this.getCtx();this._headless=false;this.input.setupListeners(this._canvas)}}return this._canvas},clearCanvas:function(){if(this._ctx){this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height)}},removeCanvas:function(){if(this.input){this.input.destroyListeners()}window.removeEventListener("resize",this._resizeEvent);if(this._createdFrontBuffer){document.body.removeChild(this._canvas)}delete this._canvas;delete this._ctx;this._ctx=$i_46;this._headless=true},openUrl:function(url){if(url!==undefined){if(ige.cocoonJs&&ige.cocoonJs.detected){ige.cocoonJs.openUrl(url)}else{window.open(url)}}},showWebView:function(url){if(ige.cocoonJs&&ige.cocoonJs.detected){ige.cocoonJs.showWebView(url)}else{var overlay=document.getElementById("igeOverlay");if(!overlay){overlay=document.createElement("iframe");overlay.id="igeOverlay";overlay.style.position="absolute";overlay.style.border="none";overlay.style.left="0px";overlay.style.top="0px";overlay.style.width="100%";overlay.style.height="100%";document.body.appendChild(overlay)}if(url!==undefined){overlay.src=url}overlay.style.display="block"}return this},hideWebView:function(){if(ige.cocoonJs&&ige.cocoonJs.detected){ige.cocoonJs.hideWebView()}else{var overlay=document.getElementById("igeOverlay");if(overlay){overlay.style.display="none"}}return this},layerCall:function(js){if(js!==undefined){eval(js)}},mousePos:function(){return this._mousePos.clone()},mouseOverList:function(obj,entArr){var arr;var arrCount;var mp;var mouseTriggerPoly;var first=false;if(!obj){obj=ige;entArr=[];first=true}if(obj===ige){arr=obj._children;if(arr){arrCount=arr.length;while(arrCount--){if(arr[arrCount]._scene){if(arr[arrCount]._scene._shouldRender){this.mouseOverList(arr[arrCount]._scene,entArr)}}}}}else{mp=this.mousePosWorld();if(mp&&obj.aabb){mouseTriggerPoly=obj.aabb();if(mouseTriggerPoly.xyInside(mp.x,mp.y)){entArr.push(obj)}}arr=obj._children;if(arr){arrCount=arr.length;while(arrCount--){this.mouseOverList(arr[arrCount],entArr)}}}if(first){entArr.reverse()}return entArr},_resizeEvent:function(event){var canvasBoundingRect;if(ige.isClient)return;if(ige._autoSize){var newWidth=window.innerWidth;var newHeight=window.innerHeight;var arr=ige._children;var arrCount=arr.length;if(ige._canvas){canvasBoundingRect=ige._canvasPosition();newWidth-=parseInt(canvasBoundingRect.left);newHeight-=parseInt(canvasBoundingRect.top);if(newWidth%2){newWidth--}if(newHeight%2){newHeight--}if(ige.client&&ige.client.resolutionQuality==="low"){ige._canvas.width=newWidth*ige._deviceFinalDrawRatio/2;ige._canvas.height=newHeight*ige._deviceFinalDrawRatio/2;ige._bounds2d=new $i_5(newWidth/2,newHeight/2,0)}else{ige._canvas.width=newWidth*ige._deviceFinalDrawRatio;ige._canvas.height=newHeight*ige._deviceFinalDrawRatio;ige._bounds2d=new $i_5(newWidth,newHeight,0)}if(ige._deviceFinalDrawRatio!==1||ige.client&&ige.client.resolutionQuality==="low"){ige._canvas.style.width=`${newWidth}px`;ige._canvas.style.height=`${newHeight}px`;ige._ctx.scale(ige._deviceFinalDrawRatio,ige._deviceFinalDrawRatio)}}while(arrCount--){arr[arrCount]._resizeEvent(event)}}else{if(ige._canvas){if(ige.isClient&&ige.client.scaleMode>0){if(ige.client.scaleMode==1||ige.client.scaleMode==3){var newWidth=window.innerWidth;var newHeight=window.innerHeight;if(ige.client.scaleMode==1){var aspectWindow=window.innerWidth/window.innerHeight;var aspectResolution=$("#igeFrontBuffer").attr("width")/$("#igeFrontBuffer").attr("height");if(aspectWindow>=aspectResolution){newWidth=newHeight*aspectResolution}else{newHeight=newWidth/aspectResolution}}canvasBoundingRect=ige._canvasPosition();newWidth-=parseInt(canvasBoundingRect.left);newHeight-=parseInt(canvasBoundingRect.top);if(newWidth%2){newWidth--}if(newHeight%2){newHeight--}ige._canvas.style.width=`${newWidth}px`;ige._canvas.style.height=`${newHeight}px`;ige._ctx.scale(ige._deviceFinalDrawRatio,ige._deviceFinalDrawRatio)}}else{var w=$("#igeFrontBuffer").attr("width");var h=$("#igeFrontBuffer").attr("height");ige._canvas.style.width=`${w}px`;ige._canvas.style.height=`${h}px`}ige._bounds2d=new $i_5(ige._canvas.width,ige._canvas.height,0)}}if(ige._showSgTree){var sgTreeElem=document.getElementById("igeSgTree");canvasBoundingRect=ige._canvasPosition();sgTreeElem.style.top=`${parseInt(canvasBoundingRect.top)+5}px`;sgTreeElem.style.left=`${parseInt(canvasBoundingRect.left)+5}px`;sgTreeElem.style.height=`${ige._bounds2d.y-30}px`}ige._resized=true},scaleMap:function(map){var gameMap=_.cloneDeep(map);if(ige.game.data.defaultData.dontResize){ige.scaleMapDetails={scaleFactor:{x:1,y:1},shouldScaleTilesheet:false,tileWidth:gameMap.tilewidth,tileHeight:gameMap.tileheight,originalTileHeight:gameMap.tileheight,originalTileWidth:gameMap.tilewidth}}else{gameMap.originalTileWidth=gameMap.tilewidth;gameMap.originalTileHeight=gameMap.tileheight;ige.scaleMapDetails={scaleFactor:{x:64/gameMap.originalTileWidth,y:64/gameMap.originalTileHeight},originalTileHeight:gameMap.originalTileHeight,originalTileWidth:gameMap.originalTileWidth,tileWidth:64,tileHeight:64,shouldScaleTilesheet:false};if(ige.scaleMapDetails.scaleFactor.x!==1||ige.scaleMapDetails.scaleFactor.y!==1){ige.scaleMapDetails.shouldScaleTilesheet=true}}return gameMap},_canvasPosition:function(){try{return ige._canvas.getBoundingClientRect()}catch(e){return{top:ige._canvas.offsetTop,left:ige._canvas.offsetLeft}}},toggleFullScreen:function(){var elem=this._canvas;if(elem.requestFullscreen){elem.requestFullscreen()}else if(elem.mozRequestFullScreen){elem.mozRequestFullScreen()}else if(elem.webkitRequestFullscreen){elem.webkitRequestFullscreen()}},watchStart:function(evalStringOrObject){this._watch=this._watch||[];this._watch.push(evalStringOrObject);return this._watch.length-1},watchStop:function(index){this._watch=this._watch||[];this._watch.splice(index,1)},traceSet:function(obj,propName,sampleCount,callbackEvaluator){obj.___igeTraceCurrentVal=obj.___igeTraceCurrentVal||{};obj.___igeTraceCurrentVal[propName]=obj[propName];obj.___igeTraceMax=sampleCount||1;obj.___igeTraceCount=0;Object.defineProperty(obj,propName,{get:function(){return obj.___igeTraceCurrentVal[propName]},set:function(val){if(callbackEvaluator){if(callbackEvaluator(val)){debugger}}else{debugger}obj.___igeTraceCurrentVal[propName]=val;obj.___igeTraceCount++;if(obj.___igeTraceCount===obj.___igeTraceMax){ige.traceSetOff(obj,propName)}}})},traceSetOff:function(object,propName){Object.defineProperty(object,propName,{set:function(val){this.___igeTraceCurrentVal[propName]=val}})},findBaseClass:function(obj){if(obj&&obj._classId){if(obj._classId.substr(0,3)==="Ige"){return obj._classId}else{if(obj.__proto__._classId){return this.findBaseClass(obj.__proto__)}else{return""}}}else{return""}},getClassDerivedList:function(obj,arr){if(!arr){arr=[]}else{if(obj._classId){arr.push(obj._classId)}}if(obj.__proto__._classId){this.getClassDerivedList(obj.__proto__,arr)}return arr},spawnQueue:function(ent){if(ent!==undefined){this._spawnQueue.push(ent);return this}return this._spawnQueue},_secondTick:function(){var self=ige;self._renderFPS=self._renderFrames;self._physicsFPS=self._physicsFrames;self._dps=self._dpf*self._renderFPS;if(ige.isClient)$("#updatefps").html(self._renderFPS);self._renderFrames=0;self._physicsFrames=0;self._drawCount=0},timeScale:function(val){if(val!==undefined){this._timeScale=val;return this}return this._timeScale},incrementTime:function(){var now=Date.now();this._currentTime=(now+this.timeDiscrepancy)*this._timeScale;this.renderTime=this._currentTime-100;return this._currentTime},currentTime:function(){return this._currentTime},pause:function(val){if(val!==undefined){this._pause=val;return this}return this._pause},useManualTicks:function(val){if(val!==undefined){this._useManualTicks=val;return this}return this._useManualTicks},manualTick:function(){if(this._manualFrameAlternator!==this._frameAlternator){this._manualFrameAlternator=this._frameAlternator;requestAnimFrame(this.engineStep)}},useManualRender:function(val){if(val!==undefined){this._useManualRender=val;return this}return this._useManualRender},manualRender:function(){this._manualRender=true},updateCreateEntitySnapshot:function(){var allEntities=ige.$("baseScene")._children;if(allEntities){for(var i=0;i=1000/ige._gameLoopTickRate-ige._gameLoopTickRemainder){ige._lastGameLoopTickAt=ige.now;ige._gameLoopTickRemainder=Math.min(timeElapsed-(1000/ige._gameLoopTickRate-ige._gameLoopTickRemainder),1000/ige._gameLoopTickRate);ige.gameLoopTickHasExecuted=true}var timeElapsed=ige.now-ige._lastPhysicsTickAt;if(ige.physics&&(ige.gameLoopTickHasExecuted||timeElapsed>=1000/ige._physicsTickRate-ige._physicsTickRemainder)){ige._lastPhysicsTickAt=ige.now;ige._physicsTickRemainder=Math.min(timeElapsed-(1000/ige._physicsTickRate-ige._physicsTickRemainder),1000/ige._physicsTickRate);ige.physics.update(timeElapsed);ige.physicsTickHasExecuted=true}if(ige.isServer){if(ige.gameLoopTickHasExecuted)ige.trigger.fire("frameTick")}else if(ige.isClient){var snapshot=ige.snapshots[0];while(snapshot&&(ige.renderTime>snapshot[0]||ige.nextSnapshot&&ige.renderTime>ige.nextSnapshot[0])){snapshot=ige.snapshots.shift();ige.prevSnapshot=ige.nextSnapshot;ige.nextSnapshot=snapshot}if(ige.client.myPlayer){ige.client.myPlayer.control._behaviour()}return}ige.updateCount=0;ige.tickCount=0;ige.updateTransform=0;ige.inViewCount=0;ige.entityManagerUpdateBehaviour=0;ige.entityManagerUpdateorphan=0;ige.entityManagerUpdateChildren=0;ige.totalChildren=0;ige.totalOrphans=0;if(self._enableUpdates){if(igeConfig.debug._timing){updateStart=Date.now();self.updateSceneGraph(ctx);ige._updateTime=Date.now()-updateStart}else{self.updateSceneGraph(ctx)}}if(!ige.gameLoopTickHasExecuted){return}unbornQueue=ige._spawnQueue;unbornCount=unbornQueue.length;for(unbornIndex=unbornCount-1;unbornIndex>=0;unbornIndex--){unbornEntity=unbornQueue[unbornIndex];if(ige._currentTime>=unbornEntity._bornTime){unbornEntity.mount(ige.$(unbornEntity._birthMount));unbornQueue.splice(unbornIndex,1)}}if(self._enableRenders){if(!self._useManualRender){if(igeConfig.debug._timing){renderStart=Date.now();self.renderSceneGraph(ctx)}else{self.renderSceneGraph(ctx)}}else{if(self._manualRender){if(igeConfig.debug._timing){renderStart=Date.now();self.renderSceneGraph(ctx)}else{self.renderSceneGraph(ctx)}self._manualRender=false}}}self.lastTick=self._tickStart;self._dpf=self._drawCount;self._drawCount=0;if(ige.isServer){if(self.now-self.lastCheckedAt>1000){self.lastCheckedAt=self.now;var playerCount=ige.$$("player").filter(function(player){return player._stats.controlledBy=="human"}).length;if(playerCount<=0){if(!self.serverEmptySince){self.serverEmptySince=self.now}if((ige.server.tier==="1"||ige.server.tier==="2")&&self.now-self.serverEmptySince>self.emptyTimeLimit){ige.server.kill("game's been empty for too long (10 min)")}}else{self.serverEmptySince=null}var lifeSpan=self.getLifeSpan();var age=self.now-ige.server.gameStartedAt;var shouldLog=ige.server.logTriggers&&ige.server.logTriggers.timerLogs;if(shouldLog){console.log(self.now,ige.server.gameStartedAt,age,lifeSpan,age>lifeSpan)}if(age>lifeSpan){console.log({lifeSpan,age,now:self.now,startedAt:ige.server.gameStartedAt});ige.server.kill(`server lifespan expired ${lifeSpan}`)}}}ige.network.stream._sendQueue(timeStamp);ige.network.stream.updateEntityAttributes();if(ige.count==undefined||ige.now-ige.lastSent<30){ige.count=0}ige.lastSent=ige.now;ige.count++}ige.gameLoopTickHasExecuted=false;ige.physicsTickHasExecuted=false;self._resized=false;et=new Date().getTime();ige._tickTime=et-ige.now;if(ige.server&&ige.server.gameId=="5a7fd59b1014dc000eeec3dd")if(ige._tickTime>1000/self._fpsRate){self.lagOccurenceCount++;self.lastLagOccurenceAt=et;if(self.lagOccurenceCount>50){console.log("engineTick is taking too long! (",ige._tickTime,"ms. It should be under",1000/self._fpsRate,`(${self.lagOccurenceCount}/100)`)}if(self.lagOccurenceCount>100){ige.server.kill("engineTick has been consistently running slow. killing the server. (this causes lag)")}}else{self.lagOccurenceCount=0}if(ige.isClient){if(statsPanels.ms){statsPanels.fps.end();statsPanels.ms.end()}}},updateSceneGraph:function(ctx){var arr=this._children;var arrCount;var us;var ud;var tickDelta=ige._tickDelta;this._processUpdateBehaviours(ctx,tickDelta);if(arr){arrCount=arr.length;if(igeConfig.debug._timing){while(arrCount--){us=new Date().getTime();arr[arrCount].update(ctx,tickDelta);ud=new Date().getTime()-us;if(arr[arrCount]){if(!ige._timeSpentInUpdate[arr[arrCount].id()]){ige._timeSpentInUpdate[arr[arrCount].id()]=0}if(!ige._timeSpentLastUpdate[arr[arrCount].id()]){ige._timeSpentLastUpdate[arr[arrCount].id()]={}}ige._timeSpentInUpdate[arr[arrCount].id()]+=ud;ige._timeSpentLastUpdate[arr[arrCount].id()].ms=ud}}}else{while(arrCount--){arr[arrCount].update(ctx,tickDelta)}}}},renderSceneGraph:function(ctx){var ts,td;this._processTickBehaviours(ctx);if(ige.isServer){if(this._viewportDepth){if(igeConfig.debug._timing){ts=new Date().getTime();this.depthSortChildren();td=new Date().getTime()-ts;if(!ige._timeSpentLastTick[this.id()]){ige._timeSpentLastTick[this.id()]={}}ige._timeSpentLastTick[this.id()].depthSortChildren=td}else{this.depthSortChildren()}}ctx.save();ctx.translate(this._bounds2d.x2,this._bounds2d.y2);var arr=this._children;var arrCount;if(arr){arrCount=arr.length;if(igeConfig.debug._timing){while(arrCount--){ctx.save();ts=new Date().getTime();arr[arrCount].tick(ctx);td=new Date().getTime()-ts;if(arr[arrCount]){if(!ige._timeSpentInTick[arr[arrCount].id()]){ige._timeSpentInTick[arr[arrCount].id()]=0}if(!ige._timeSpentLastTick[arr[arrCount].id()]){ige._timeSpentLastTick[arr[arrCount].id()]={}}ige._timeSpentInTick[arr[arrCount].id()]+=td;ige._timeSpentLastTick[arr[arrCount].id()].ms=td}ctx.restore()}}else{while(arrCount--){ctx.save();arr[arrCount].tick(ctx);ctx.restore()}}}ctx.restore()}},fps:function(){return this._renderFPS},dpf:function(){return this._dpf},dps:function(){return this._dps},analyseTiming:function(){if(!igeConfig.debug._timing){$i_102.prototype.log("Cannot analyse timing because the igeConfig.debug._timing flag is not enabled so no timing data has been recorded!","warning")}},saveSceneGraph:function(item){var arr,arrCount,i;if(!item){item=this.getSceneGraphData()}if(item.obj.stringify){item.str=item.obj.stringify()}else{$i_102.prototype.log(`Class ${item.classId} has no stringify() method! For object: ${item.id}`,item.obj)}arr=item.items;if(arr){arrCount=arr.length;for(i=0;i0){item.items=items}return item},_childMounted:function(child){if(child.$i_68){if(!ige._currentViewport){ige._currentViewport=child;ige._currentCamera=child.camera}}$i_56.prototype._childMounted.call(this,child)},destroy:function(){this.stop();if(this.isClient){this.removeCanvas()}$i_56.prototype.destroy.call(this);$i_102.prototype.log("Engine destroy complete.")},devLog:function(){}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_102}var $i_103=$i_3.extend({classId:"$i_103",componentId:"physics",init:function(entity,options){if(ige._state!=0){console.log("Cannot add box2d physics component to the ige instance once the engine has started!","error")}this._entity=entity;this._options=options;this._mode=0;this._actionQueue=[];this._scaleRatio=30;this.physicsTickDuration=0;this.avgPhysicsTickDuration=0;this.totalBodiesCreated=0;this.lastSecondAt=Date.now();this.totalDisplacement=0;this.totalTimeElapsed=0;this.exponent=2;this.divisor=80;if(ige.isServer){this.engine=$i_106.defaultEngine;if(ige.game&&ige.game.data&&ige.game.data.defaultData){this.engine=ige.game.data.defaultData.physicsEngine}}else if(ige.isClient){if(ige.game&&ige.game.data&&ige.game.data.defaultData){this.engine=ige.game.data.defaultData.clientPhysicsEngine}}this.engine=this.engine.toUpperCase();console.log("Physics engine: ",this.engine);if(this.engine){$i_106[this.engine].init(this)}else{if(ige.isClient){alert("no physics engine selected")}}},gravity:function(x,y){$i_106[this.engine].gravity(x,y)},useWorker:function(val){if(typeof Worker!=="undefined"){if(val!==undefined){this._useWorker=val;return this._entity}return this._useWorker}else{$i_103.prototype.log("Web workers were not detected on this browser. Cannot access useWorker() method.","warning")}},mode:function(val){if(val!==undefined){this._mode=val;return this._entity}return this._mode},sleep:function(val){if(val!==undefined){this._sleep=val;return this._entity}return this._sleep},scaleRatio:function(val){if(val!==undefined){this._scaleRatio=val;return this._entity}return this._scaleRatio},tilesizeRatio:function(val){if(val!==undefined){this._tilesizeRatio=val;return this._entity}return this._tilesizeRatio},world:function(){return this._world},createFixture:function(params){var tempDef=new this.b2FixtureDef;var param;for(param in params){if(params.hasOwnProperty(param)){if(param!=="shape"&¶m!=="filter"){tempDef[param]=params[param]}}}return tempDef},createBody:function(entity,body,isLossTolerant){this.totalBodiesCreated++;return $i_106[this.engine].createBody(this,entity,body,isLossTolerant)},destroyBody:function(entity,body){if(body||entity&&entity.body){body=body||entity.body;destroyBody=this._world.destroyBody;var isBodyDestroyed=destroyBody.apply(this._world,[body]);if(this.engine=="BOX2DWEB"){this._world.m_contactSolver.m_constraints=[];this._world.m_island.m_bodies=[];this._world.m_island.m_contacts=[];this._world.m_island.m_joints=[];this._world.m_contactManager.m_broadPhase.m_pairBuffer=[];this._world.m_contactManager.m_broadPhase.m_tree.m_freeList=null;for(var i=0;i<$i_108.Dynamics.b2World.s_queue.length;i++){if($i_108.Dynamics.b2World.s_queue[i]._entity._id==entity._id){$i_108.Dynamics.b2World.s_queue.splice(i,1)}}for(var i=0;i0){var action=self._actionQueue.shift();queueSize++;if(queueSize>1000){ige.devLog(`$i_103.js _behaviour queue looped over 1000 times. Currently processing action: ${action.type}`)}switch(action.type){case"createBody":self.createBody(action.entity,action.def);break;case"destroyBody":self.destroyBody(action.entity);break;case"createJoint":self.createJoint(action.entityA,action.entityB,action.anchorA,action.anchorB);break;case"destroyJoint":self.destroyJoint(action.entityA,action.entityB);break;}}}let timeStart=ige.now;if(self.engine=="crash"){self._world.step(timeElapsedSinceLastStep)}else{self._world.step(timeElapsedSinceLastStep/1000,8,3);var tempBod=self._world.getBodyList();while(tempBod&&typeof tempBod.getNext=="function"){if(tempBod.m_type!=="static"&&tempBod.isAwake()){entity=tempBod._entity;if(entity){var mxfp=$i_106[ige.physics.engine].getmxfp(tempBod);var x=mxfp.x*ige.physics._scaleRatio;var y=mxfp.y*ige.physics._scaleRatio;if(entity._category=="projectile"&&entity._stats.currentBody&&!entity._stats.currentBody.fixedRotation&&tempBod.m_linearVelocity.y!=0&&tempBod.m_linearVelocity.x!=0){var angle=Math.atan2(tempBod.m_linearVelocity.y,tempBod.m_linearVelocity.x)+Math.PI/2}else{var angle=tempBod.getAngle()}var tileWidth=ige.scaleMapDetails.tileWidth;var tileHeight=ige.scaleMapDetails.tileHeight;var skipBoundaryCheck=entity._stats&&entity._stats.confinedWithinMapBoundaries===false;var padding=tileWidth/2;if((entity._category=="unit"||entity._category=="debris"||entity._category=="item"||entity._category=="projectile")&&!skipBoundaryCheck&&(xige.map.data.width*tileWidth-padding||yige.map.data.height*tileHeight-padding)){if(!entity.isOutOfBounds){if(entity._category=="unit"){ige.trigger.fire("unitTouchesWall",{unitId:entity.id()})}else if(entity._category=="item"){ige.trigger.fire("itemTouchesWall",{itemId:entity.id()})}else if(entity._category=="projectile"){ige.trigger.fire("projectileTouchesWall",{projectileId:entity.id()})}entity.isOutOfBounds=true}x=Math.max(Math.min(x,ige.map.data.width*tileWidth-padding),padding);y=Math.max(Math.min(y,ige.map.data.height*tileHeight-padding),padding)}else{if(entity.isOutOfBounds){entity.isOutOfBounds=false}}if(ige.isServer){if(ige.game.cspEnabled&&entity.clientStreamedPosition){var targetX=entity.clientStreamedPosition[0];var targetY=entity.clientStreamedPosition[1];var xDiff=targetX-x;var yDiff=targetY-y;x+=xDiff/2;y+=yDiff/2}entity.translateTo(x,y,0);entity.rotateTo(0,0,angle)}else if(ige.isClient){let nextFrameTime=ige._currentTime+1000/ige._physicsTickRate;if(ige.physics&&ige.game.cspEnabled&&ige.client.selectedUnit==entity){if(entity.isOutOfBounds){entity.body.setPosition({x:x/entity._b2dRef._scaleRatio,y:y/entity._b2dRef._scaleRatio});entity.body.setAngle(angle)}if(entity.nextPhysicsFrame==undefined||ige._currentTime>entity.nextPhysicsFrame[0]){entity.prevPhysicsFrame=entity.nextPhysicsFrame;entity.nextPhysicsFrame=[nextFrameTime,[x,y,angle]]}}else if(entity._category=="projectile"&&entity._stats.sourceItemId!=undefined){if(entity._streamMode==0){entity.prevPhysicsFrame=entity.nextPhysicsFrame;entity.nextPhysicsFrame=[nextFrameTime,[x,y,angle]]}}else{x=entity._translate.x;y=entity._translate.y;angle=entity._rotate.z;entity.nextPhysicsFrame=undefined;entity.body.setPosition({x:x/entity._b2dRef._scaleRatio,y:y/entity._b2dRef._scaleRatio});entity.body.setAngle(angle)}}if(tempBod.asleep){tempBod.asleep=false;ige.physics.emit("afterAwake",entity)}}else{if(!tempBod.asleep){tempBod.asleep=true;ige.physics.emit("afterAsleep",entity)}}}tempBod=tempBod.getNext()}ige._physicsFrames++;self._world.clearForces();var timeEnd=Date.now();self.physicsTickDuration+=timeEnd-timeStart;if(timeEnd-self.lastSecondAt>1000){self.lastSecondAt=timeEnd;self.avgPhysicsTickDuration=self.physicsTickDuration/ige._fpsRate;self.totalDisplacement=0;self.totalTimeElapsed=0;self.physicsTickDuration=0}}if(typeof self._updateCallback==="function"){self._updateCallback()}}},destroy:function(){this._entity.removeBehaviour("box2dStep");if(ige.isClient){clearInterval(this._intervalTimer)}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_103}var $i_56Physics=$i_56.extend({classId:"$i_56Physics",init:function(defaultData={}){$i_56.prototype.init.call(this,defaultData);var self=this;this._b2dRef=ige.physics;if(ige.isClient){self.addComponent($i_10)}if(ige.isServer&&ige.physics){if(!this._b2dRef._networkDebugMode){this._translateToProto=this.translateTo;this._translateByProto=this.translateBy;this._rotateToProto=this.rotateTo;this._rotateByProto=this.rotateBy;this.translateTo=this._translateTo;this.translateBy=this._translateBy;this.rotateTo=this._rotateTo;this.rotateBy=this._rotateBy}else{this._translateToProto=function(){};this._translateByProto=function(){};this._rotateToProto=function(){};this._rotateByProto=function(){};this._updateProto=this.update}this.jointsAttached={};this.isOutOfBounds=false}this._actionQueue=[];if(ige.isClient){self.addComponent(IgePixiTexture);self.addComponent(IgePixiAnimation)}},updateBody:function(defaultData,isLossTolerant){var self=this;body=this._stats.currentBody;if(!body){return}if(body.type==="none"||body.type==="spriteOnly"){self.destroyBody();return}this.width(parseFloat(body.width)*this._scale.x);this.height(parseFloat(body.height)*this._scale.y);var filterCategoryBits=2;if(this._category==="units"){filterCategoryBits=2}else if(this._category==="debris"){filterCategoryBits=4}else if(this._category==="item"){filterCategoryBits=8}else if(this._category==="projectile"){filterCategoryBits=16}else if(this._category==="region"){filterCategoryBits=32}else if(this._category==="sensor"){filterCategoryBits=64}var collidesWith=body.collidesWith||{};var body={type:body.type||"dynamic",linearDamping:parseFloat(body.linearDamping)||0,angularDamping:parseFloat(body.angularDamping)||0,allowSleep:false,bullet:body.bullet,fixedRotation:body.fixedRotation,affectedByGravity:body.affectedByGravity!=false,fixtures:[{density:body.fixtures?parseFloat(body.fixtures[0].density):0,friction:body.fixtures?parseFloat(body.fixtures[0].friction):0,restitution:body.fixtures?body.fixtures[0].restitution:0,isSensor:body.fixtures?body.fixtures[0].isSensor||false:false,filter:{filterGroupIndex:0,filterCategoryBits:filterCategoryBits,filterMaskBits:(collidesWith.walls?1:0)|(collidesWith.units?2:0)|(collidesWith.debris?4:0)|(collidesWith.items?8:0)|(collidesWith.projectiles?16:0)|(this._category!="sensor"?32:0)|(this._category=="unit"||this._category=="item"?64:0)},shape:{type:body.fixtures&&body.fixtures[0]&&body.fixtures[0].shape&&body.fixtures[0].shape.type?body.fixtures[0].shape.type:"rectangle",data:body.fixtures&&body.fixtures[0]&&body.fixtures[0].shape&&body.fixtures[0].shape.data?body.fixtures[0].shape.data:undefined},igeId:this.id()}]};this.physicsBody(body,isLossTolerant);if(defaultData){var rotate=defaultData.rotate;if(!isNaN(rotate)){this.rotateTo(0,0,rotate)}if(defaultData.translate){var x=defaultData.translate.x;var y=defaultData.translate.y;if(!isNaN(x)&&!isNaN(y)){this.translateTo(x,y,0)}}if(defaultData.velocity&&!isNaN(defaultData.velocity.x)&&!isNaN(defaultData.velocity.y)){switch(defaultData.velocity.deployMethod){case"applyForce":this.applyForce(defaultData.velocity.x,defaultData.velocity.y);break;case"applyImpulse":this.applyImpulse(defaultData.velocity.x,defaultData.velocity.y);break;case"setVelocity":default:this.setLinearVelocity(defaultData.velocity.x,defaultData.velocity.y,0,isLossTolerant);break;}}}},box2dActive:function(val){if(this.body){if(val!==undefined){this.body.setActive(val);return this}return this.body.isActive()}return this},physicsBody:function(def,isLossTolerant){if(def){this.bodyDef=def;if(ige.physics){if(isLossTolerant){ige.physics.createBody(this,def,isLossTolerant)}else{this.destroyBody();ige.physics.queueAction({type:"createBody",entity:this,def:def})}}else{}return this}return this.bodyDef},destroyBody:function(){$i_56Physics.prototype.log("destroyBody");if(this.jointsAttached){for(var entityId in this.jointsAttached){this.detachEntity(entityId)}}ige.physics&&ige.physics.queueAction({type:"destroyBody",entity:this,body:this.body})},gravitic:function(val){if(this.body){if(val!==undefined){this.body.m_nonGravitic=!val;this.body.m_gravityScale=!val?0:1;this.body.setAwake(true);return this}return!this.body.m_nonGravitic}},on:function(){if(arguments.length===3){var evName=arguments[0];var target=arguments[1];var callback=arguments[2];var type;switch(target.substr(0,1)){case"#":type=0;break;case".":type=1;break;}target=target.substr(1,target.length-1);switch(evName){case"collisionStart":this._collisionStartListeners=this._collisionStartListeners||[];this._collisionStartListeners.push({type:type,target:target,callback:callback});if(!this._contactListener){this._contactListener=this._setupContactListeners()}break;case"collisionEnd":this._collisionEndListeners=this._collisionEndListeners||[];this._collisionEndListeners.push({type:type,target:target,callback:callback});if(!this._contactListener){this._contactListener=this._setupContactListeners()}break;default:$i_56Physics.prototype.log(`Cannot add event listener, event type ${evName} not recognised`,"error");break;}}else{$i_56.prototype.on.apply(this,arguments)}},off:function(){if(arguments.length===3){}else{$i_56.prototype.off.apply(this,arguments)}},attachTo:function(entityB,anchorA,anchorB){for(entityId in this.jointsAttached){this.detachEntity(entityId)}var self=this;ige.physics.queueAction({type:"createJoint",entityA:self,entityB:entityB,anchorA:anchorA,anchorB:anchorB})},detachEntity:function(entityId){var attachedEntity=ige.$(entityId);if(entityId&&attachedEntity){$i_56Physics.prototype.log(`detachEntity ${this._stats.name} ${attachedEntity._stats.name}`);ige.physics.queueAction({type:"destroyJoint",entityA:this,entityB:attachedEntity})}},applyTorque:function(torque){if(ige.physics._world.isLocked()||this.body==undefined){this.queueAction({type:"applyTorque",torque:torque})}else{this.applyTorqueLT(torque)}},setLinearVelocity:function(x,y,z,isLossTolerant){if(!ige.physics._world.isLocked()&&this.body!=undefined||isLossTolerant){this.setLinearVelocityLT(x,y)}else{this.queueAction({type:"setLinearVelocity",x:x,y:y})}},setLinearVelocityLT:function(x,y){try{ige.physicsTickCount++;if(!isNaN(x)&&!isNaN(y)&&isFinite(x)&&isFinite(y)){this.body.setLinearVelocity(new $i_5(x,y,0))}}catch(e){console.log(`$i_56Box2d.js: setLinearVelocityLT ${e}`)}},applyForce:function(x,y){if(!ige.physics)return;if(!ige.physics._world.isLocked()&&this.body!=undefined){this.applyForceLT(x,y)}else{this.queueAction({type:"applyForce",x:x,y:y})}},applyForceLT:function(x,y){try{if(!isNaN(x)&&!isNaN(y)&&isFinite(x)&&isFinite(y)){var thrustVector=new ige.physics.b2Vec2(x,y);this.body.applyForce(thrustVector,this.body.getWorldCenter())}}catch(e){console.log(e);$i_56Physics.prototype.log(`igeEntityBox2d.js: applyForce ${e}`)}},applyImpulse:function(x,y){if(!ige.physics._world.isLocked()&&this.body!=undefined){this.applyImpulseLT(x,y)}else{this.queueAction({type:"applyImpulse",x:x,y:y})}},applyImpulseLT:function(x,y){try{if(!isNaN(x)&&!isNaN(y)&&isFinite(x)&&isFinite(y)){var thrustVector=new ige.physics.b2Vec2(x,y);this.body.applyLinearImpulse(thrustVector,this.body.getWorldCenter())}}catch(e){console.log(e);$i_56Physics.prototype.log(`igeEntityBox2d.js: applyForce ${e}`)}},applyTorqueLT:function(torque){try{if(!isNaN(torque)){this.body.applyTorque(torque)}}catch(e){$i_56Physics.prototype.log(`igeEntityBox2d.js: applyTorque ${e}`)}},_setupContactListeners:function(){var self=this;ige.physics.contactListener(function(contact){var arr=self._collisionStartListeners;if(arr){self._checkContact(contact,arr)}},function(contact){var arr=self._collisionEndListeners;if(arr){self._checkContact(contact,arr)}})},_checkContact:function(contact,arr){var self=this;var arrCount=arr.length;var otherEntity;var listener;var i;if(contact.igeEntityA()._id===self._id){otherEntity=contact.igeEntityB()}else if(contact.igeEntityB()._id===self._id){otherEntity=contact.igeEntityA()}else{return}for(i=0;i0){var action=this._actionQueue.shift();x++;if(x>1000){console.log("$i_56Physics processBox2dQueue running over 1000 times",action.type,this._category,this._stats.name,"id:",this.id())}switch(action.type){case"rotateTo":this.rotateToLT(action.angle);break;case"translateTo":this.translateToLT(action.x,action.y);break;case"applyForce":this.applyForceLT(action.x,action.y);break;case"applyImpulse":this.applyImpulseLT(action.x,action.y);break;case"applyTorque":this.applyTorque(action.torque);break;case"setLinearVelocity":this.setLinearVelocityLT(action.x,action.y);break;case"destroy":this.destroy();break;}}}}},remove:function(){this._isBeingRemoved=true;if(this._stats&&!this.body){this.destroy()}else{this.queueAction({type:"destroy"})}if(ige.isClient){this.clearAllPointers()}},destroy:function(){this._alive=false;this.destroyBody();$i_56.prototype.destroy.call(this);delete this._actionQueue}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_56Physics}var $i_106={defaultEngine:"PLANCK",PLANCK:{init:function(component){component.b2Vec2=$i_107.Vec2;component.b2AABB=$i_107.AABB;component.b2Math=$i_107.Math;component.b2Shape=$i_107.Shape;component.b2Body=$i_107.Body;component.b2Fixture=$i_107.Fixture;component.b2World=$i_107.World;component.b2PolygonShape=$i_107.Polygon;component.b2CircleShape=$i_107.Circle;component.createWorld=function(id,options){component._world=new component.b2World(this._gravity,this._sleep);component._world.setContinuousPhysics(false)};component.gravity=function(x,y){if(x!==undefined&&y!==undefined){this._gravity=new this.b2Vec2(x,y);return this._entity}return this._gravity};component._sleep=true;component._gravity=new component.b2Vec2(0,0)},getmxfp:function(body){return body.m_xf.p},queryAABB:function(self,aabb,callback){self.world().queryAABB(aabb,callback)},createBody:function(self,entity,body,isLossTolerant){$i_103.prototype.log(`createBody of ${entity._stats.name}`);if(!entity){$i_103.prototype.log("warning: creating body for non-existent entity");return}if(entity.body){$i_103.prototype.log("body already exists, destroying body");self.destroyBody(entity)}var tempDef={};var param;var tempBod;var fixtureDef;var finalFixture;var tempShape;var tempFilterData;var i;var finalX;var finalY;var finalWidth;var finalHeight;for(param in body){if(body.hasOwnProperty(param)){switch(param){case"type":case"gravitic":case"fixedRotation":case"fixtures":break;default:tempDef[param]=body[param];break;}}}tempDef.type=body.type;tempDef.angle=entity._rotate.z;tempDef.position=new self.b2Vec2(entity._translate.x/self._scaleRatio,entity._translate.y/self._scaleRatio);tempBod=self._world.createBody(tempDef,undefined,isLossTolerant);for(param in body){if(body.hasOwnProperty(param)){switch(param){case"gravitic":if(!body.gravitic){tempBod.m_nonGravitic=true}break;case"fixedRotation":if(body.fixedRotation){tempBod.setFixedRotation(true)}else if(entity._rotate.z){tempBod.setAngle(entity._rotate.z)}break;case"fixtures":if(body.fixtures&&body.fixtures.length){for(i=0;imax*max){var invLength=Math.invSqrt(lengthSqr);this.x*=invLength*max;this.y*=invLength*max}return this};Vec2.clamp=function(v,max){v=Vec2.neo(v.x,v.y);v.clamp(max);return v};Vec2.scaleFn=function(x,y){return function(v){return Vec2.neo(v.x*x,v.y*y)}};Vec2.translateFn=function(x,y){return function(v){return Vec2.neo(v.x+x,v.y+y)}}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;var common=__webpack_require__(2);var create=__webpack_require__(6);var native=Math;var math=module.exports=create(native);math.EPSILON=1e-9;math.isFinite=function(x){return typeof x==="number"&&isFinite(x)&&!isNaN(x)};math.assert=function(x){if(!_ASSERT)return;if(!math.isFinite(x)){_DEBUG&&common.debug(x);throw new Error("Invalid Number!")}};math.invSqrt=function(x){return 1/native.sqrt(x)};math.nextPowerOfTwo=function(x){x|=x>>1;x|=x>>2;x|=x>>4;x|=x>>8;x|=x>>16;return x+1};math.isPowerOfTwo=function(x){return x>0&&(x&x-1)==0};math.mod=function(num,min,max){if(typeof min==="undefined"){max=1,min=0}else if(typeof max==="undefined"){max=min,min=0}if(max>min){num=(num-min)%(max-min);return num+(num<0?max:min)}else{num=(num-max)%(min-max);return num+(num<=0?min:max)}};math.clamp=function(num,min,max){if(nummax){return max}else{return num}};math.random=function(min,max){if(typeof min==="undefined"){max=1;min=0}else if(typeof max==="undefined"){max=min;min=0}return min==max?min:native.random()*(max-min)+min}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;exports.debug=function(){if(!_DEBUG)return;console.log.apply(console,arguments)};exports.assert=function(statement,err,log){if(!_ASSERT)return;if(statement)return;log&&console.log(log);throw new Error(err)}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Rot;var common=__webpack_require__(2);var Vec2=__webpack_require__(0);var Math=__webpack_require__(1);function Rot(angle){if(!(this instanceof Rot)){return new Rot(angle)}if(typeof angle==="number"){this.setAngle(angle)}else if(typeof angle==="object"){this.set(angle)}else{this.setIdentity()}}Rot.neo=function(angle){var obj=Object.create(Rot.prototype);obj.setAngle(angle);return obj};Rot.clone=function(rot){_ASSERT&&Rot.assert(rot);var obj=Object.create(Rot.prototype);obj.s=rot.s;obj.c=rot.c;return obj};Rot.identity=function(){var obj=Object.create(Rot.prototype);obj.s=0;obj.c=1;return obj};Rot.isValid=function(o){return o&&Math.isFinite(o.s)&&Math.isFinite(o.c)};Rot.assert=function(o){if(!_ASSERT)return;if(!Rot.isValid(o)){_DEBUG&&common.debug(o);throw new Error("Invalid Rot!")}};Rot.prototype.setIdentity=function(){this.s=0;this.c=1};Rot.prototype.set=function(angle){if(typeof angle==="object"){_ASSERT&&Rot.assert(angle);this.s=angle.s;this.c=angle.c}else{_ASSERT&&Math.assert(angle);this.s=Math.sin(angle);this.c=Math.cos(angle)}};Rot.prototype.setAngle=function(angle){_ASSERT&&Math.assert(angle);this.s=Math.sin(angle);this.c=Math.cos(angle)};Rot.prototype.getAngle=function(){return Math.atan2(this.s,this.c)};Rot.prototype.getXAxis=function(){return Vec2.neo(this.c,this.s)};Rot.prototype.getYAxis=function(){return Vec2.neo(-this.s,this.c)};Rot.mul=function(rot,m){_ASSERT&&Rot.assert(rot);if("c"in m&&"s"in m){_ASSERT&&Rot.assert(m);var qr=Rot.identity();qr.s=rot.s*m.c+rot.c*m.s;qr.c=rot.c*m.c-rot.s*m.s;return qr}else if("x"in m&&"y"in m){_ASSERT&&Vec2.assert(m);return Vec2.neo(rot.c*m.x-rot.s*m.y,rot.s*m.x+rot.c*m.y)}};Rot.mulRot=function(rot,m){_ASSERT&&Rot.assert(rot);_ASSERT&&Rot.assert(m);var qr=Rot.identity();qr.s=rot.s*m.c+rot.c*m.s;qr.c=rot.c*m.c-rot.s*m.s;return qr};Rot.mulVec2=function(rot,m){_ASSERT&&Rot.assert(rot);_ASSERT&&Vec2.assert(m);return Vec2.neo(rot.c*m.x-rot.s*m.y,rot.s*m.x+rot.c*m.y)};Rot.mulSub=function(rot,v,w){var x=rot.c*(v.x-w.x)-rot.s*(v.y-w.y);var y=rot.s*(v.x-w.x)+rot.c*(v.y-w.y);return Vec2.neo(x,y)};Rot.mulT=function(rot,m){if("c"in m&&"s"in m){_ASSERT&&Rot.assert(m);var qr=Rot.identity();qr.s=rot.c*m.s-rot.s*m.c;qr.c=rot.c*m.c+rot.s*m.s;return qr}else if("x"in m&&"y"in m){_ASSERT&&Vec2.assert(m);return Vec2.neo(rot.c*m.x+rot.s*m.y,-rot.s*m.x+rot.c*m.y)}};Rot.mulTRot=function(rot,m){_ASSERT&&Rot.assert(m);var qr=Rot.identity();qr.s=rot.c*m.s-rot.s*m.c;qr.c=rot.c*m.c+rot.s*m.s;return qr};Rot.mulTVec2=function(rot,m){_ASSERT&&Vec2.assert(m);return Vec2.neo(rot.c*m.x+rot.s*m.y,-rot.s*m.x+rot.c*m.y)}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;var Settings=exports;Settings.maxManifoldPoints=2;Settings.maxPolygonVertices=12;Settings.aabbExtension=0.1;Settings.aabbMultiplier=2;Settings.linearSlop=0.005;Settings.linearSlopSquared=Settings.linearSlop*Settings.linearSlop;Settings.angularSlop=2/180*Math.PI;Settings.polygonRadius=2*Settings.linearSlop;Settings.maxSubSteps=8;Settings.maxTOIContacts=32;Settings.maxTOIIterations=20;Settings.maxDistnceIterations=20;Settings.velocityThreshold=1;Settings.maxLinearCorrection=0.2;Settings.maxAngularCorrection=8/180*Math.PI;Settings.maxTranslation=500;Settings.maxTranslationSquared=Settings.maxTranslation*Settings.maxTranslation;Settings.maxRotation=0.5*Math.PI;Settings.maxRotationSquared=Settings.maxRotation*Settings.maxRotation;Settings.baumgarte=0.2;Settings.toiBaugarte=0.75;Settings.timeToSleep=0.5;Settings.linearSleepTolerance=0.01;Settings.linearSleepToleranceSqr=Math.pow(Settings.linearSleepTolerance,2);Settings.angularSleepTolerance=2/180*Math.PI;Settings.angularSleepToleranceSqr=Math.pow(Settings.angularSleepTolerance,2)},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Transform;var common=__webpack_require__(2);var Vec2=__webpack_require__(0);var Rot=__webpack_require__(3);function Transform(position,rotation){if(!(this instanceof Transform)){return new Transform(position,rotation)}this.p=Vec2.zero();this.q=Rot.identity();if(typeof position!=="undefined"){this.p.set(position)}if(typeof rotation!=="undefined"){this.q.set(rotation)}}Transform.clone=function(xf){var obj=Object.create(Transform.prototype);obj.p=Vec2.clone(xf.p);obj.q=Rot.clone(xf.q);return obj};Transform.neo=function(position,rotation){var obj=Object.create(Transform.prototype);obj.p=Vec2.clone(position);obj.q=Rot.clone(rotation);return obj};Transform.identity=function(){var obj=Object.create(Transform.prototype);obj.p=Vec2.zero();obj.q=Rot.identity();return obj};Transform.prototype.setIdentity=function(){this.p.setZero();this.q.setIdentity()};Transform.prototype.set=function(a,b){if(typeof b==="undefined"){this.p.set(a.p);this.q.set(a.q)}else{this.p.set(a);this.q.set(b)}};Transform.isValid=function(o){return o&&Vec2.isValid(o.p)&&Rot.isValid(o.q)};Transform.assert=function(o){if(!_ASSERT)return;if(!Transform.isValid(o)){_DEBUG&&common.debug(o);throw new Error("Invalid Transform!")}};Transform.mul=function(a,b){_ASSERT&&Transform.assert(a);if(Array.isArray(b)){var arr=[];for(var i=0;i=0);_ASSERT&&common.assert(Math.isFinite(def.linearDamping)&&def.linearDamping>=0);this.m_world=world;this.m_awakeFlag=def.awake;this.m_autoSleepFlag=def.allowSleep;this.m_bulletFlag=def.bullet;this.m_fixedRotationFlag=def.fixedRotation;this.m_activeFlag=def.active;this.m_islandFlag=false;this.m_toiFlag=false;this.m_userData=def.userData;this.m_type=def.type;if(this.m_type==dynamicBody){this.m_mass=1;this.m_invMass=1}else{this.m_mass=0;this.m_invMass=0}this.m_I=0;this.m_invI=0;this.m_xf=Transform.identity();this.m_xf.p=Vec2.clone(def.position);this.m_xf.q.setAngle(def.angle);this.m_sweep=new Sweep;this.m_sweep.setTransform(this.m_xf);this.c_velocity=new Velocity;this.c_position=new Position;this.m_force=Vec2.zero();this.m_torque=0;this.m_linearVelocity=Vec2.clone(def.linearVelocity);this.m_angularVelocity=def.angularVelocity;this.m_linearDamping=def.linearDamping;this.m_angularDamping=def.angularDamping;this.m_gravityScale=def.gravityScale;this.m_sleepTime=0;this.m_jointList=null;this.m_contactList=null;this.m_fixtureList=null;this.m_prev=null;this.m_next=null;this.m_destroyed=false}Body.prototype._serialize=function(){var fixtures=[];for(var f=this.m_fixtureList;f;f=f.m_next){fixtures.push(f)}return{type:this.m_type,position:this.m_xf.p,angle:this.m_xf.q.getAngle(),linearVelocity:this.m_linearVelocity,angularVelocity:this.m_angularVelocity,fixtures:fixtures}};Body._deserialize=function(data,world,restore){var body=new Body(world,data);data.fixtures.forEach(function(data){var fixture=restore(Fixture,data,body);body._addFixture(fixture)});return body};Body.prototype.isWorldLocked=function(){return!!(this.m_world&&this.m_world.isLocked())};Body.prototype.getWorld=function(){return this.m_world};Body.prototype.getNext=function(){return this.m_next};Body.prototype.setUserData=function(data){this.m_userData=data};Body.prototype.getUserData=function(){return this.m_userData};Body.prototype.getFixtureList=function(){return this.m_fixtureList};Body.prototype.getJointList=function(){return this.m_jointList};Body.prototype.getContactList=function(){return this.m_contactList};Body.prototype.isStatic=function(){return this.m_type==staticBody};Body.prototype.isDynamic=function(){return this.m_type==dynamicBody};Body.prototype.isKinematic=function(){return this.m_type==kinematicBody};Body.prototype.setStatic=function(){this.setType(staticBody);return this};Body.prototype.setDynamic=function(){this.setType(dynamicBody);return this};Body.prototype.setKinematic=function(){this.setType(kinematicBody);return this};Body.prototype.getType=function(){return this.m_type};Body.prototype.setType=function(type){_ASSERT&&common.assert(type===staticBody||type===kinematicBody||type===dynamicBody);_ASSERT&&common.assert(this.isWorldLocked()==false);if(this.isWorldLocked()==true){return}if(this.m_type==type){return}this.m_type=type;this.resetMassData();if(this.m_type==staticBody){this.m_linearVelocity.setZero();this.m_angularVelocity=0;this.m_sweep.forward();this.synchronizeFixtures()}this.setAwake(true);this.m_force.setZero();this.m_torque=0;var ce=this.m_contactList;while(ce){var ce0=ce;ce=ce.next;this.m_world.destroyContact(ce0.contact)}this.m_contactList=null;var broadPhase=this.m_world.m_broadPhase;for(var f=this.m_fixtureList;f;f=f.m_next){var proxyCount=f.m_proxyCount;for(var i=0;i0){this.setAwake(true)}this.m_linearVelocity.set(v)};Body.prototype.getAngularVelocity=function(){return this.m_angularVelocity};Body.prototype.setAngularVelocity=function(w){if(this.m_type==staticBody){return}if(w*w>0){this.setAwake(true)}this.m_angularVelocity=w};Body.prototype.getLinearDamping=function(){return this.m_linearDamping};Body.prototype.setLinearDamping=function(linearDamping){this.m_linearDamping=linearDamping};Body.prototype.getAngularDamping=function(){return this.m_angularDamping};Body.prototype.setAngularDamping=function(angularDamping){this.m_angularDamping=angularDamping};Body.prototype.getGravityScale=function(){return this.m_gravityScale};Body.prototype.setGravityScale=function(scale){this.m_gravityScale=scale};Body.prototype.getMass=function(){return this.m_mass};Body.prototype.getInertia=function(){return this.m_I+this.m_mass*Vec2.dot(this.m_sweep.localCenter,this.m_sweep.localCenter)};function MassData(){this.mass=0;this.center=Vec2.zero();this.I=0}Body.prototype.getMassData=function(data){data.mass=this.m_mass;data.I=this.getInertia();data.center.set(this.m_sweep.localCenter)};Body.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.isStatic()||this.isKinematic()){this.m_sweep.c0.set(this.m_xf.p);this.m_sweep.c.set(this.m_xf.p);this.m_sweep.a0=this.m_sweep.a;return}_ASSERT&&common.assert(this.isDynamic());var localCenter=Vec2.zero();for(var f=this.m_fixtureList;f;f=f.m_next){if(f.m_density==0){continue}var massData=new MassData;f.getMassData(massData);this.m_mass+=massData.mass;localCenter.addMul(massData.mass,massData.center);this.m_I+=massData.I}if(this.m_mass>0){this.m_invMass=1/this.m_mass;localCenter.mul(this.m_invMass)}else{this.m_mass=1;this.m_invMass=1}if(this.m_I>0&&this.m_fixedRotationFlag==false){this.m_I-=this.m_mass*Vec2.dot(localCenter,localCenter);_ASSERT&&common.assert(this.m_I>0);this.m_invI=1/this.m_I}else{this.m_I=0;this.m_invI=0}var oldCenter=Vec2.clone(this.m_sweep.c);this.m_sweep.setLocalCenter(localCenter,this.m_xf);this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity,Vec2.sub(this.m_sweep.c,oldCenter)))};Body.prototype.setMassData=function(massData){_ASSERT&&common.assert(this.isWorldLocked()==false);if(this.isWorldLocked()==true){return}if(this.m_type!=dynamicBody){return}this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_mass=massData.mass;if(this.m_mass<=0){this.m_mass=1}this.m_invMass=1/this.m_mass;if(massData.I>0&&this.m_fixedRotationFlag==false){this.m_I=massData.I-this.m_mass*Vec2.dot(massData.center,massData.center);_ASSERT&&common.assert(this.m_I>0);this.m_invI=1/this.m_I}var oldCenter=Vec2.clone(this.m_sweep.c);this.m_sweep.setLocalCenter(massData.center,this.m_xf);this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity,Vec2.sub(this.m_sweep.c,oldCenter)))};Body.prototype.applyForce=function(force,point,wake){if(this.m_type!=dynamicBody){return}if(wake&&this.m_awakeFlag==false){this.setAwake(true)}if(this.m_awakeFlag){this.m_force.add(force);this.m_torque+=Vec2.cross(Vec2.sub(point,this.m_sweep.c),force)}};Body.prototype.applyForceToCenter=function(force,wake){if(this.m_type!=dynamicBody){return}if(wake&&this.m_awakeFlag==false){this.setAwake(true)}if(this.m_awakeFlag){this.m_force.add(force)}};Body.prototype.applyTorque=function(torque,wake){if(this.m_type!=dynamicBody){return}if(wake&&this.m_awakeFlag==false){this.setAwake(true)}if(this.m_awakeFlag){this.m_torque+=torque}};Body.prototype.applyLinearImpulse=function(impulse,point,wake){if(this.m_type!=dynamicBody){return}if(wake&&this.m_awakeFlag==false){this.setAwake(true)}if(this.m_awakeFlag){this.m_linearVelocity.addMul(this.m_invMass,impulse);this.m_angularVelocity+=this.m_invI*Vec2.cross(Vec2.sub(point,this.m_sweep.c),impulse)}};Body.prototype.applyAngularImpulse=function(impulse,wake){if(this.m_type!=dynamicBody){return}if(wake&&this.m_awakeFlag==false){this.setAwake(true)}if(this.m_awakeFlag){this.m_angularVelocity+=this.m_invI*impulse}};Body.prototype.shouldCollide=function(that){if(this.m_type!=dynamicBody&&that.m_type!=dynamicBody){return false}for(var jn=this.m_jointList;jn;jn=jn.next){if(jn.other==that){if(jn.joint.m_collideConnected==false){return false}}}return true};Body.prototype._addFixture=function(fixture){_ASSERT&&common.assert(this.isWorldLocked()==false);if(this.isWorldLocked()==true){return null}if(this.m_activeFlag){var broadPhase=this.m_world.m_broadPhase;fixture.createProxies(broadPhase,this.m_xf)}fixture.m_next=this.m_fixtureList;this.m_fixtureList=fixture;if(fixture.m_density>0){this.resetMassData()}this.m_world.m_newFixture=true;return fixture};Body.prototype.createFixture=function(shape,fixdef){_ASSERT&&common.assert(this.isWorldLocked()==false);if(this.isWorldLocked()==true){return null}var fixture=new Fixture(this,shape,fixdef);this._addFixture(fixture);return fixture};Body.prototype.destroyFixture=function(fixture){_ASSERT&&common.assert(this.isWorldLocked()==false);if(this.isWorldLocked()==true){return}_ASSERT&&common.assert(fixture.m_body==this);var found=false;if(this.m_fixtureList===fixture){this.m_fixtureList=fixture.m_next;found=true}else{var node=this.m_fixtureList;while(node!=null){if(node.m_next===fixture){node.m_next=fixture.m_next;found=true;break}node=node.m_next}}_ASSERT&&common.assert(found);var edge=this.m_contactList;while(edge){var c=edge.contact;edge=edge.next;var fixtureA=c.getFixtureA();var fixtureB=c.getFixtureB();if(fixture==fixtureA||fixture==fixtureB){this.m_world.destroyContact(c)}}if(this.m_activeFlag){var broadPhase=this.m_world.m_broadPhase;fixture.destroyProxies(broadPhase)}fixture.m_body=null;fixture.m_next=null;this.m_world.publish("remove-fixture",fixture);this.resetMassData()};Body.prototype.getWorldPoint=function(localPoint){return Transform.mulVec2(this.m_xf,localPoint)};Body.prototype.getWorldVector=function(localVector){return Rot.mulVec2(this.m_xf.q,localVector)};Body.prototype.getLocalPoint=function(worldPoint){return Transform.mulTVec2(this.m_xf,worldPoint)};Body.prototype.getLocalVector=function(worldVector){return Rot.mulTVec2(this.m_xf.q,worldVector)}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Sweep;var common=__webpack_require__(2);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var Rot=__webpack_require__(3);var Transform=__webpack_require__(5);function Sweep(c,a){_ASSERT&&common.assert(typeof c==="undefined");_ASSERT&&common.assert(typeof a==="undefined");this.localCenter=Vec2.zero();this.c=Vec2.zero();this.a=0;this.alpha0=0;this.c0=Vec2.zero();this.a0=0}Sweep.prototype.setTransform=function(xf){var c=Transform.mulVec2(xf,this.localCenter);this.c.set(c);this.c0.set(c);this.a=xf.q.getAngle();this.a0=xf.q.getAngle()};Sweep.prototype.setLocalCenter=function(localCenter,xf){this.localCenter.set(localCenter);var c=Transform.mulVec2(xf,this.localCenter);this.c.set(c);this.c0.set(c)};Sweep.prototype.getTransform=function(xf,beta){beta=typeof beta==="undefined"?0:beta;xf.q.setAngle((1-beta)*this.a0+beta*this.a);xf.p.setCombine(1-beta,this.c0,beta,this.c);xf.p.sub(Rot.mulVec2(xf.q,this.localCenter))};Sweep.prototype.advance=function(alpha){_ASSERT&&common.assert(this.alpha0<1);var beta=(alpha-this.alpha0)/(1-this.alpha0);this.c0.setCombine(beta,this.c,1-beta,this.c0);this.a0=beta*this.a+(1-beta)*this.a0;this.alpha0=alpha};Sweep.prototype.forward=function(){this.a0=this.a;this.c0.set(this.c)};Sweep.prototype.normalize=function(){var a0=Math.mod(this.a0,-Math.PI,+Math.PI);this.a-=this.a0-a0;this.a0=a0};Sweep.prototype.clone=function(){var clone=new Sweep;clone.localCenter.set(this.localCenter);clone.alpha0=this.alpha0;clone.a0=this.a0;clone.a=this.a;clone.c0.set(this.c0);clone.c.set(this.c);return clone};Sweep.prototype.set=function(that){this.localCenter.set(that.localCenter);this.alpha0=that.alpha0;this.a0=that.a0;this.a=that.a;this.c0.set(that.c0);this.c.set(that.c)}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Mat22;var common=__webpack_require__(2);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);function Mat22(a,b,c,d){if(typeof a==="object"&&a!==null){this.ex=Vec2.clone(a);this.ey=Vec2.clone(b)}else if(typeof a==="number"){this.ex=Vec2.neo(a,c);this.ey=Vec2.neo(b,d)}else{this.ex=Vec2.zero();this.ey=Vec2.zero()}}Mat22.prototype.toString=function(){return JSON.stringify(this)};Mat22.isValid=function(o){return o&&Vec2.isValid(o.ex)&&Vec2.isValid(o.ey)};Mat22.assert=function(o){if(!_ASSERT)return;if(!Mat22.isValid(o)){_DEBUG&&common.debug(o);throw new Error("Invalid Mat22!")}};Mat22.prototype.set=function(a,b,c,d){if(typeof a==="number"&&typeof b==="number"&&typeof c==="number"&&typeof d==="number"){this.ex.set(a,c);this.ey.set(b,d)}else if(typeof a==="object"&&typeof b==="object"){this.ex.set(a);this.ey.set(b)}else if(typeof a==="object"){_ASSERT&&Mat22.assert(a);this.ex.set(a.ex);this.ey.set(a.ey)}else{_ASSERT&&common.assert(false)}};Mat22.prototype.setIdentity=function(){this.ex.x=1;this.ey.x=0;this.ex.y=0;this.ey.y=1};Mat22.prototype.setZero=function(){this.ex.x=0;this.ey.x=0;this.ex.y=0;this.ey.y=0};Mat22.prototype.getInverse=function(){var a=this.ex.x;var b=this.ey.x;var c=this.ex.y;var d=this.ey.y;var det=a*d-b*c;if(det!=0){det=1/det}var imx=new Mat22;imx.ex.x=det*d;imx.ey.x=-det*b;imx.ex.y=-det*c;imx.ey.y=det*a;return imx};Mat22.prototype.solve=function(v){_ASSERT&&Vec2.assert(v);var a=this.ex.x;var b=this.ey.x;var c=this.ex.y;var d=this.ey.y;var det=a*d-b*c;if(det!=0){det=1/det}var w=Vec2.zero();w.x=det*(d*v.x-b*v.y);w.y=det*(a*v.y-c*v.x);return w};Mat22.mul=function(mx,v){if(v&&"x"in v&&"y"in v){_ASSERT&&Vec2.assert(v);var x=mx.ex.x*v.x+mx.ey.x*v.y;var y=mx.ex.y*v.x+mx.ey.y*v.y;return Vec2.neo(x,y)}else if(v&&"ex"in v&&"ey"in v){_ASSERT&&Mat22.assert(v);var a=mx.ex.x*v.ex.x+mx.ey.x*v.ex.y;var b=mx.ex.x*v.ey.x+mx.ey.x*v.ey.y;var c=mx.ex.y*v.ex.x+mx.ey.y*v.ex.y;var d=mx.ex.y*v.ey.x+mx.ey.y*v.ey.y;return new Mat22(a,b,c,d)}_ASSERT&&common.assert(false)};Mat22.mulVec2=function(mx,v){_ASSERT&&Vec2.assert(v);var x=mx.ex.x*v.x+mx.ey.x*v.y;var y=mx.ex.y*v.x+mx.ey.y*v.y;return Vec2.neo(x,y)};Mat22.mulMat22=function(mx,v){_ASSERT&&Mat22.assert(v);var a=mx.ex.x*v.ex.x+mx.ey.x*v.ex.y;var b=mx.ex.x*v.ey.x+mx.ey.x*v.ey.y;var c=mx.ex.y*v.ex.x+mx.ey.y*v.ex.y;var d=mx.ex.y*v.ey.x+mx.ey.y*v.ey.y;return new Mat22(a,b,c,d);_ASSERT&&common.assert(false)};Mat22.mulT=function(mx,v){if(v&&"x"in v&&"y"in v){_ASSERT&&Vec2.assert(v);return Vec2.neo(Vec2.dot(v,mx.ex),Vec2.dot(v,mx.ey))}else if(v&&"ex"in v&&"ey"in v){_ASSERT&&Mat22.assert(v);var c1=Vec2.neo(Vec2.dot(mx.ex,v.ex),Vec2.dot(mx.ey,v.ex));var c2=Vec2.neo(Vec2.dot(mx.ex,v.ey),Vec2.dot(mx.ey,v.ey));return new Mat22(c1,c2)}_ASSERT&&common.assert(false)};Mat22.mulTVec2=function(mx,v){_ASSERT&&Mat22.assert(mx);_ASSERT&&Vec2.assert(v);return Vec2.neo(Vec2.dot(v,mx.ex),Vec2.dot(v,mx.ey))};Mat22.mulTMat22=function(mx,v){_ASSERT&&Mat22.assert(mx);_ASSERT&&Mat22.assert(v);var c1=Vec2.neo(Vec2.dot(mx.ex,v.ex),Vec2.dot(mx.ey,v.ex));var c2=Vec2.neo(Vec2.dot(mx.ex,v.ey),Vec2.dot(mx.ey,v.ey));return new Mat22(c1,c2)};Mat22.abs=function(mx){_ASSERT&&Mat22.assert(mx);return new Mat22(Vec2.abs(mx.ex),Vec2.abs(mx.ey))};Mat22.add=function(mx1,mx2){_ASSERT&&Mat22.assert(mx1);_ASSERT&&Mat22.assert(mx2);return new Mat22(Vec2.add(mx1.ex,mx2.ex),Vec2.add(mx1.ey,mx2.ey))}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Vec3;var common=__webpack_require__(2);var Math=__webpack_require__(1);function Vec3(x,y,z){if(!(this instanceof Vec3)){return new Vec3(x,y,z)}if(typeof x==="undefined"){this.x=0,this.y=0,this.z=0}else if(typeof x==="object"){this.x=x.x,this.y=x.y,this.z=x.z}else{this.x=x,this.y=y,this.z=z}_ASSERT&&Vec3.assert(this)}Vec3.prototype._serialize=function(){return{x:this.x,y:this.y,z:this.z}};Vec3._deserialize=function(data){var obj=Object.create(Vec3.prototype);obj.x=data.x;obj.y=data.y;obj.z=data.z;return obj};Vec3.neo=function(x,y,z){var obj=Object.create(Vec3.prototype);obj.x=x;obj.y=y;obj.z=z;return obj};Vec3.clone=function(v){_ASSERT&&Vec3.assert(v);return Vec3.neo(v.x,v.y,v.z)};Vec3.prototype.toString=function(){return JSON.stringify(this)};Vec3.isValid=function(v){return v&&Math.isFinite(v.x)&&Math.isFinite(v.y)&&Math.isFinite(v.z)};Vec3.assert=function(o){if(!_ASSERT)return;if(!Vec3.isValid(o)){_DEBUG&&common.debug(o);throw new Error("Invalid Vec3!")}};Vec3.prototype.setZero=function(){this.x=0;this.y=0;this.z=0;return this};Vec3.prototype.set=function(x,y,z){this.x=x;this.y=y;this.z=z;return this};Vec3.prototype.add=function(w){this.x+=w.x;this.y+=w.y;this.z+=w.z;return this};Vec3.prototype.sub=function(w){this.x-=w.x;this.y-=w.y;this.z-=w.z;return this};Vec3.prototype.mul=function(m){this.x*=m;this.y*=m;this.z*=m;return this};Vec3.areEqual=function(v,w){_ASSERT&&Vec3.assert(v);_ASSERT&&Vec3.assert(w);return v==w||typeof v==="object"&&v!==null&&typeof w==="object"&&w!==null&&v.x===w.x&&v.y===w.y&&v.z===w.z};Vec3.dot=function(v,w){return v.x*w.x+v.y*w.y+v.z*w.z};Vec3.cross=function(v,w){return new Vec3(v.y*w.z-v.z*w.y,v.z*w.x-v.x*w.z,v.x*w.y-v.y*w.x)};Vec3.add=function(v,w){return new Vec3(v.x+w.x,v.y+w.y,v.z+w.z)};Vec3.sub=function(v,w){return new Vec3(v.x-w.x,v.y-w.y,v.z-w.z)};Vec3.mul=function(v,m){return new Vec3(m*v.x,m*v.y,m*v.z)};Vec3.prototype.neg=function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this};Vec3.neg=function(v){return new Vec3(-v.x,-v.y,-v.z)}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Joint;var common=__webpack_require__(2);function JointEdge(){this.other=null;this.joint=null;this.prev=null;this.next=null}var DEFAULTS={userData:null,collideConnected:false};function Joint(def,bodyA,bodyB){bodyA=def.bodyA||bodyA;bodyB=def.bodyB||bodyB;_ASSERT&&common.assert(bodyA);_ASSERT&&common.assert(bodyB);_ASSERT&&common.assert(bodyA!=bodyB);this.m_type="unknown-joint";this.m_bodyA=bodyA;this.m_bodyB=bodyB;this.m_index=0;this.m_collideConnected=!!def.collideConnected;this.m_prev=null;this.m_next=null;this.m_edgeA=new JointEdge;this.m_edgeB=new JointEdge;this.m_islandFlag=false;this.m_userData=def.userData}Joint.TYPES={};Joint._deserialize=function(data,context,restore){var clazz=Joint.TYPES[data.type];return clazz&&restore(clazz,data)};Joint.prototype.isActive=function(){return this.m_bodyA.isActive()&&this.m_bodyB.isActive()};Joint.prototype.getType=function(){return this.m_type};Joint.prototype.getBodyA=function(){return this.m_bodyA};Joint.prototype.getBodyB=function(){return this.m_bodyB};Joint.prototype.getNext=function(){return this.m_next};Joint.prototype.getUserData=function(){return this.m_userData};Joint.prototype.setUserData=function(data){this.m_userData=data};Joint.prototype.getCollideConnected=function(){return this.m_collideConnected};Joint.prototype.getAnchorA=function(){};Joint.prototype.getAnchorB=function(){};Joint.prototype.getReactionForce=function(inv_dt){};Joint.prototype.getReactionTorque=function(inv_dt){};Joint.prototype.shiftOrigin=function(newOrigin){};Joint.prototype.initVelocityConstraints=function(step){};Joint.prototype.solveVelocityConstraints=function(step){};Joint.prototype.solvePositionConstraints=function(step){}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Velocity;var Vec2=__webpack_require__(0);function Velocity(){this.v=Vec2.zero();this.w=0}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Position;var Vec2=__webpack_require__(0);var Rot=__webpack_require__(3);function Position(){this.c=Vec2.zero();this.a=0}Position.prototype.getTransform=function(xf,p){xf.q.set(this.a);xf.p.set(Vec2.sub(this.c,Rot.mulVec2(xf.q,p)));return xf}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Mat33;var common=__webpack_require__(2);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var Vec3=__webpack_require__(11);function Mat33(a,b,c){if(typeof a==="object"&&a!==null){this.ex=Vec3.clone(a);this.ey=Vec3.clone(b);this.ez=Vec3.clone(c)}else{this.ex=Vec3();this.ey=Vec3();this.ez=Vec3()}}Mat33.prototype.toString=function(){return JSON.stringify(this)};Mat33.isValid=function(o){return o&&Vec3.isValid(o.ex)&&Vec3.isValid(o.ey)&&Vec3.isValid(o.ez)};Mat33.assert=function(o){if(!_ASSERT)return;if(!Mat33.isValid(o)){_DEBUG&&common.debug(o);throw new Error("Invalid Mat33!")}};Mat33.prototype.setZero=function(){this.ex.setZero();this.ey.setZero();this.ez.setZero();return this};Mat33.prototype.solve33=function(v){var det=Vec3.dot(this.ex,Vec3.cross(this.ey,this.ez));if(det!=0){det=1/det}var r=new Vec3;r.x=det*Vec3.dot(v,Vec3.cross(this.ey,this.ez));r.y=det*Vec3.dot(this.ex,Vec3.cross(v,this.ez));r.z=det*Vec3.dot(this.ex,Vec3.cross(this.ey,v));return r};Mat33.prototype.solve22=function(v){var a11=this.ex.x;var a12=this.ey.x;var a21=this.ex.y;var a22=this.ey.y;var det=a11*a22-a12*a21;if(det!=0){det=1/det}var r=Vec2.zero();r.x=det*(a22*v.x-a12*v.y);r.y=det*(a11*v.y-a21*v.x);return r};Mat33.prototype.getInverse22=function(M){var a=this.ex.x;var b=this.ey.x;var c=this.ex.y;var d=this.ey.y;var det=a*d-b*c;if(det!=0){det=1/det}M.ex.x=det*d;M.ey.x=-det*b;M.ex.z=0;M.ex.y=-det*c;M.ey.y=det*a;M.ey.z=0;M.ez.x=0;M.ez.y=0;M.ez.z=0};Mat33.prototype.getSymInverse33=function(M){var det=Vec3.dot(this.ex,Vec3.cross(this.ey,this.ez));if(det!=0){det=1/det}var a11=this.ex.x;var a12=this.ey.x;var a13=this.ez.x;var a22=this.ey.y;var a23=this.ez.y;var a33=this.ez.z;M.ex.x=det*(a22*a33-a23*a23);M.ex.y=det*(a13*a23-a12*a33);M.ex.z=det*(a12*a23-a13*a22);M.ey.x=M.ex.y;M.ey.y=det*(a11*a33-a13*a13);M.ey.z=det*(a13*a12-a11*a23);M.ez.x=M.ex.z;M.ez.y=M.ey.z;M.ez.z=det*(a11*a22-a12*a12)};Mat33.mul=function(a,b){_ASSERT&&Mat33.assert(a);if(b&&"z"in b&&"y"in b&&"x"in b){_ASSERT&&Vec3.assert(b);var x=a.ex.x*b.x+a.ey.x*b.y+a.ez.x*b.z;var y=a.ex.y*b.x+a.ey.y*b.y+a.ez.y*b.z;var z=a.ex.z*b.x+a.ey.z*b.y+a.ez.z*b.z;return new Vec3(x,y,z)}else if(b&&"y"in b&&"x"in b){_ASSERT&&Vec2.assert(b);var x=a.ex.x*b.x+a.ey.x*b.y;var y=a.ex.y*b.x+a.ey.y*b.y;return Vec2.neo(x,y)}_ASSERT&&common.assert(false)};Mat33.mulVec3=function(a,b){_ASSERT&&Mat33.assert(a);_ASSERT&&Vec3.assert(b);var x=a.ex.x*b.x+a.ey.x*b.y+a.ez.x*b.z;var y=a.ex.y*b.x+a.ey.y*b.y+a.ez.y*b.z;var z=a.ex.z*b.x+a.ey.z*b.y+a.ez.z*b.z;return new Vec3(x,y,z)};Mat33.mulVec2=function(a,b){_ASSERT&&Mat33.assert(a);_ASSERT&&Vec2.assert(b);var x=a.ex.x*b.x+a.ey.x*b.y;var y=a.ex.y*b.x+a.ey.y*b.y;return Vec2.neo(x,y)};Mat33.add=function(a,b){_ASSERT&&Mat33.assert(a);_ASSERT&&Mat33.assert(b);return new Mat33(Vec3.add(a.ex,b.ex),Vec3.add(a.ey,b.ey),Vec3.add(a.ez,b.ez))}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Shape;var Math=__webpack_require__(1);function Shape(){this.m_type;this.m_radius}Shape.prototype._reset=function(){};Shape.prototype._serialize=function(){return{}};Shape.TYPES={};Shape._deserialize=function(data,context,restore){var clazz=Shape.TYPES[data.type];return clazz&&restore(clazz,data)};Shape.isValid=function(shape){return!!shape};Shape.prototype.getRadius=function(){return this.m_radius};Shape.prototype.getType=function(){return this.m_type};Shape.prototype._clone=function(){};Shape.prototype.getChildCount=function(){};Shape.prototype.testPoint=function(xf,p){};Shape.prototype.rayCast=function(output,input,transform,childIndex){};Shape.prototype.computeAABB=function(aabb,xf,childIndex){};Shape.prototype.computeMass=function(massData,density){};Shape.prototype.computeDistanceProxy=function(proxy){}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;var Settings=__webpack_require__(4);var common=__webpack_require__(2);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);module.exports=AABB;function AABB(lower,upper){if(!(this instanceof AABB)){return new AABB(lower,upper)}this.lowerBound=Vec2.zero();this.upperBound=Vec2.zero();if(typeof lower==="object"){this.lowerBound.set(lower)}if(typeof upper==="object"){this.upperBound.set(upper)}else if(typeof lower==="object"){this.upperBound.set(lower)}}AABB.prototype.isValid=function(){return AABB.isValid(this)};AABB.isValid=function(aabb){var d=Vec2.sub(aabb.upperBound,aabb.lowerBound);var valid=d.x>=0&&d.y>=0&&Vec2.isValid(aabb.lowerBound)&&Vec2.isValid(aabb.upperBound);return valid};AABB.assert=function(o){if(!_ASSERT)return;if(!AABB.isValid(o)){_DEBUG&&common.debug(o);throw new Error("Invalid AABB!")}};AABB.prototype.getCenter=function(){return Vec2.neo((this.lowerBound.x+this.upperBound.x)*0.5,(this.lowerBound.y+this.upperBound.y)*0.5)};AABB.prototype.getExtents=function(){return Vec2.neo((this.upperBound.x-this.lowerBound.x)*0.5,(this.upperBound.y-this.lowerBound.y)*0.5)};AABB.prototype.getPerimeter=function(){return 2*(this.upperBound.x-this.lowerBound.x+this.upperBound.y-this.lowerBound.y)};AABB.prototype.combine=function(a,b){b=b||this;var lowerA=a.lowerBound;var upperA=a.upperBound;var lowerB=b.lowerBound;var upperB=b.upperBound;var lowerX=Math.min(lowerA.x,lowerB.x);var lowerY=Math.min(lowerA.y,lowerB.y);var upperX=Math.max(upperB.x,upperA.x);var upperY=Math.max(upperB.y,upperA.y);this.lowerBound.set(lowerX,lowerY);this.upperBound.set(upperX,upperY)};AABB.prototype.combinePoints=function(a,b){this.lowerBound.set(Math.min(a.x,b.x),Math.min(a.y,b.y));this.upperBound.set(Math.max(a.x,b.x),Math.max(a.y,b.y))};AABB.prototype.set=function(aabb){this.lowerBound.set(aabb.lowerBound.x,aabb.lowerBound.y);this.upperBound.set(aabb.upperBound.x,aabb.upperBound.y)};AABB.prototype.contains=function(aabb){var result=true;result=result&&this.lowerBound.x<=aabb.lowerBound.x;result=result&&this.lowerBound.y<=aabb.lowerBound.y;result=result&&aabb.upperBound.x<=this.upperBound.x;result=result&&aabb.upperBound.y<=this.upperBound.y;return result};AABB.prototype.extend=function(value){AABB.extend(this,value);return this};AABB.extend=function(aabb,value){aabb.lowerBound.x-=value;aabb.lowerBound.y-=value;aabb.upperBound.x+=value;aabb.upperBound.y+=value};AABB.testOverlap=function(a,b){var d1x=b.lowerBound.x-a.upperBound.x;var d2x=a.lowerBound.x-b.upperBound.x;var d1y=b.lowerBound.y-a.upperBound.y;var d2y=a.lowerBound.y-b.upperBound.y;if(d1x>0||d1y>0||d2x>0||d2y>0){return false}return true};AABB.areEqual=function(a,b){return Vec2.areEqual(a.lowerBound,b.lowerBound)&&Vec2.areEqual(a.upperBound,b.upperBound)};AABB.diff=function(a,b){var wD=Math.max(0,Math.min(a.upperBound.x,b.upperBound.x)-Math.max(b.lowerBound.x,a.lowerBound.x));var hD=Math.max(0,Math.min(a.upperBound.y,b.upperBound.y)-Math.max(b.lowerBound.y,a.lowerBound.y));var wA=a.upperBound.x-a.lowerBound.x;var hA=a.upperBound.y-a.lowerBound.y;var wB=b.upperBound.x-b.lowerBound.x;var hB=b.upperBound.y-b.lowerBound.y;return wA*hA+wB*hB-wD*hD};AABB.prototype.rayCast=function(output,input){var tmin=-Infinity;var tmax=Infinity;var p=input.p1;var d=Vec2.sub(input.p2,input.p1);var absD=Vec2.abs(d);var normal=Vec2.zero();for(var f="x";f!==null;f=f==="x"?"y":null){if(absD.xt2){var temp=t1;t1=t2,t2=temp;s=1}if(t1>tmin){normal.setZero();normal[f]=s;tmin=t1}tmax=Math.min(tmax,t2);if(tmin>tmax){return false}}}if(tmin<0||input.maxFraction0);this.v_invMassA=bodyA.m_invMass;this.v_invMassB=bodyB.m_invMass;this.v_invIA=bodyA.m_invI;this.v_invIB=bodyB.m_invI;this.v_friction=this.m_friction;this.v_restitution=this.m_restitution;this.v_tangentSpeed=this.m_tangentSpeed;this.v_pointCount=pointCount;this.v_K.setZero();this.v_normalMass.setZero();this.p_invMassA=bodyA.m_invMass;this.p_invMassB=bodyB.m_invMass;this.p_invIA=bodyA.m_invI;this.p_invIB=bodyB.m_invI;this.p_localCenterA=Vec2.clone(bodyA.m_sweep.localCenter);this.p_localCenterB=Vec2.clone(bodyB.m_sweep.localCenter);this.p_radiusA=shapeA.m_radius;this.p_radiusB=shapeB.m_radius;this.p_type=manifold.type;this.p_localNormal=Vec2.clone(manifold.localNormal);this.p_localPoint=Vec2.clone(manifold.localPoint);this.p_pointCount=pointCount;for(var j=0;j0;for(var i=0;i0?-C/K:0;var P=Vec2.mul(impulse,normal);cA.subMul(mA,P);aA-=iA*Vec2.cross(rA,P);cB.addMul(mB,P);aB+=iB*Vec2.cross(rB,P)}positionA.c.set(cA);positionA.a=aA;positionB.c.set(cB);positionB.a=aB;return minSeparation};function VelocityConstraintPoint(){this.rA=Vec2.zero();this.rB=Vec2.zero();this.normalImpulse=0;this.tangentImpulse=0;this.normalMass=0;this.tangentMass=0;this.velocityBias=0}Contact.prototype.initVelocityConstraint=function(step){var fixtureA=this.m_fixtureA;var fixtureB=this.m_fixtureB;var bodyA=fixtureA.getBody();var bodyB=fixtureB.getBody();var velocityA=bodyA.c_velocity;var velocityB=bodyB.c_velocity;var positionA=bodyA.c_position;var positionB=bodyB.c_position;var radiusA=this.p_radiusA;var radiusB=this.p_radiusB;var manifold=this.getManifold();var mA=this.v_invMassA;var mB=this.v_invMassB;var iA=this.v_invIA;var iB=this.v_invIB;var localCenterA=Vec2.clone(this.p_localCenterA);var localCenterB=Vec2.clone(this.p_localCenterB);var cA=Vec2.clone(positionA.c);var aA=positionA.a;var vA=Vec2.clone(velocityA.v);var wA=velocityA.w;var cB=Vec2.clone(positionB.c);var aB=positionB.a;var vB=Vec2.clone(velocityB.v);var wB=velocityB.w;_ASSERT&&common.assert(manifold.pointCount>0);var xfA=Transform.identity();var xfB=Transform.identity();xfA.q.set(aA);xfB.q.set(aB);xfA.p.setCombine(1,cA,-1,Rot.mulVec2(xfA.q,localCenterA));xfB.p.setCombine(1,cB,-1,Rot.mulVec2(xfB.q,localCenterB));var worldManifold=manifold.getWorldManifold(null,xfA,radiusA,xfB,radiusB);this.v_normal.set(worldManifold.normal);for(var j=0;j0?1/kNormal:0;var tangent=Vec2.cross(this.v_normal,1);var rtA=Vec2.cross(vcp.rA,tangent);var rtB=Vec2.cross(vcp.rB,tangent);var kTangent=mA+mB+iA*rtA*rtA+iB*rtB*rtB;vcp.tangentMass=kTangent>0?1/kTangent:0;vcp.velocityBias=0;var vRel=Vec2.dot(this.v_normal,vB)+Vec2.dot(this.v_normal,Vec2.cross(wB,vcp.rB))-Vec2.dot(this.v_normal,vA)-Vec2.dot(this.v_normal,Vec2.cross(wA,vcp.rA));if(vRel<-Settings.velocityThreshold){vcp.velocityBias=-this.v_restitution*vRel}}if(this.v_pointCount==2&&step.blockSolve){var vcp1=this.v_points[0];var vcp2=this.v_points[1];var rn1A=Vec2.cross(vcp1.rA,this.v_normal);var rn1B=Vec2.cross(vcp1.rB,this.v_normal);var rn2A=Vec2.cross(vcp2.rA,this.v_normal);var rn2B=Vec2.cross(vcp2.rB,this.v_normal);var k11=mA+mB+iA*rn1A*rn1A+iB*rn1B*rn1B;var k22=mA+mB+iA*rn2A*rn2A+iB*rn2B*rn2B;var k12=mA+mB+iA*rn1A*rn2A+iB*rn1B*rn2B;var k_maxConditionNumber=1000;if(k11*k11=0&&a.y>=0);var dv1=Vec2.zero().add(vB).add(Vec2.cross(wB,vcp1.rB)).sub(vA).sub(Vec2.cross(wA,vcp1.rA));var dv2=Vec2.zero().add(vB).add(Vec2.cross(wB,vcp2.rB)).sub(vA).sub(Vec2.cross(wA,vcp2.rA));var vn1=Vec2.dot(dv1,normal);var vn2=Vec2.dot(dv2,normal);var b=Vec2.neo(vn1-vcp1.velocityBias,vn2-vcp2.velocityBias);b.sub(Mat22.mulVec2(this.v_K,a));var k_errorTol=1e-3;for(;;){var x=Mat22.mulVec2(this.v_normalMass,b).neg();if(x.x>=0&&x.y>=0){var d=Vec2.sub(x,a);var P1=Vec2.mul(d.x,normal);var P2=Vec2.mul(d.y,normal);vA.subCombine(mA,P1,mA,P2);wA-=iA*(Vec2.cross(vcp1.rA,P1)+Vec2.cross(vcp2.rA,P2));vB.addCombine(mB,P1,mB,P2);wB+=iB*(Vec2.cross(vcp1.rB,P1)+Vec2.cross(vcp2.rB,P2));vcp1.normalImpulse=x.x;vcp2.normalImpulse=x.y;if(DEBUG_SOLVER){dv1=vB+Vec2.cross(wB,vcp1.rB)-vA-Vec2.cross(wA,vcp1.rA);dv2=vB+Vec2.cross(wB,vcp2.rB)-vA-Vec2.cross(wA,vcp2.rA);vn1=Dot(dv1,normal);vn2=Dot(dv2,normal);_ASSERT&&common.assert(Abs(vn1-vcp1.velocityBias)=0&&vn2>=0){var d=Vec2.sub(x,a);var P1=Vec2.mul(d.x,normal);var P2=Vec2.mul(d.y,normal);vA.subCombine(mA,P1,mA,P2);wA-=iA*(Vec2.cross(vcp1.rA,P1)+Vec2.cross(vcp2.rA,P2));vB.addCombine(mB,P1,mB,P2);wB+=iB*(Vec2.cross(vcp1.rB,P1)+Vec2.cross(vcp2.rB,P2));vcp1.normalImpulse=x.x;vcp2.normalImpulse=x.y;if(DEBUG_SOLVER){var dv1B=Vec2.add(vB,Vec2.cross(wB,vcp1.rB));var dv1A=Vec2.add(vA,Vec2.cross(wA,vcp1.rA));var dv1=Vec2.sub(dv1B,dv1A);vn1=Vec2.dot(dv1,normal);_ASSERT&&common.assert(Math.abs(vn1-vcp1.velocityBias)=0&&vn1>=0){var d=Vec2.sub(x,a);var P1=Vec2.mul(d.x,normal);var P2=Vec2.mul(d.y,normal);vA.subCombine(mA,P1,mA,P2);wA-=iA*(Vec2.cross(vcp1.rA,P1)+Vec2.cross(vcp2.rA,P2));vB.addCombine(mB,P1,mB,P2);wB+=iB*(Vec2.cross(vcp1.rB,P1)+Vec2.cross(vcp2.rB,P2));vcp1.normalImpulse=x.x;vcp2.normalImpulse=x.y;if(DEBUG_SOLVER){var dv2B=Vec2.add(vB,Vec2.cross(wB,vcp2.rB));var dv2A=Vec2.add(vA,Vec2.cross(wA,vcp2.rA));var dv1=Vec2.sub(dv2B,dv2A);vn2=Vec2.dot(dv2,normal);_ASSERT&&common.assert(Math.abs(vn2-vcp2.velocityBias)=0&&vn2>=0){var d=Vec2.sub(x,a);var P1=Vec2.mul(d.x,normal);var P2=Vec2.mul(d.y,normal);vA.subCombine(mA,P1,mA,P2);wA-=iA*(Vec2.cross(vcp1.rA,P1)+Vec2.cross(vcp2.rA,P2));vB.addCombine(mB,P1,mB,P2);wB+=iB*(Vec2.cross(vcp1.rB,P1)+Vec2.cross(vcp2.rB,P2));vcp1.normalImpulse=x.x;vcp2.normalImpulse=x.y;break}break}}velocityA.v.set(vA);velocityA.w=wA;velocityB.v.set(vB);velocityB.w=wB};function mixFriction(friction1,friction2){return Math.sqrt(friction1*friction2)}function mixRestitution(restitution1,restitution2){return restitution1>restitution2?restitution1:restitution2}var s_registers=[];Contact.addType=function(type1,type2,callback){s_registers[type1]=s_registers[type1]||{};s_registers[type1][type2]=callback};Contact.create=function(fixtureA,indexA,fixtureB,indexB){var typeA=fixtureA.getType();var typeB=fixtureB.getType();var contact,evaluateFcn;if(evaluateFcn=s_registers[typeA]&&s_registers[typeA][typeB]){contact=new Contact(fixtureA,indexA,fixtureB,indexB,evaluateFcn)}else if(evaluateFcn=s_registers[typeB]&&s_registers[typeB][typeA]){contact=new Contact(fixtureB,indexB,fixtureA,indexA,evaluateFcn)}else{return null}fixtureA=contact.getFixtureA();fixtureB=contact.getFixtureB();indexA=contact.getChildIndexA();indexB=contact.getChildIndexB();var bodyA=fixtureA.getBody();var bodyB=fixtureB.getBody();contact.m_nodeA.contact=contact;contact.m_nodeA.other=bodyB;contact.m_nodeA.prev=null;contact.m_nodeA.next=bodyA.m_contactList;if(bodyA.m_contactList!=null){bodyA.m_contactList.prev=contact.m_nodeA}bodyA.m_contactList=contact.m_nodeA;contact.m_nodeB.contact=contact;contact.m_nodeB.other=bodyA;contact.m_nodeB.prev=null;contact.m_nodeB.next=bodyB.m_contactList;if(bodyB.m_contactList!=null){bodyB.m_contactList.prev=contact.m_nodeB}bodyB.m_contactList=contact.m_nodeB;if(fixtureA.isSensor()==false&&fixtureB.isSensor()==false){bodyA.setAwake(true);bodyB.setAwake(true)}return contact};Contact.destroy=function(contact,listener){var fixtureA=contact.m_fixtureA;var fixtureB=contact.m_fixtureB;var bodyA=fixtureA.getBody();var bodyB=fixtureB.getBody();if(contact.isTouching()){listener.endContact(contact)}if(contact.m_nodeA.prev){contact.m_nodeA.prev.next=contact.m_nodeA.next}if(contact.m_nodeA.next){contact.m_nodeA.next.prev=contact.m_nodeA.prev}if(contact.m_nodeA==bodyA.m_contactList){bodyA.m_contactList=contact.m_nodeA.next}if(contact.m_nodeB.prev){contact.m_nodeB.prev.next=contact.m_nodeB.next}if(contact.m_nodeB.next){contact.m_nodeB.next.prev=contact.m_nodeB.prev}if(contact.m_nodeB==bodyB.m_contactList){bodyB.m_contactList=contact.m_nodeB.next}if(contact.m_manifold.pointCount>0&&fixtureA.isSensor()==false&&fixtureB.isSensor()==false){bodyA.setAwake(true);bodyB.setAwake(true)}var typeA=fixtureA.getType();var typeB=fixtureB.getType();var destroyFcn=s_registers[typeA][typeB].destroyFcn;if(typeof destroyFcn==="function"){destroyFcn(contact)}}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;var common=__webpack_require__(2);var Vec2=__webpack_require__(0);var Transform=__webpack_require__(5);var Math=__webpack_require__(1);var Rot=__webpack_require__(3);module.exports=Manifold;module.exports.clipSegmentToLine=clipSegmentToLine;module.exports.clipVertex=ClipVertex;module.exports.getPointStates=getPointStates;module.exports.PointState=PointState;Manifold.e_circles=0;Manifold.e_faceA=1;Manifold.e_faceB=2;Manifold.e_vertex=0;Manifold.e_face=1;function Manifold(){this.type;this.localNormal=Vec2.zero();this.localPoint=Vec2.zero();this.points=[new ManifoldPoint,new ManifoldPoint];this.pointCount=0}function ManifoldPoint(){this.localPoint=Vec2.zero();this.normalImpulse=0;this.tangentImpulse=0;this.id=new ContactID}function ContactID(){this.cf=new ContactFeature}Object.defineProperty(ContactID.prototype,"key",{get:function(){return this.cf.indexA+this.cf.indexB*4+this.cf.typeA*16+this.cf.typeB*64},enumerable:true,configurable:true});ContactID.prototype.set=function(o){this.cf.set(o.cf)};function ContactFeature(){this.indexA;this.indexB;this.typeA;this.typeB}ContactFeature.prototype.set=function(o){this.indexA=o.indexA;this.indexB=o.indexB;this.typeA=o.typeA;this.typeB=o.typeB};function WorldManifold(){this.normal;this.points=[];this.separations=[]}Manifold.prototype.getWorldManifold=function(wm,xfA,radiusA,xfB,radiusB){if(this.pointCount==0){return}wm=wm||new WorldManifold;var normal=wm.normal;var points=wm.points;var separations=wm.separations;switch(this.type){case Manifold.e_circles:normal=Vec2.neo(1,0);var pointA=Transform.mulVec2(xfA,this.localPoint);var pointB=Transform.mulVec2(xfB,this.points[0].localPoint);var dist=Vec2.sub(pointB,pointA);if(Vec2.lengthSquared(dist)>Math.EPSILON*Math.EPSILON){normal.set(dist);normal.normalize()}var cA=pointA.clone().addMul(radiusA,normal);var cB=pointB.clone().addMul(-radiusB,normal);points[0]=Vec2.mid(cA,cB);separations[0]=Vec2.dot(Vec2.sub(cB,cA),normal);points.length=1;separations.length=1;break;case Manifold.e_faceA:normal=Rot.mulVec2(xfA.q,this.localNormal);var planePoint=Transform.mulVec2(xfA,this.localPoint);for(var i=0;iVec2._deserialize(v));var shape=new PolygonShape(vertices);return shape};PolygonShape.prototype.getVertex=function(index){_ASSERT&&common.assert(index>=0&&index=3);var c=Vec2.zero();var area=0;var pRef=Vec2.zero();if(false){var i}var inv3=1/3;for(var i=0;iMath.EPSILON);c.mul(1/area);return c}PolygonShape.prototype._reset=function(){this._set(this.m_vertices)};PolygonShape.prototype._set=function(vertices){_ASSERT&&common.assert(vertices.length>=3&&vertices.length<=Settings.maxPolygonVertices);if(vertices.length<3){this._setAsBox(1,1);return}var n=Math.min(vertices.length,Settings.maxPolygonVertices);var ps=[];for(var i=0;ix0||x===x0&&ps[i].yr.lengthSquared()){ie=j}}++m;ih=ie;if(ie===i0){break}}if(m<3){_ASSERT&&common.assert(false);this._setAsBox(1,1);return}this.m_count=m;this.m_vertices=[];for(var i=0;iMath.EPSILON*Math.EPSILON);this.m_normals[i]=Vec2.cross(edge,1);this.m_normals[i].normalize()}this.m_centroid=ComputeCentroid(this.m_vertices,m)};PolygonShape.prototype._setAsBox=function(hx,hy,center,angle){this.m_vertices[0]=Vec2.neo(hx,-hy);this.m_vertices[1]=Vec2.neo(hx,hy);this.m_vertices[2]=Vec2.neo(-hx,hy);this.m_vertices[3]=Vec2.neo(-hx,-hy);this.m_normals[0]=Vec2.neo(1,0);this.m_normals[1]=Vec2.neo(0,1);this.m_normals[2]=Vec2.neo(-1,0);this.m_normals[3]=Vec2.neo(0,-1);this.m_count=4;if(Vec2.isValid(center)){angle=angle||0;this.m_centroid.set(center);var xf=Transform.identity();xf.p.set(center);xf.q.set(angle);for(var i=0;i0){return false}}return true};PolygonShape.prototype.rayCast=function(output,input,xf,childIndex){var p1=Rot.mulTVec2(xf.q,Vec2.sub(input.p1,xf.p));var p2=Rot.mulTVec2(xf.q,Vec2.sub(input.p2,xf.p));var d=Vec2.sub(p2,p1);var lower=0;var upper=input.maxFraction;var index=-1;for(var i=0;i0&&numerator=0&&lower<=input.maxFraction);if(index>=0){output.fraction=lower;output.normal=Rot.mulVec2(xf.q,this.m_normals[index]);return true}return false};PolygonShape.prototype.computeAABB=function(aabb,xf,childIndex){var minX=Infinity;var minY=Infinity;var maxX=-Infinity;var maxY=-Infinity;for(var i=0;i=3);var center=Vec2.zero();var area=0;var I=0;var s=Vec2.zero();for(var i=0;iMath.EPSILON);center.mul(1/area);massData.center.setCombine(1,center,1,s);massData.I=density*I;massData.I+=massData.mass*(Vec2.dot(massData.center,massData.center)-Vec2.dot(center,center))};PolygonShape.prototype.validate=function(){for(var i=0;i=distanceSqr1){}distanceSqr1=distanceSqr2;var d=simplex.getSearchDirection();if(d.lengthSquared()rA+rB&&output.distance>Math.EPSILON){output.distance-=rA+rB;var normal=Vec2.sub(output.pointB,output.pointA);normal.normalize();output.pointA.addMul(rA,normal);output.pointB.subMul(rB,normal)}else{var p=Vec2.mid(output.pointA,output.pointB);output.pointA.set(p);output.pointB.set(p);output.distance=0}}}function DistanceProxy(){this.m_buffer=[];this.m_vertices=[];this.m_count=0;this.m_radius=0}DistanceProxy.prototype.getVertexCount=function(){return this.m_count};DistanceProxy.prototype.getVertex=function(index){_ASSERT&&common.assert(index>=0&&indexbestValue){bestIndex=i;bestValue=value}}return bestIndex};DistanceProxy.prototype.getSupportVertex=function(d){return this.m_vertices[this.getSupport(d)]};DistanceProxy.prototype.set=function(shape,index){_ASSERT&&common.assert(typeof shape.computeDistanceProxy==="function");shape.computeDistanceProxy(this,index)};function SimplexVertex(){this.indexA;this.indexB;this.wA=Vec2.zero();this.wB=Vec2.zero();this.w=Vec2.zero();this.a}SimplexVertex.prototype.set=function(v){this.indexA=v.indexA;this.indexB=v.indexB;this.wA=Vec2.clone(v.wA);this.wB=Vec2.clone(v.wB);this.w=Vec2.clone(v.w);this.a=v.a};function Simplex(){this.m_v1=new SimplexVertex;this.m_v2=new SimplexVertex;this.m_v3=new SimplexVertex;this.m_v=[this.m_v1,this.m_v2,this.m_v3];this.m_count}Simplex.prototype.print=function(){if(this.m_count==3){return[`+${this.m_count}`,this.m_v1.a,this.m_v1.wA.x,this.m_v1.wA.y,this.m_v1.wB.x,this.m_v1.wB.y,this.m_v2.a,this.m_v2.wA.x,this.m_v2.wA.y,this.m_v2.wB.x,this.m_v2.wB.y,this.m_v3.a,this.m_v3.wA.x,this.m_v3.wA.y,this.m_v3.wB.x,this.m_v3.wB.y].toString()}else if(this.m_count==2){return[`+${this.m_count}`,this.m_v1.a,this.m_v1.wA.x,this.m_v1.wA.y,this.m_v1.wB.x,this.m_v1.wB.y,this.m_v2.a,this.m_v2.wA.x,this.m_v2.wA.y,this.m_v2.wB.x,this.m_v2.wB.y].toString()}else if(this.m_count==1){return[`+${this.m_count}`,this.m_v1.a,this.m_v1.wA.x,this.m_v1.wA.y,this.m_v1.wB.x,this.m_v1.wB.y].toString()}else{return`+${this.m_count}`}};Simplex.prototype.readCache=function(cache,proxyA,transformA,proxyB,transformB){_ASSERT&&common.assert(cache.count<=3);this.m_count=cache.count;for(var i=0;i1){var metric1=cache.metric;var metric2=this.getMetric();if(metric2<0.5*metric1||2*metric10){return Vec2.cross(1,e12)}else{return Vec2.cross(e12,1)}}default:_ASSERT&&common.assert(false);return Vec2.zero();}};Simplex.prototype.getClosestPoint=function(){switch(this.m_count){case 0:_ASSERT&&common.assert(false);return Vec2.zero();case 1:return Vec2.clone(this.m_v1.w);case 2:return Vec2.combine(this.m_v1.a,this.m_v1.w,this.m_v2.a,this.m_v2.w);case 3:return Vec2.zero();default:_ASSERT&&common.assert(false);return Vec2.zero();}};Simplex.prototype.getWitnessPoints=function(pA,pB){switch(this.m_count){case 0:_ASSERT&&common.assert(false);break;case 1:pA.set(this.m_v1.wA);pB.set(this.m_v1.wB);break;case 2:pA.setCombine(this.m_v1.a,this.m_v1.wA,this.m_v2.a,this.m_v2.wA);pB.setCombine(this.m_v1.a,this.m_v1.wB,this.m_v2.a,this.m_v2.wB);break;case 3:pA.setCombine(this.m_v1.a,this.m_v1.wA,this.m_v2.a,this.m_v2.wA);pA.addMul(this.m_v3.a,this.m_v3.wA);pB.set(pA);break;default:_ASSERT&&common.assert(false);break;}};Simplex.prototype.getMetric=function(){switch(this.m_count){case 0:_ASSERT&&common.assert(false);return 0;case 1:return 0;case 2:return Vec2.distance(this.m_v1.w,this.m_v2.w);case 3:return Vec2.cross(Vec2.sub(this.m_v2.w,this.m_v1.w),Vec2.sub(this.m_v3.w,this.m_v1.w));default:_ASSERT&&common.assert(false);return 0;}};Simplex.prototype.solve=function(){switch(this.m_count){case 1:break;case 2:this.solve2();break;case 3:this.solve3();break;default:_ASSERT&&common.assert(false);}};Simplex.prototype.solve2=function(){var w1=this.m_v1.w;var w2=this.m_v2.w;var e12=Vec2.sub(w2,w1);var d12_2=-Vec2.dot(w1,e12);if(d12_2<=0){this.m_v1.a=1;this.m_count=1;return}var d12_1=Vec2.dot(w2,e12);if(d12_1<=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};Simplex.prototype.solve3=function(){var w1=this.m_v1.w;var w2=this.m_v2.w;var w3=this.m_v3.w;var e12=Vec2.sub(w2,w1);var w1e12=Vec2.dot(w1,e12);var w2e12=Vec2.dot(w2,e12);var d12_1=w2e12;var d12_2=-w1e12;var e13=Vec2.sub(w3,w1);var w1e13=Vec2.dot(w1,e13);var w3e13=Vec2.dot(w3,e13);var d13_1=w3e13;var d13_2=-w1e13;var e23=Vec2.sub(w3,w2);var w2e23=Vec2.dot(w2,e23);var w3e23=Vec2.dot(w3,e23);var d23_1=w3e23;var d23_2=-w2e23;var n123=Vec2.cross(e12,e13);var d123_1=n123*Vec2.cross(w2,w3);var d123_2=n123*Vec2.cross(w3,w1);var d123_3=n123*Vec2.cross(w1,w2);if(d12_2<=0&&d13_2<=0){this.m_v1.a=1;this.m_count=1;return}if(d12_1>0&&d12_2>0&&d123_3<=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>0&&d13_2>0&&d123_2<=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<=0&&d23_2<=0){this.m_v2.a=1;this.m_count=1;this.m_v1.set(this.m_v2);return}if(d13_1<=0&&d23_1<=0){this.m_v3.a=1;this.m_count=1;this.m_v1.set(this.m_v3);return}if(d23_1>0&&d23_2>0&&d123_1<=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};Distance.testOverlap=function(shapeA,indexA,shapeB,indexB,xfA,xfB){var input=new DistanceInput;input.proxyA.set(shapeA,indexA);input.proxyB.set(shapeB,indexB);input.transformA=xfA;input.transformB=xfB;input.useRadii=true;var cache=new SimplexCache;var output=new DistanceOutput;Distance(output,cache,input);return output.distance<10*Math.EPSILON}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=CircleShape;var common=__webpack_require__(2);var create=__webpack_require__(6);var options=__webpack_require__(7);var Math=__webpack_require__(1);var Transform=__webpack_require__(5);var Rot=__webpack_require__(3);var Vec2=__webpack_require__(0);var AABB=__webpack_require__(17);var Settings=__webpack_require__(4);var Shape=__webpack_require__(16);CircleShape._super=Shape;CircleShape.prototype=create(CircleShape._super.prototype);CircleShape.TYPE="circle";Shape.TYPES[CircleShape.TYPE]=CircleShape;function CircleShape(a,b){if(!(this instanceof CircleShape)){return new CircleShape(a,b)}CircleShape._super.call(this);this.m_type=CircleShape.TYPE;this.m_p=Vec2.zero();this.m_radius=1;if(typeof a==="object"&&Vec2.isValid(a)){this.m_p.set(a);if(typeof b==="number"){this.m_radius=b}}else if(typeof a==="number"){this.m_radius=a}}CircleShape.prototype._serialize=function(){return{type:this.m_type,p:this.m_p,radius:this.m_radius}};CircleShape._deserialize=function(data){return new CircleShape(data.p,data.radius)};CircleShape.prototype.getRadius=function(){return this.m_radius};CircleShape.prototype.getCenter=function(){return this.m_p};CircleShape.prototype.getVertex=function(index){_ASSERT&&common.assert(index==0);return this.m_p};CircleShape.prototype.getVertexCount=function(index){return 1};CircleShape.prototype._clone=function(){var clone=new CircleShape;clone.m_type=this.m_type;clone.m_radius=this.m_radius;clone.m_p=this.m_p.clone();return clone};CircleShape.prototype.getChildCount=function(){return 1};CircleShape.prototype.testPoint=function(xf,p){var center=Vec2.add(xf.p,Rot.mulVec2(xf.q,this.m_p));var d=Vec2.sub(p,center);return Vec2.dot(d,d)<=this.m_radius*this.m_radius};CircleShape.prototype.rayCast=function(output,input,xf,childIndex){var position=Vec2.add(xf.p,Rot.mulVec2(xf.q,this.m_p));var s=Vec2.sub(input.p1,position);var b=Vec2.dot(s,s)-this.m_radius*this.m_radius;var r=Vec2.sub(input.p2,input.p1);var c=Vec2.dot(s,r);var rr=Vec2.dot(r,r);var sigma=c*c-rr*b;if(sigma<0||rr=0&&a<=input.maxFraction*rr){a/=rr;output.fraction=a;output.normal=Vec2.add(s,Vec2.mul(a,r));output.normal.normalize();return true}return false};CircleShape.prototype.computeAABB=function(aabb,xf,childIndex){var p=Vec2.add(xf.p,Rot.mulVec2(xf.q,this.m_p));aabb.lowerBound.set(p.x-this.m_radius,p.y-this.m_radius);aabb.upperBound.set(p.x+this.m_radius,p.y+this.m_radius)};CircleShape.prototype.computeMass=function(massData,density){massData.mass=density*Math.PI*this.m_radius*this.m_radius;massData.center=this.m_p;massData.I=massData.mass*(0.5*this.m_radius*this.m_radius+Vec2.dot(this.m_p,this.m_p))};CircleShape.prototype.computeDistanceProxy=function(proxy){proxy.m_vertices.push(this.m_p);proxy.m_count=1;proxy.m_radius=this.m_radius}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=EdgeShape;var create=__webpack_require__(6);var options=__webpack_require__(7);var Settings=__webpack_require__(4);var Shape=__webpack_require__(16);var Math=__webpack_require__(1);var Transform=__webpack_require__(5);var Rot=__webpack_require__(3);var Vec2=__webpack_require__(0);var AABB=__webpack_require__(17);EdgeShape._super=Shape;EdgeShape.prototype=create(EdgeShape._super.prototype);EdgeShape.TYPE="edge";Shape.TYPES[EdgeShape.TYPE]=EdgeShape;function EdgeShape(v1,v2){if(!(this instanceof EdgeShape)){return new EdgeShape(v1,v2)}EdgeShape._super.call(this);this.m_type=EdgeShape.TYPE;this.m_radius=Settings.polygonRadius;this.m_vertex1=v1?Vec2.clone(v1):Vec2.zero();this.m_vertex2=v2?Vec2.clone(v2):Vec2.zero();this.m_vertex0=Vec2.zero();this.m_vertex3=Vec2.zero();this.m_hasVertex0=false;this.m_hasVertex3=false}EdgeShape.prototype._serialize=function(){return{type:this.m_type,vertex1:this.m_vertex1,vertex2:this.m_vertex2,vertex0:this.m_vertex0,vertex3:this.m_vertex3,hasVertex0:this.m_hasVertex0,hasVertex3:this.m_hasVertex3}};EdgeShape._deserialize=function(data){var shape=new EdgeShape(data.vertex1,data.vertex2);if(shape.hasVertex0){shape.setPrev(data.vertex0)}if(shape.hasVertex3){shape.setNext(data.vertex3)}return shape};EdgeShape.prototype.setNext=function(v3){if(v3){this.m_vertex3.set(v3);this.m_hasVertex3=true}else{this.m_vertex3.setZero();this.m_hasVertex3=false}return this};EdgeShape.prototype.setPrev=function(v0){if(v0){this.m_vertex0.set(v0);this.m_hasVertex0=true}else{this.m_vertex0.setZero();this.m_hasVertex0=false}return this};EdgeShape.prototype._set=function(v1,v2){this.m_vertex1.set(v1);this.m_vertex2.set(v2);this.m_hasVertex0=false;this.m_hasVertex3=false;return this};EdgeShape.prototype._clone=function(){var clone=new EdgeShape;clone.m_type=this.m_type;clone.m_radius=this.m_radius;clone.m_vertex1.set(this.m_vertex1);clone.m_vertex2.set(this.m_vertex2);clone.m_vertex0.set(this.m_vertex0);clone.m_vertex3.set(this.m_vertex3);clone.m_hasVertex0=this.m_hasVertex0;clone.m_hasVertex3=this.m_hasVertex3;return clone};EdgeShape.prototype.getChildCount=function(){return 1};EdgeShape.prototype.testPoint=function(xf,p){return false};EdgeShape.prototype.rayCast=function(output,input,xf,childIndex){var p1=Rot.mulTVec2(xf.q,Vec2.sub(input.p1,xf.p));var p2=Rot.mulTVec2(xf.q,Vec2.sub(input.p2,xf.p));var d=Vec2.sub(p2,p1);var v1=this.m_vertex1;var v2=this.m_vertex2;var e=Vec2.sub(v2,v1);var normal=Vec2.neo(e.y,-e.x);normal.normalize();var numerator=Vec2.dot(normal,Vec2.sub(v1,p1));var denominator=Vec2.dot(normal,d);if(denominator==0){return false}var t=numerator/denominator;if(t<0||input.maxFraction1){return false}output.fraction=t;if(numerator>0){output.normal=Rot.mulVec2(xf.q,normal).neg()}else{output.normal=Rot.mulVec2(xf.q,normal)}return true};EdgeShape.prototype.computeAABB=function(aabb,xf,childIndex){var v1=Transform.mulVec2(xf,this.m_vertex1);var v2=Transform.mulVec2(xf,this.m_vertex2);aabb.combinePoints(v1,v2);aabb.extend(this.m_radius)};EdgeShape.prototype.computeMass=function(massData,density){massData.mass=0;massData.center.setCombine(0.5,this.m_vertex1,0.5,this.m_vertex2);massData.I=0};EdgeShape.prototype.computeDistanceProxy=function(proxy){proxy.m_vertices.push(this.m_vertex1);proxy.m_vertices.push(this.m_vertex2);proxy.m_count=2;proxy.m_radius=this.m_radius}},,,function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;exports.toString=function(newline){newline=typeof newline==="string"?newline:"\n";var string="";for(var name in this){if(typeof this[name]!=="function"&&typeof this[name]!=="object"){string+=`${name}: ${this[name]}${newline}`}}return string}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=ChainShape;var common=__webpack_require__(2);var create=__webpack_require__(6);var options=__webpack_require__(7);var Math=__webpack_require__(1);var Transform=__webpack_require__(5);var Rot=__webpack_require__(3);var Vec2=__webpack_require__(0);var AABB=__webpack_require__(17);var Settings=__webpack_require__(4);var Shape=__webpack_require__(16);var EdgeShape=__webpack_require__(24);ChainShape._super=Shape;ChainShape.prototype=create(ChainShape._super.prototype);ChainShape.TYPE="chain";Shape.TYPES[ChainShape.TYPE]=ChainShape;function ChainShape(vertices,loop){if(!(this instanceof ChainShape)){return new ChainShape(vertices,loop)}ChainShape._super.call(this);this.m_type=ChainShape.TYPE;this.m_radius=Settings.polygonRadius;this.m_vertices=[];this.m_count=0;this.m_prevVertex=null;this.m_nextVertex=null;this.m_hasPrevVertex=false;this.m_hasNextVertex=false;this.m_isLoop=loop;if(vertices&&vertices.length){if(loop){this._createLoop(vertices)}else{this._createChain(vertices)}}}ChainShape.prototype._serialize=function(){const data={type:this.m_type,vertices:this.m_vertices,isLoop:this.m_isLoop,hasPrevVertex:this.m_hasPrevVertex,hasNextVertex:this.m_hasNextVertex};if(this.m_prevVertex){data.prevVertex=this.m_prevVertex}if(this.m_nextVertex){data.nextVertex=this.m_nextVertex}return data};ChainShape._deserialize=function(data){var shape=new ChainShape(data.vertices.map(Vec2._deserialize),data.isLoop);if(data.prevVertex){shape._setPrevVertex(data.prevVertex)}if(data.nextVertex){shape._setNextVertex(data.nextVertex)}return shape};ChainShape.prototype._createLoop=function(vertices){_ASSERT&&common.assert(this.m_vertices.length==0&&this.m_count==0);_ASSERT&&common.assert(vertices.length>=3);for(var i=1;iSettings.linearSlopSquared)}this.m_vertices.length=0;this.m_count=vertices.length+1;for(var i=0;i=2);for(var i=1;iSettings.linearSlopSquared)}this.m_count=vertices.length;for(var i=0;i=0&&childIndex0){edge.m_vertex0=this.m_vertices[childIndex-1];edge.m_hasVertex0=true}else{edge.m_vertex0=this.m_prevVertex;edge.m_hasVertex0=this.m_hasPrevVertex}if(childIndex=0&&index<=this.m_count);if(index=0&&childIndex=0&&childIndex=0&&childIndex0);_ASSERT&&common.assert(this.isLocked()==false);if(this.isLocked()){return}if(b.m_destroyed){return false}var je=b.m_jointList;while(je){var je0=je;je=je.next;this.publish("remove-joint",je0.joint);this.destroyJoint(je0.joint);b.m_jointList=je}b.m_jointList=null;var ce=b.m_contactList;while(ce){var ce0=ce;ce=ce.next;this.destroyContact(ce0.contact);b.m_contactList=ce}b.m_contactList=null;var f=b.m_fixtureList;while(f){var f0=f;f=f.m_next;this.publish("remove-fixture",f0);f0.destroyProxies(this.m_broadPhase);b.m_fixtureList=f}b.m_fixtureList=null;if(b.m_prev){b.m_prev.m_next=b.m_next}if(b.m_next){b.m_next.m_prev=b.m_prev}if(b==this.m_bodyList){this.m_bodyList=b.m_next}b.m_destroyed=true;--this.m_bodyCount;this.publish("remove-body",b);return true};World.prototype.createJoint=function(joint){_ASSERT&&common.assert(!!joint.m_bodyA);_ASSERT&&common.assert(!!joint.m_bodyB);_ASSERT&&common.assert(this.isLocked()==false);if(this.isLocked()){return null}joint.m_prev=null;joint.m_next=this.m_jointList;if(this.m_jointList){this.m_jointList.m_prev=joint}this.m_jointList=joint;++this.m_jointCount;joint.m_edgeA.joint=joint;joint.m_edgeA.other=joint.m_bodyB;joint.m_edgeA.prev=null;joint.m_edgeA.next=joint.m_bodyA.m_jointList;if(joint.m_bodyA.m_jointList)joint.m_bodyA.m_jointList.prev=joint.m_edgeA;joint.m_bodyA.m_jointList=joint.m_edgeA;joint.m_edgeB.joint=joint;joint.m_edgeB.other=joint.m_bodyA;joint.m_edgeB.prev=null;joint.m_edgeB.next=joint.m_bodyB.m_jointList;if(joint.m_bodyB.m_jointList)joint.m_bodyB.m_jointList.prev=joint.m_edgeB;joint.m_bodyB.m_jointList=joint.m_edgeB;if(joint.m_collideConnected==false){for(var edge=joint.m_bodyB.getContactList();edge;edge=edge.next){if(edge.other==joint.m_bodyA){edge.contact.flagForFiltering()}}}return joint};World.prototype.destroyJoint=function(joint){_ASSERT&&common.assert(this.isLocked()==false);if(this.isLocked()){return}if(joint.m_prev){joint.m_prev.m_next=joint.m_next}if(joint.m_next){joint.m_next.m_prev=joint.m_prev}if(joint==this.m_jointList){this.m_jointList=joint.m_next}var bodyA=joint.m_bodyA;var bodyB=joint.m_bodyB;bodyA.setAwake(true);bodyB.setAwake(true);if(joint.m_edgeA.prev){joint.m_edgeA.prev.next=joint.m_edgeA.next}if(joint.m_edgeA.next){joint.m_edgeA.next.prev=joint.m_edgeA.prev}if(joint.m_edgeA==bodyA.m_jointList){bodyA.m_jointList=joint.m_edgeA.next}joint.m_edgeA.prev=null;joint.m_edgeA.next=null;if(joint.m_edgeB.prev){joint.m_edgeB.prev.next=joint.m_edgeB.next}if(joint.m_edgeB.next){joint.m_edgeB.next.prev=joint.m_edgeB.prev}if(joint.m_edgeB==bodyB.m_jointList){bodyB.m_jointList=joint.m_edgeB.next}joint.m_edgeB.prev=null;joint.m_edgeB.next=null;_ASSERT&&common.assert(this.m_jointCount>0);--this.m_jointCount;if(joint.m_collideConnected==false){var edge=bodyB.getContactList();while(edge){if(edge.other==bodyA){edge.contact.flagForFiltering()}edge=edge.next}}this.publish("remove-joint",joint)};var s_step=new Solver.TimeStep;World.prototype.step=function(timeStep,velocityIterations,positionIterations){if((velocityIterations|0)!==velocityIterations){velocityIterations=0}velocityIterations=velocityIterations||this.m_velocityIterations;positionIterations=positionIterations||this.m_positionIterations;this.m_stepCount++;if(this.m_newFixture){this.findNewContacts();this.m_newFixture=false}this.m_locked=true;s_step.reset(timeStep);s_step.velocityIterations=velocityIterations;s_step.positionIterations=positionIterations;s_step.warmStarting=this.m_warmStarting;s_step.blockSolve=this.m_blockSolve;this.updateContacts();if(this.m_stepComplete&&timeStep>0){this.m_solver.solveWorld(s_step);for(var b=this.m_bodyList;b;b=b.getNext()){if(b.m_islandFlag==false){continue}if(b.isStatic()){continue}b.synchronizeFixtures()}this.findNewContacts()}if(this.m_continuousPhysics&&timeStep>0){this.m_solver.solveWorldTOI(s_step)}if(this.m_clearForces){this.clearForces()}this.m_locked=false};World.prototype.findNewContacts=function(){this.m_broadPhase.updatePairs(this.addPair)};World.prototype.createContact=function(proxyA,proxyB){var fixtureA=proxyA.fixture;var fixtureB=proxyB.fixture;var indexA=proxyA.childIndex;var indexB=proxyB.childIndex;var bodyA=fixtureA.getBody();var bodyB=fixtureB.getBody();if(bodyA==bodyB){return}var edge=bodyB.getContactList();while(edge){if(edge.other==bodyA){var fA=edge.contact.getFixtureA();var fB=edge.contact.getFixtureB();var iA=edge.contact.getChildIndexA();var iB=edge.contact.getChildIndexB();if(fA==fixtureA&&fB==fixtureB&&iA==indexA&&iB==indexB){return}if(fA==fixtureB&&fB==fixtureA&&iA==indexB&&iB==indexA){return}}edge=edge.next}if(bodyB.shouldCollide(bodyA)==false){return}if(fixtureB.shouldCollide(fixtureA)==false){return}var contact=Contact.create(fixtureA,indexA,fixtureB,indexB);if(contact==null){return}contact.m_prev=null;if(this.m_contactList!=null){contact.m_next=this.m_contactList;this.m_contactList.m_prev=contact}this.m_contactList=contact;++this.m_contactCount};World.prototype.updateContacts=function(){var c;var next_c=this.m_contactList;while(c=next_c){next_c=c.getNext();var fixtureA=c.getFixtureA();var fixtureB=c.getFixtureB();var indexA=c.getChildIndexA();var indexB=c.getChildIndexB();var bodyA=fixtureA.getBody();var bodyB=fixtureB.getBody();if(c.m_filterFlag){if(bodyB.shouldCollide(bodyA)==false){this.destroyContact(c);continue}if(fixtureB.shouldCollide(fixtureA)==false){this.destroyContact(c);continue}c.m_filterFlag=false}var activeA=bodyA.isAwake()&&!bodyA.isStatic();var activeB=bodyB.isAwake()&&!bodyB.isStatic();if(activeA==false&&activeB==false){continue}var proxyIdA=fixtureA.m_proxies[indexA].proxyId;var proxyIdB=fixtureB.m_proxies[indexB].proxyId;var overlap=this.m_broadPhase.testOverlap(proxyIdA,proxyIdB);if(overlap==false){this.destroyContact(c);continue}c.update(this)}};World.prototype.destroyContact=function(contact){Contact.destroy(contact,this);if(contact.m_prev){contact.m_prev.m_next=contact.m_next}if(contact.m_next){contact.m_next.m_prev=contact.m_prev}if(contact==this.m_contactList){this.m_contactList=contact.m_next}--this.m_contactCount};World.prototype._listeners=null;World.prototype.on=function(name,listener){if(typeof name!=="string"||typeof listener!=="function"){return this}if(!this._listeners){this._listeners={}}if(!this._listeners[name]){this._listeners[name]=[]}this._listeners[name].push(listener);return this};World.prototype.off=function(name,listener){if(typeof name!=="string"||typeof listener!=="function"){return this}var listeners=this._listeners&&this._listeners[name];if(!listeners||!listeners.length){return this}var index=listeners.indexOf(listener);if(index>=0){listeners.splice(index,1)}return this};World.prototype.publish=function(name,arg1,arg2,arg3){var listeners=this._listeners&&this._listeners[name];if(!listeners||!listeners.length){return 0}for(var l=0;l1){var F=C.child1;var G=C.child2;C.child1=A;C.parent=A.parent;A.parent=C;if(C.parent!=null){if(C.parent.child1==iA){C.parent.child1=C}else{C.parent.child2=C}}else{this.m_root=C}if(F.height>G.height){C.child2=F;A.child2=G;G.parent=A;A.aabb.combine(B.aabb,G.aabb);C.aabb.combine(A.aabb,F.aabb);A.height=1+Math.max(B.height,G.height);C.height=1+Math.max(A.height,F.height)}else{C.child2=G;A.child2=F;F.parent=A;A.aabb.combine(B.aabb,F.aabb);C.aabb.combine(A.aabb,G.aabb);A.height=1+Math.max(B.height,F.height);C.height=1+Math.max(A.height,G.height)}return C}if(balance<-1){var D=B.child1;var E=B.child2;B.child1=A;B.parent=A.parent;A.parent=B;if(B.parent!=null){if(B.parent.child1==A){B.parent.child1=B}else{B.parent.child2=B}}else{this.m_root=B}if(D.height>E.height){B.child2=D;A.child1=E;E.parent=A;A.aabb.combine(C.aabb,E.aabb);B.aabb.combine(A.aabb,D.aabb);A.height=1+Math.max(C.height,E.height);B.height=1+Math.max(A.height,D.height)}else{B.child2=E;A.child1=D;D.parent=A;A.aabb.combine(C.aabb,D.aabb);B.aabb.combine(A.aabb,E.aabb);A.height=1+Math.max(C.height,D.height);B.height=1+Math.max(A.height,E.height)}return B}return A};DynamicTree.prototype.getHeight=function(){if(this.m_root==null){return 0}return this.m_root.height};DynamicTree.prototype.getAreaRatio=function(){if(this.m_root==null){return 0}var root=this.m_root;var rootArea=root.aabb.getPerimeter();var totalArea=0;var node;var it=iteratorPool.allocate().preorder(this.m_root);while(node=it.next()){if(node.height<0){continue}totalArea+=node.aabb.getPerimeter()}iteratorPool.release(it);return totalArea/rootArea};DynamicTree.prototype.computeHeight=function(id){var node;if(typeof id!=="undefined"){node=this.m_nodes[id]}else{node=this.m_root}if(node.isLeaf()){return 0}var height1=this.computeHeight(node.child1.id);var height2=this.computeHeight(node.child2.id);return 1+Math.max(height1,height2)};DynamicTree.prototype.validateStructure=function(node){if(node==null){return}if(node==this.m_root){_ASSERT&&common.assert(node.parent==null)}var child1=node.child1;var child2=node.child2;if(node.isLeaf()){_ASSERT&&common.assert(child1==null);_ASSERT&&common.assert(child2==null);_ASSERT&&common.assert(node.height==0);return}_ASSERT&&common.assert(child1.parent==node);_ASSERT&&common.assert(child2.parent==node);this.validateStructure(child1);this.validateStructure(child2)};DynamicTree.prototype.validateMetrics=function(node){if(node==null){return}var child1=node.child1;var child2=node.child2;if(node.isLeaf()){_ASSERT&&common.assert(child1==null);_ASSERT&&common.assert(child2==null);_ASSERT&&common.assert(node.height==0);return}var height1=child1.height;var height2=child2.height;var height=1+Math.max(height1,height2);_ASSERT&&common.assert(node.height==height);var aabb=new AABB;aabb.combine(child1.aabb,child2.aabb);_ASSERT&&common.assert(AABB.areEqual(aabb,node.aabb));this.validateMetrics(child1);this.validateMetrics(child2)};DynamicTree.prototype.validate=function(){this.validateStructure(this.m_root);this.validateMetrics(this.m_root);_ASSERT&&common.assert(this.getHeight()==this.computeHeight())};DynamicTree.prototype.getMaxBalance=function(){var maxBalance=0;var node;var it=iteratorPool.allocate().preorder(this.m_root);while(node=it.next()){if(node.height<=1){continue}_ASSERT&&common.assert(node.isLeaf()==false);var balance=Math.abs(node.child2.height-node.child1.height);maxBalance=Math.max(maxBalance,balance)}iteratorPool.release(it);return maxBalance};DynamicTree.prototype.rebuildBottomUp=function(){var nodes=[];var count=0;var node;var it=iteratorPool.allocate().preorder(this.m_root);while(node=it.next()){if(node.height<0){continue}if(node.isLeaf()){node.parent=null;nodes[count]=node;++count}else{this.freeNode(node)}}iteratorPool.release(it);while(count>1){var minCost=Infinity;var iMin=-1;var jMin=-1;for(var i=0;i0){var node=stack.pop();if(node==null){continue}if(AABB.testOverlap(node.aabb,aabb)){if(node.isLeaf()){var proceed=queryCallback(node.id);if(proceed==false){return}}else{stack.push(node.child1);stack.push(node.child2)}}}stackPool.release(stack)};DynamicTree.prototype.rayCast=function(input,rayCastCallback){_ASSERT&&common.assert(typeof rayCastCallback==="function");var p1=input.p1;var p2=input.p2;var r=Vec2.sub(p2,p1);_ASSERT&&common.assert(r.lengthSquared()>0);r.normalize();var v=Vec2.cross(1,r);var abs_v=Vec2.abs(v);var maxFraction=input.maxFraction;var segmentAABB=new AABB;var t=Vec2.combine(1-maxFraction,p1,maxFraction,p2);segmentAABB.combinePoints(p1,t);var stack=stackPool.allocate();var subInput=inputPool.allocate();stack.push(this.m_root);while(stack.length>0){var node=stack.pop();if(node==null){continue}if(AABB.testOverlap(node.aabb,segmentAABB)==false){continue}var c=node.aabb.getCenter();var h=node.aabb.getExtents();var separation=Math.abs(Vec2.dot(v,Vec2.sub(p1,c)))-Vec2.dot(abs_v,h);if(separation>0){continue}if(node.isLeaf()){subInput.p1=Vec2.clone(input.p1);subInput.p2=Vec2.clone(input.p2);subInput.maxFraction=maxFraction;var value=rayCastCallback(subInput,node.id);if(value==0){return}if(value>0){maxFraction=value;t=Vec2.combine(1-maxFraction,p1,maxFraction,p2);segmentAABB.combinePoints(p1,t)}}else{stack.push(node.child1);stack.push(node.child2)}}stackPool.release(stack);inputPool.release(subInput)};var inputPool=new Pool({create:function(){return{}},release:function(stack){}});var stackPool=new Pool({create:function(){return[]},release:function(stack){stack.length=0}});var iteratorPool=new Pool({create:function(){return new Iterator},release:function(iterator){iterator.close()}});function Iterator(){var parents=[];var states=[];return{preorder:function(root){parents.length=0;parents.push(root);states.length=0;states.push(0);return this},next:function(){while(parents.length>0){var i=parents.length-1;var node=parents[i];if(states[i]===0){states[i]=1;return node}if(states[i]===1){states[i]=2;if(node.child1){parents.push(node.child1);states.push(1);return node.child1}}if(states[i]===2){states[i]=3;if(node.child2){parents.push(node.child2);states.push(1);return node.child2}}parents.pop();states.pop()}},close:function(){parents.length=0}}}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Fixture;var common=__webpack_require__(2);var options=__webpack_require__(7);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var AABB=__webpack_require__(17);var Shape=__webpack_require__(16);var FixtureDef={userData:null,friction:0.2,restitution:0,density:0,isSensor:false,filterGroupIndex:0,filterCategoryBits:1,filterMaskBits:65535};function FixtureProxy(fixture,childIndex){this.aabb=new AABB;this.fixture=fixture;this.childIndex=childIndex;this.proxyId}function Fixture(body,shape,def){if(shape.shape){def=shape;shape=shape.shape}else if(typeof def==="number"){def={density:def}}def=options(def,FixtureDef);this.m_body=body;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_density=def.density;this.m_isSensor=def.isSensor;this.m_filterGroupIndex=def.filterGroupIndex;this.m_filterCategoryBits=def.filterCategoryBits;this.m_filterMaskBits=def.filterMaskBits;this.m_shape=shape;this.m_next=null;this.m_proxies=[];this.m_proxyCount=0;var childCount=this.m_shape.getChildCount();for(var i=0;i=0);this.m_density=density};Fixture.prototype.getFriction=function(){return this.m_friction};Fixture.prototype.setFriction=function(friction){this.m_friction=friction};Fixture.prototype.getRestitution=function(){return this.m_restitution};Fixture.prototype.setRestitution=function(restitution){this.m_restitution=restitution};Fixture.prototype.testPoint=function(p){return this.m_shape.testPoint(this.m_body.getTransform(),p)};Fixture.prototype.rayCast=function(output,input,childIndex){return this.m_shape.rayCast(output,input,this.m_body.getTransform(),childIndex)};Fixture.prototype.getMassData=function(massData){this.m_shape.computeMass(massData,this.m_density)};Fixture.prototype.getAABB=function(childIndex){_ASSERT&&common.assert(childIndex>=0&&childIndex0}var collide=(that.m_filterMaskBits&this.m_filterCategoryBits)!=0&&(that.m_filterCategoryBits&this.m_filterMaskBits)!=0;return collide}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=TimeOfImpact;module.exports.Input=TOIInput;module.exports.Output=TOIOutput;var Settings=__webpack_require__(4);var common=__webpack_require__(2);var Timer=__webpack_require__(44);var stats=__webpack_require__(27);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var Vec3=__webpack_require__(11);var Mat22=__webpack_require__(10);var Mat33=__webpack_require__(15);var Rot=__webpack_require__(3);var Sweep=__webpack_require__(9);var Transform=__webpack_require__(5);var Velocity=__webpack_require__(13);var Position=__webpack_require__(14);var Distance=__webpack_require__(22);var DistanceInput=Distance.Input;var DistanceOutput=Distance.Output;var DistanceProxy=Distance.Proxy;var SimplexCache=Distance.Cache;function TOIInput(){this.proxyA=new DistanceProxy;this.proxyB=new DistanceProxy;this.sweepA=new Sweep;this.sweepB=new Sweep;this.tMax}TOIOutput.e_unknown=0;TOIOutput.e_failed=1;TOIOutput.e_overlapped=2;TOIOutput.e_touching=3;TOIOutput.e_separated=4;function TOIOutput(){this.state;this.t}stats.toiTime=0;stats.toiMaxTime=0;stats.toiCalls=0;stats.toiIters=0;stats.toiMaxIters=0;stats.toiRootIters=0;stats.toiMaxRootIters=0;function TimeOfImpact(output,input){var timer=Timer.now();++stats.toiCalls;output.state=TOIOutput.e_unknown;output.t=input.tMax;var proxyA=input.proxyA;var proxyB=input.proxyB;var sweepA=input.sweepA;var sweepB=input.sweepB;sweepA.normalize();sweepB.normalize();var tMax=input.tMax;var totalRadius=proxyA.m_radius+proxyB.m_radius;var target=Math.max(Settings.linearSlop,totalRadius-3*Settings.linearSlop);var tolerance=0.25*Settings.linearSlop;_ASSERT&&common.assert(target>tolerance);var t1=0;var k_maxIterations=Settings.maxTOIIterations;var iter=0;var cache=new SimplexCache;var distanceInput=new DistanceInput;distanceInput.proxyA=input.proxyA;distanceInput.proxyB=input.proxyB;distanceInput.useRadii=false;for(;;){var xfA=Transform.identity();var xfB=Transform.identity();sweepA.getTransform(xfA,t1);sweepB.getTransform(xfB,t1);distanceInput.transformA=xfA;distanceInput.transformB=xfB;var distanceOutput=new DistanceOutput;Distance(distanceOutput,cache,distanceInput);if(distanceOutput.distance<=0){output.state=TOIOutput.e_overlapped;output.t=0;break}if(distanceOutput.distancetarget+tolerance){output.state=TOIOutput.e_separated;output.t=tMax;done=true;break}if(s2>target-tolerance){t1=t2;break}var s1=fcn.evaluate(t1);var indexA=fcn.indexA;var indexB=fcn.indexB;if(s1target){a1=t;s1=s}else{a2=t;s2=s}if(rootIterCount==50){break}}stats.toiMaxRootIters=Math.max(stats.toiMaxRootIters,rootIterCount);++pushBackIter;if(pushBackIter==Settings.maxPolygonVertices){break}}++iter;++stats.toiIters;if(done){break}if(iter==k_maxIterations){output.state=TOIOutput.e_failed;output.t=t1;break}}stats.toiMaxIters=Math.max(stats.toiMaxIters,iter);var time=Timer.diff(timer);stats.toiMaxTime=Math.max(stats.toiMaxTime,time);stats.toiTime+=time}var e_points=1;var e_faceA=2;var e_faceB=3;function SeparationFunction(){this.m_proxyA=new DistanceProxy;this.m_proxyB=new DistanceProxy;this.m_sweepA;this.m_sweepB;this.indexA;this.indexB;this.m_type;this.m_localPoint=Vec2.zero();this.m_axis=Vec2.zero()}SeparationFunction.prototype.initialize=function(cache,proxyA,sweepA,proxyB,sweepB,t1){this.m_proxyA=proxyA;this.m_proxyB=proxyB;var count=cache.count;_ASSERT&&common.assert(count>0&&count<3);this.m_sweepA=sweepA;this.m_sweepB=sweepB;var xfA=Transform.identity();var xfB=Transform.identity();this.m_sweepA.getTransform(xfA,t1);this.m_sweepB.getTransform(xfB,t1);if(count==1){this.m_type=e_points;var localPointA=this.m_proxyA.getVertex(cache.indexA[0]);var localPointB=this.m_proxyB.getVertex(cache.indexB[0]);var pointA=Transform.mulVec2(xfA,localPointA);var pointB=Transform.mulVec2(xfB,localPointB);this.m_axis.setCombine(1,pointB,-1,pointA);var s=this.m_axis.normalize();return s}else if(cache.indexA[0]==cache.indexA[1]){this.m_type=e_faceB;var localPointB1=proxyB.getVertex(cache.indexB[0]);var localPointB2=proxyB.getVertex(cache.indexB[1]);this.m_axis=Vec2.cross(Vec2.sub(localPointB2,localPointB1),1);this.m_axis.normalize();var normal=Rot.mulVec2(xfB.q,this.m_axis);this.m_localPoint=Vec2.mid(localPointB1,localPointB2);var pointB=Transform.mulVec2(xfB,this.m_localPoint);var localPointA=proxyA.getVertex(cache.indexA[0]);var pointA=Transform.mulVec2(xfA,localPointA);var s=Vec2.dot(pointA,normal)-Vec2.dot(pointB,normal);if(s<0){this.m_axis=Vec2.neg(this.m_axis);s=-s}return s}else{this.m_type=e_faceA;var localPointA1=this.m_proxyA.getVertex(cache.indexA[0]);var localPointA2=this.m_proxyA.getVertex(cache.indexA[1]);this.m_axis=Vec2.cross(Vec2.sub(localPointA2,localPointA1),1);this.m_axis.normalize();var normal=Rot.mulVec2(xfA.q,this.m_axis);this.m_localPoint=Vec2.mid(localPointA1,localPointA2);var pointA=Transform.mulVec2(xfA,this.m_localPoint);var localPointB=this.m_proxyB.getVertex(cache.indexB[0]);var pointB=Transform.mulVec2(xfB,localPointB);var s=Vec2.dot(pointB,normal)-Vec2.dot(pointA,normal);if(s<0){this.m_axis=Vec2.neg(this.m_axis);s=-s}return s}};SeparationFunction.prototype.compute=function(find,t){var xfA=Transform.identity();var xfB=Transform.identity();this.m_sweepA.getTransform(xfA,t);this.m_sweepB.getTransform(xfB,t);switch(this.m_type){case e_points:{if(find){var axisA=Rot.mulTVec2(xfA.q,this.m_axis);var axisB=Rot.mulTVec2(xfB.q,Vec2.neg(this.m_axis));this.indexA=this.m_proxyA.getSupport(axisA);this.indexB=this.m_proxyB.getSupport(axisB)}var localPointA=this.m_proxyA.getVertex(this.indexA);var localPointB=this.m_proxyB.getVertex(this.indexB);var pointA=Transform.mulVec2(xfA,localPointA);var pointB=Transform.mulVec2(xfB,localPointB);var sep=Vec2.dot(pointB,this.m_axis)-Vec2.dot(pointA,this.m_axis);return sep}case e_faceA:{var normal=Rot.mulVec2(xfA.q,this.m_axis);var pointA=Transform.mulVec2(xfA,this.m_localPoint);if(find){var axisB=Rot.mulTVec2(xfB.q,Vec2.neg(normal));this.indexA=-1;this.indexB=this.m_proxyB.getSupport(axisB)}var localPointB=this.m_proxyB.getVertex(this.indexB);var pointB=Transform.mulVec2(xfB,localPointB);var sep=Vec2.dot(pointB,normal)-Vec2.dot(pointA,normal);return sep}case e_faceB:{var normal=Rot.mulVec2(xfB.q,this.m_axis);var pointB=Transform.mulVec2(xfB,this.m_localPoint);if(find){var axisA=Rot.mulTVec2(xfA.q,Vec2.neg(normal));this.indexB=-1;this.indexA=this.m_proxyA.getSupport(axisA)}var localPointA=this.m_proxyA.getVertex(this.indexA);var pointA=Transform.mulVec2(xfA,localPointA);var sep=Vec2.dot(pointA,normal)-Vec2.dot(pointB,normal);return sep}default:_ASSERT&&common.assert(false);if(find){this.indexA=-1;this.indexB=-1}return 0;}};SeparationFunction.prototype.findMinSeparation=function(t){return this.compute(true,t)};SeparationFunction.prototype.evaluate=function(t){return this.compute(false,t)}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=RevoluteJoint;var common=__webpack_require__(2);var options=__webpack_require__(7);var create=__webpack_require__(6);var Settings=__webpack_require__(4);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var Vec3=__webpack_require__(11);var Mat22=__webpack_require__(10);var Mat33=__webpack_require__(15);var Rot=__webpack_require__(3);var Sweep=__webpack_require__(9);var Transform=__webpack_require__(5);var Velocity=__webpack_require__(13);var Position=__webpack_require__(14);var Joint=__webpack_require__(12);var Body=__webpack_require__(8);var inactiveLimit=0;var atLowerLimit=1;var atUpperLimit=2;var equalLimits=3;RevoluteJoint.TYPE="revolute-joint";Joint.TYPES[RevoluteJoint.TYPE]=RevoluteJoint;RevoluteJoint._super=Joint;RevoluteJoint.prototype=create(RevoluteJoint._super.prototype);var DEFAULTS={lowerAngle:0,upperAngle:0,maxMotorTorque:0,motorSpeed:0,enableLimit:false,enableMotor:false};function RevoluteJoint(def,bodyA,bodyB,anchor){if(!(this instanceof RevoluteJoint)){return new RevoluteJoint(def,bodyA,bodyB,anchor)}def=options(def,DEFAULTS);Joint.call(this,def,bodyA,bodyB);bodyA=this.m_bodyA;bodyB=this.m_bodyB;this.m_type=RevoluteJoint.TYPE;this.m_localAnchorA=Vec2.clone(anchor?bodyA.getLocalPoint(anchor):def.localAnchorA||Vec2.zero());this.m_localAnchorB=Vec2.clone(anchor?bodyB.getLocalPoint(anchor):def.localAnchorB||Vec2.zero());this.m_referenceAngle=Math.isFinite(def.referenceAngle)?def.referenceAngle:bodyB.getAngle()-bodyA.getAngle();this.m_impulse=Vec3();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_rA;this.m_rB;this.m_localCenterA;this.m_localCenterB;this.m_invMassA;this.m_invMassB;this.m_invIA;this.m_invIB;this.m_mass=new Mat33;this.m_motorMass;this.m_limitState=inactiveLimit}RevoluteJoint.prototype._serialize=function(){return{type:this.m_type,bodyA:this.m_bodyA,bodyB:this.m_bodyB,collideConnected:this.m_collideConnected,lowerAngle:this.m_lowerAngle,upperAngle:this.m_upperAngle,maxMotorTorque:this.m_maxMotorTorque,motorSpeed:this.m_motorSpeed,enableLimit:this.m_enableLimit,enableMotor:this.m_enableMotor,localAnchorA:this.m_localAnchorA,localAnchorB:this.m_localAnchorB,referenceAngle:this.m_referenceAngle}};RevoluteJoint._deserialize=function(data,world,restore){data.bodyA=restore(Body,data.bodyA,world);data.bodyB=restore(Body,data.bodyB,world);var joint=new RevoluteJoint(data);return joint};RevoluteJoint.prototype._setAnchors=function(def){if(def.anchorA){this.m_localAnchorA.set(this.m_bodyA.getLocalPoint(def.anchorA))}else if(def.localAnchorA){this.m_localAnchorA.set(def.localAnchorA)}if(def.anchorB){this.m_localAnchorB.set(this.m_bodyB.getLocalPoint(def.anchorB))}else if(def.localAnchorB){this.m_localAnchorB.set(def.localAnchorB)}};RevoluteJoint.prototype.getLocalAnchorA=function(){return this.m_localAnchorA};RevoluteJoint.prototype.getLocalAnchorB=function(){return this.m_localAnchorB};RevoluteJoint.prototype.getReferenceAngle=function(){return this.m_referenceAngle};RevoluteJoint.prototype.getJointAngle=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;return bB.m_sweep.a-bA.m_sweep.a-this.m_referenceAngle};RevoluteJoint.prototype.getJointSpeed=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;return bB.m_angularVelocity-bA.m_angularVelocity};RevoluteJoint.prototype.isMotorEnabled=function(){return this.m_enableMotor};RevoluteJoint.prototype.enableMotor=function(flag){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_enableMotor=flag};RevoluteJoint.prototype.getMotorTorque=function(inv_dt){return inv_dt*this.m_motorImpulse};RevoluteJoint.prototype.setMotorSpeed=function(speed){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_motorSpeed=speed};RevoluteJoint.prototype.getMotorSpeed=function(){return this.m_motorSpeed};RevoluteJoint.prototype.setMaxMotorTorque=function(torque){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_maxMotorTorque=torque};RevoluteJoint.prototype.getMaxMotorTorque=function(){return this.m_maxMotorTorque};RevoluteJoint.prototype.isLimitEnabled=function(){return this.m_enableLimit};RevoluteJoint.prototype.enableLimit=function(flag){if(flag!=this.m_enableLimit){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_enableLimit=flag;this.m_impulse.z=0}};RevoluteJoint.prototype.getLowerLimit=function(){return this.m_lowerAngle};RevoluteJoint.prototype.getUpperLimit=function(){return this.m_upperAngle};RevoluteJoint.prototype.setLimits=function(lower,upper){_ASSERT&&common.assert(lower<=upper);if(lower!=this.m_lowerAngle||upper!=this.m_upperAngle){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_impulse.z=0;this.m_lowerAngle=lower;this.m_upperAngle=upper}};RevoluteJoint.prototype.getAnchorA=function(){return this.m_bodyA.getWorldPoint(this.m_localAnchorA)};RevoluteJoint.prototype.getAnchorB=function(){return this.m_bodyB.getWorldPoint(this.m_localAnchorB)};RevoluteJoint.prototype.getReactionForce=function(inv_dt){return Vec2.neo(this.m_impulse.x,this.m_impulse.y).mul(inv_dt)};RevoluteJoint.prototype.getReactionTorque=function(inv_dt){return inv_dt*this.m_impulse.z};RevoluteJoint.prototype.initVelocityConstraints=function(step){this.m_localCenterA=this.m_bodyA.m_sweep.localCenter;this.m_localCenterB=this.m_bodyB.m_sweep.localCenter;this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var aA=this.m_bodyA.c_position.a;var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var aB=this.m_bodyB.c_position.a;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var qA=Rot.neo(aA);var qB=Rot.neo(aB);this.m_rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));this.m_rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var fixedRotation=iA+iB===0;this.m_mass.ex.x=mA+mB+this.m_rA.y*this.m_rA.y*iA+this.m_rB.y*this.m_rB.y*iB;this.m_mass.ey.x=-this.m_rA.y*this.m_rA.x*iA-this.m_rB.y*this.m_rB.x*iB;this.m_mass.ez.x=-this.m_rA.y*iA-this.m_rB.y*iB;this.m_mass.ex.y=this.m_mass.ey.x;this.m_mass.ey.y=mA+mB+this.m_rA.x*this.m_rA.x*iA+this.m_rB.x*this.m_rB.x*iB;this.m_mass.ez.y=this.m_rA.x*iA+this.m_rB.x*iB;this.m_mass.ex.z=this.m_mass.ez.x;this.m_mass.ey.z=this.m_mass.ez.y;this.m_mass.ez.z=iA+iB;this.m_motorMass=iA+iB;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass}if(this.m_enableMotor==false||fixedRotation){this.m_motorImpulse=0}if(this.m_enableLimit&&fixedRotation==false){var jointAngle=aB-aA-this.m_referenceAngle;if(Math.abs(this.m_upperAngle-this.m_lowerAngle)<2*Settings.angularSlop){this.m_limitState=equalLimits}else if(jointAngle<=this.m_lowerAngle){if(this.m_limitState!=atLowerLimit){this.m_impulse.z=0}this.m_limitState=atLowerLimit}else if(jointAngle>=this.m_upperAngle){if(this.m_limitState!=atUpperLimit){this.m_impulse.z=0}this.m_limitState=atUpperLimit}else{this.m_limitState=inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=inactiveLimit}if(step.warmStarting){this.m_impulse.mul(step.dtRatio);this.m_motorImpulse*=step.dtRatio;var P=Vec2.neo(this.m_impulse.x,this.m_impulse.y);vA.subMul(mA,P);wA-=iA*(Vec2.cross(this.m_rA,P)+this.m_motorImpulse+this.m_impulse.z);vB.addMul(mB,P);wB+=iB*(Vec2.cross(this.m_rB,P)+this.m_motorImpulse+this.m_impulse.z)}else{this.m_impulse.setZero();this.m_motorImpulse=0}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};RevoluteJoint.prototype.solveVelocityConstraints=function(step){var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var fixedRotation=iA+iB===0;if(this.m_enableMotor&&this.m_limitState!=equalLimits&&fixedRotation==false){var Cdot=wB-wA-this.m_motorSpeed;var impulse=-this.m_motorMass*Cdot;var oldImpulse=this.m_motorImpulse;var maxImpulse=step.dt*this.m_maxMotorTorque;this.m_motorImpulse=Math.clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse}if(this.m_enableLimit&&this.m_limitState!=inactiveLimit&&fixedRotation==false){var Cdot1=Vec2.zero();Cdot1.addCombine(1,vB,1,Vec2.cross(wB,this.m_rB));Cdot1.subCombine(1,vA,1,Vec2.cross(wA,this.m_rA));var Cdot2=wB-wA;var Cdot=Vec3(Cdot1.x,Cdot1.y,Cdot2);var impulse=Vec3.neg(this.m_mass.solve33(Cdot));if(this.m_limitState==equalLimits){this.m_impulse.add(impulse)}else if(this.m_limitState==atLowerLimit){var newImpulse=this.m_impulse.z+impulse.z;if(newImpulse<0){var rhs=Vec2.combine(-1,Cdot1,this.m_impulse.z,Vec2.neo(this.m_mass.ez.x,this.m_mass.ez.y));var reduced=this.m_mass.solve22(rhs);impulse.x=reduced.x;impulse.y=reduced.y;impulse.z=-this.m_impulse.z;this.m_impulse.x+=reduced.x;this.m_impulse.y+=reduced.y;this.m_impulse.z=0}else{this.m_impulse.add(impulse)}}else if(this.m_limitState==atUpperLimit){var newImpulse=this.m_impulse.z+impulse.z;if(newImpulse>0){var rhs=Vec2.combine(-1,Cdot1,this.m_impulse.z,Vec2.neo(this.m_mass.ez.x,this.m_mass.ez.y));var reduced=this.m_mass.solve22(rhs);impulse.x=reduced.x;impulse.y=reduced.y;impulse.z=-this.m_impulse.z;this.m_impulse.x+=reduced.x;this.m_impulse.y+=reduced.y;this.m_impulse.z=0}else{this.m_impulse.add(impulse)}}var P=Vec2.neo(impulse.x,impulse.y);vA.subMul(mA,P);wA-=iA*(Vec2.cross(this.m_rA,P)+impulse.z);vB.addMul(mB,P);wB+=iB*(Vec2.cross(this.m_rB,P)+impulse.z)}else{var Cdot=Vec2.zero();Cdot.addCombine(1,vB,1,Vec2.cross(wB,this.m_rB));Cdot.subCombine(1,vA,1,Vec2.cross(wA,this.m_rA));var impulse=this.m_mass.solve22(Vec2.neg(Cdot));this.m_impulse.x+=impulse.x;this.m_impulse.y+=impulse.y;vA.subMul(mA,impulse);wA-=iA*Vec2.cross(this.m_rA,impulse);vB.addMul(mB,impulse);wB+=iB*Vec2.cross(this.m_rB,impulse)}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};RevoluteJoint.prototype.solvePositionConstraints=function(step){var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var angularError=0;var positionError=0;var fixedRotation=this.m_invIA+this.m_invIB==0;if(this.m_enableLimit&&this.m_limitState!=inactiveLimit&&fixedRotation==false){var angle=aB-aA-this.m_referenceAngle;var limitImpulse=0;if(this.m_limitState==equalLimits){var C=Math.clamp(angle-this.m_lowerAngle,-Settings.maxAngularCorrection,Settings.maxAngularCorrection);limitImpulse=-this.m_motorMass*C;angularError=Math.abs(C)}else if(this.m_limitState==atLowerLimit){var C=angle-this.m_lowerAngle;angularError=-C;C=Math.clamp(C+Settings.angularSlop,-Settings.maxAngularCorrection,0);limitImpulse=-this.m_motorMass*C}else if(this.m_limitState==atUpperLimit){var C=angle-this.m_upperAngle;angularError=C;C=Math.clamp(C-Settings.angularSlop,0,Settings.maxAngularCorrection);limitImpulse=-this.m_motorMass*C}aA-=this.m_invIA*limitImpulse;aB+=this.m_invIB*limitImpulse}{qA.set(aA);qB.set(aB);var rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));var rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var C=Vec2.zero();C.addCombine(1,cB,1,rB);C.subCombine(1,cA,1,rA);positionError=C.length();var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var K=new Mat22;K.ex.x=mA+mB+iA*rA.y*rA.y+iB*rB.y*rB.y;K.ex.y=-iA*rA.x*rA.y-iB*rB.x*rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*rA.x*rA.x+iB*rB.x*rB.x;var impulse=Vec2.neg(K.solve(C));cA.subMul(mA,impulse);aA-=iA*Vec2.cross(rA,impulse);cB.addMul(mB,impulse);aB+=iB*Vec2.cross(rB,impulse)}this.m_bodyA.c_position.c.set(cA);this.m_bodyA.c_position.a=aA;this.m_bodyB.c_position.c.set(cB);this.m_bodyB.c_position.a=aB;return positionError<=Settings.linearSlop&&angularError<=Settings.angularSlop}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=PrismaticJoint;var common=__webpack_require__(2);var options=__webpack_require__(7);var create=__webpack_require__(6);var Settings=__webpack_require__(4);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var Vec3=__webpack_require__(11);var Mat22=__webpack_require__(10);var Mat33=__webpack_require__(15);var Rot=__webpack_require__(3);var Sweep=__webpack_require__(9);var Transform=__webpack_require__(5);var Velocity=__webpack_require__(13);var Position=__webpack_require__(14);var Joint=__webpack_require__(12);var Body=__webpack_require__(8);var inactiveLimit=0;var atLowerLimit=1;var atUpperLimit=2;var equalLimits=3;PrismaticJoint.TYPE="prismatic-joint";Joint.TYPES[PrismaticJoint.TYPE]=PrismaticJoint;PrismaticJoint._super=Joint;PrismaticJoint.prototype=create(PrismaticJoint._super.prototype);var DEFAULTS={enableLimit:false,lowerTranslation:0,upperTranslation:0,enableMotor:false,maxMotorForce:0,motorSpeed:0};function PrismaticJoint(def,bodyA,bodyB,anchor,axis){if(!(this instanceof PrismaticJoint)){return new PrismaticJoint(def,bodyA,bodyB,anchor,axis)}def=options(def,DEFAULTS);Joint.call(this,def,bodyA,bodyB);bodyA=this.m_bodyA;bodyB=this.m_bodyB;this.m_type=PrismaticJoint.TYPE;this.m_localAnchorA=anchor?bodyA.getLocalPoint(anchor):def.localAnchorA||Vec2.zero();this.m_localAnchorB=anchor?bodyB.getLocalPoint(anchor):def.localAnchorB||Vec2.zero();this.m_localXAxisA=axis?bodyA.getLocalVector(axis):def.localAxisA||Vec2.neo(1,0);this.m_localXAxisA.normalize();this.m_localYAxisA=Vec2.cross(1,this.m_localXAxisA);this.m_referenceAngle=Math.isFinite(def.referenceAngle)?def.referenceAngle:bodyB.getAngle()-bodyA.getAngle();this.m_impulse=Vec3();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=inactiveLimit;this.m_axis=Vec2.zero();this.m_perp=Vec2.zero();this.m_localCenterA;this.m_localCenterB;this.m_invMassA;this.m_invMassB;this.m_invIA;this.m_invIB;this.m_axis,this.m_perp;this.m_s1,this.m_s2;this.m_a1,this.m_a2;this.m_K=new Mat33;this.m_motorMass}PrismaticJoint.prototype._serialize=function(){return{type:this.m_type,bodyA:this.m_bodyA,bodyB:this.m_bodyB,collideConnected:this.m_collideConnected,lowerTranslation:this.m_lowerTranslation,upperTranslation:this.m_upperTranslation,maxMotorForce:this.m_maxMotorForce,motorSpeed:this.m_motorSpeed,enableLimit:this.m_enableLimit,enableMotor:this.m_enableMotor,localAnchorA:this.m_localAnchorA,localAnchorB:this.m_localAnchorB,localAxisA:this.m_localXAxisA,referenceAngle:this.m_referenceAngle}};PrismaticJoint._deserialize=function(data,world,restore){data.bodyA=restore(Body,data.bodyA,world);data.bodyB=restore(Body,data.bodyB,world);data.localAxisA=Vec2(data.localAxisA);var joint=new PrismaticJoint(data);return joint};PrismaticJoint.prototype.getLocalAnchorA=function(){return this.m_localAnchorA};PrismaticJoint.prototype.getLocalAnchorB=function(){return this.m_localAnchorB};PrismaticJoint.prototype.getLocalAxisA=function(){return this.m_localXAxisA};PrismaticJoint.prototype.getReferenceAngle=function(){return this.m_referenceAngle};PrismaticJoint.prototype.getJointTranslation=function(){var pA=this.m_bodyA.getWorldPoint(this.m_localAnchorA);var pB=this.m_bodyB.getWorldPoint(this.m_localAnchorB);var d=Vec2.sub(pB,pA);var axis=this.m_bodyA.getWorldVector(this.m_localXAxisA);var translation=Vec2.dot(d,axis);return translation};PrismaticJoint.prototype.getJointSpeed=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var rA=Rot.mulVec2(bA.m_xf.q,Vec2.sub(this.m_localAnchorA,bA.m_sweep.localCenter));var rB=Rot.mulVec2(bB.m_xf.q,Vec2.sub(this.m_localAnchorB,bB.m_sweep.localCenter));var p1=Vec2.add(bA.m_sweep.c,rA);var p2=Vec2.add(bB.m_sweep.c,rB);var d=Vec2.sub(p2,p1);var axis=Rot.mulVec2(bA.m_xf.q,this.m_localXAxisA);var vA=bA.m_linearVelocity;var vB=bB.m_linearVelocity;var wA=bA.m_angularVelocity;var wB=bB.m_angularVelocity;var speed=Vec2.dot(d,Vec2.cross(wA,axis))+Vec2.dot(axis,Vec2.sub(Vec2.addCross(vB,wB,rB),Vec2.addCross(vA,wA,rA)));return speed};PrismaticJoint.prototype.isLimitEnabled=function(){return this.m_enableLimit};PrismaticJoint.prototype.enableLimit=function(flag){if(flag!=this.m_enableLimit){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_enableLimit=flag;this.m_impulse.z=0}};PrismaticJoint.prototype.getLowerLimit=function(){return this.m_lowerTranslation};PrismaticJoint.prototype.getUpperLimit=function(){return this.m_upperTranslation};PrismaticJoint.prototype.setLimits=function(lower,upper){_ASSERT&&common.assert(lower<=upper);if(lower!=this.m_lowerTranslation||upper!=this.m_upperTranslation){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_lowerTranslation=lower;this.m_upperTranslation=upper;this.m_impulse.z=0}};PrismaticJoint.prototype.isMotorEnabled=function(){return this.m_enableMotor};PrismaticJoint.prototype.enableMotor=function(flag){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_enableMotor=flag};PrismaticJoint.prototype.setMotorSpeed=function(speed){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_motorSpeed=speed};PrismaticJoint.prototype.setMaxMotorForce=function(force){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_maxMotorForce=force};PrismaticJoint.prototype.getMotorSpeed=function(){return this.m_motorSpeed};PrismaticJoint.prototype.getMotorForce=function(inv_dt){return inv_dt*this.m_motorImpulse};PrismaticJoint.prototype.getAnchorA=function(){return this.m_bodyA.getWorldPoint(this.m_localAnchorA)};PrismaticJoint.prototype.getAnchorB=function(){return this.m_bodyB.getWorldPoint(this.m_localAnchorB)};PrismaticJoint.prototype.getReactionForce=function(inv_dt){return Vec2.combine(this.m_impulse.x,this.m_perp,this.m_motorImpulse+this.m_impulse.z,this.m_axis).mul(inv_dt)};PrismaticJoint.prototype.getReactionTorque=function(inv_dt){return inv_dt*this.m_impulse.y};PrismaticJoint.prototype.initVelocityConstraints=function(step){this.m_localCenterA=this.m_bodyA.m_sweep.localCenter;this.m_localCenterB=this.m_bodyB.m_sweep.localCenter;this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));var rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var d=Vec2.zero();d.addCombine(1,cB,1,rB);d.subCombine(1,cA,1,rA);var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;{this.m_axis=Rot.mulVec2(qA,this.m_localXAxisA);this.m_a1=Vec2.cross(Vec2.add(d,rA),this.m_axis);this.m_a2=Vec2.cross(rB,this.m_axis);this.m_motorMass=mA+mB+iA*this.m_a1*this.m_a1+iB*this.m_a2*this.m_a2;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass}}{this.m_perp=Rot.mulVec2(qA,this.m_localYAxisA);this.m_s1=Vec2.cross(Vec2.add(d,rA),this.m_perp);this.m_s2=Vec2.cross(rB,this.m_perp);var s1test=Vec2.cross(rA,this.m_perp);var k11=mA+mB+iA*this.m_s1*this.m_s1+iB*this.m_s2*this.m_s2;var k12=iA*this.m_s1+iB*this.m_s2;var k13=iA*this.m_s1*this.m_a1+iB*this.m_s2*this.m_a2;var k22=iA+iB;if(k22==0){k22=1}var k23=iA*this.m_a1+iB*this.m_a2;var k33=mA+mB+iA*this.m_a1*this.m_a1+iB*this.m_a2*this.m_a2;this.m_K.ex.set(k11,k12,k13);this.m_K.ey.set(k12,k22,k23);this.m_K.ez.set(k13,k23,k33)}if(this.m_enableLimit){var jointTranslation=Vec2.dot(this.m_axis,d);if(Math.abs(this.m_upperTranslation-this.m_lowerTranslation)<2*Settings.linearSlop){this.m_limitState=equalLimits}else if(jointTranslation<=this.m_lowerTranslation){if(this.m_limitState!=atLowerLimit){this.m_limitState=atLowerLimit;this.m_impulse.z=0}}else if(jointTranslation>=this.m_upperTranslation){if(this.m_limitState!=atUpperLimit){this.m_limitState=atUpperLimit;this.m_impulse.z=0}}else{this.m_limitState=inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=inactiveLimit;this.m_impulse.z=0}if(this.m_enableMotor==false){this.m_motorImpulse=0}if(step.warmStarting){this.m_impulse.mul(step.dtRatio);this.m_motorImpulse*=step.dtRatio;var P=Vec2.combine(this.m_impulse.x,this.m_perp,this.m_motorImpulse+this.m_impulse.z,this.m_axis);var LA=this.m_impulse.x*this.m_s1+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a1;var LB=this.m_impulse.x*this.m_s2+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a2;vA.subMul(mA,P);wA-=iA*LA;vB.addMul(mB,P);wB+=iB*LB}else{this.m_impulse.setZero();this.m_motorImpulse=0}this.m_bodyA.c_velocity.v.set(vA);this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v.set(vB);this.m_bodyB.c_velocity.w=wB};PrismaticJoint.prototype.solveVelocityConstraints=function(step){var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;if(this.m_enableMotor&&this.m_limitState!=equalLimits){var Cdot=Vec2.dot(this.m_axis,Vec2.sub(vB,vA))+this.m_a2*wB-this.m_a1*wA;var impulse=this.m_motorMass*(this.m_motorSpeed-Cdot);var oldImpulse=this.m_motorImpulse;var maxImpulse=step.dt*this.m_maxMotorForce;this.m_motorImpulse=Math.clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;var P=Vec2.mul(impulse,this.m_axis);var LA=impulse*this.m_a1;var LB=impulse*this.m_a2;vA.subMul(mA,P);wA-=iA*LA;vB.addMul(mB,P);wB+=iB*LB}var Cdot1=Vec2.zero();Cdot1.x+=Vec2.dot(this.m_perp,vB)+this.m_s2*wB;Cdot1.x-=Vec2.dot(this.m_perp,vA)+this.m_s1*wA;Cdot1.y=wB-wA;if(this.m_enableLimit&&this.m_limitState!=inactiveLimit){var Cdot2=0;Cdot2+=Vec2.dot(this.m_axis,vB)+this.m_a2*wB;Cdot2-=Vec2.dot(this.m_axis,vA)+this.m_a1*wA;var Cdot=Vec3(Cdot1.x,Cdot1.y,Cdot2);var f1=Vec3(this.m_impulse);var df=this.m_K.solve33(Vec3.neg(Cdot));this.m_impulse.add(df);if(this.m_limitState==atLowerLimit){this.m_impulse.z=Math.max(this.m_impulse.z,0)}else if(this.m_limitState==atUpperLimit){this.m_impulse.z=Math.min(this.m_impulse.z,0)}var b=Vec2.combine(-1,Cdot1,-(this.m_impulse.z-f1.z),Vec2.neo(this.m_K.ez.x,this.m_K.ez.y));var f2r=Vec2.add(this.m_K.solve22(b),Vec2.neo(f1.x,f1.y));this.m_impulse.x=f2r.x;this.m_impulse.y=f2r.y;df=Vec3.sub(this.m_impulse,f1);var P=Vec2.combine(df.x,this.m_perp,df.z,this.m_axis);var LA=df.x*this.m_s1+df.y+df.z*this.m_a1;var LB=df.x*this.m_s2+df.y+df.z*this.m_a2;vA.subMul(mA,P);wA-=iA*LA;vB.addMul(mB,P);wB+=iB*LB}else{var df=this.m_K.solve22(Vec2.neg(Cdot1));this.m_impulse.x+=df.x;this.m_impulse.y+=df.y;var P=Vec2.mul(df.x,this.m_perp);var LA=df.x*this.m_s1+df.y;var LB=df.x*this.m_s2+df.y;vA.subMul(mA,P);wA-=iA*LA;vB.addMul(mB,P);wB+=iB*LB}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};PrismaticJoint.prototype.solvePositionConstraints=function(step){var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));var rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var d=Vec2.sub(Vec2.add(cB,rB),Vec2.add(cA,rA));var axis=Rot.mulVec2(qA,this.m_localXAxisA);var a1=Vec2.cross(Vec2.add(d,rA),axis);var a2=Vec2.cross(rB,axis);var perp=Rot.mulVec2(qA,this.m_localYAxisA);var s1=Vec2.cross(Vec2.add(d,rA),perp);var s2=Vec2.cross(rB,perp);var impulse=Vec3();var C1=Vec2.zero();C1.x=Vec2.dot(perp,d);C1.y=aB-aA-this.m_referenceAngle;var linearError=Math.abs(C1.x);var angularError=Math.abs(C1.y);var linearSlop=Settings.linearSlop;var maxLinearCorrection=Settings.maxLinearCorrection;var active=false;var C2=0;if(this.m_enableLimit){var translation=Vec2.dot(axis,d);if(Math.abs(this.m_upperTranslation-this.m_lowerTranslation)<2*linearSlop){C2=Math.clamp(translation,-maxLinearCorrection,maxLinearCorrection);linearError=Math.max(linearError,Math.abs(translation));active=true}else if(translation<=this.m_lowerTranslation){C2=Math.clamp(translation-this.m_lowerTranslation+linearSlop,-maxLinearCorrection,0);linearError=Math.max(linearError,this.m_lowerTranslation-translation);active=true}else if(translation>=this.m_upperTranslation){C2=Math.clamp(translation-this.m_upperTranslation-linearSlop,0,maxLinearCorrection);linearError=Math.max(linearError,translation-this.m_upperTranslation);active=true}}if(active){var k11=mA+mB+iA*s1*s1+iB*s2*s2;var k12=iA*s1+iB*s2;var k13=iA*s1*a1+iB*s2*a2;var k22=iA+iB;if(k22==0){k22=1}var k23=iA*a1+iB*a2;var k33=mA+mB+iA*a1*a1+iB*a2*a2;var K=new Mat33;K.ex.set(k11,k12,k13);K.ey.set(k12,k22,k23);K.ez.set(k13,k23,k33);var C=Vec3();C.x=C1.x;C.y=C1.y;C.z=C2;impulse=K.solve33(Vec3.neg(C))}else{var k11=mA+mB+iA*s1*s1+iB*s2*s2;var k12=iA*s1+iB*s2;var k22=iA+iB;if(k22==0){k22=1}var K=new Mat22;K.ex.set(k11,k12);K.ey.set(k12,k22);var impulse1=K.solve(Vec2.neg(C1));impulse.x=impulse1.x;impulse.y=impulse1.y;impulse.z=0}var P=Vec2.combine(impulse.x,perp,impulse.z,axis);var LA=impulse.x*s1+impulse.y+impulse.z*a1;var LB=impulse.x*s2+impulse.y+impulse.z*a2;cA.subMul(mA,P);aA-=iA*LA;cB.addMul(mB,P);aB+=iB*LB;this.m_bodyA.c_position.c=cA;this.m_bodyA.c_position.a=aA;this.m_bodyB.c_position.c=cB;this.m_bodyB.c_position.a=aB;return linearError<=Settings.linearSlop&&angularError<=Settings.angularSlop}},,,,function(module,exports,__webpack_require__){exports.internal={};exports.Serializer=__webpack_require__(40);exports.Math=__webpack_require__(1);exports.Vec2=__webpack_require__(0);exports.Vec3=__webpack_require__(11);exports.Mat22=__webpack_require__(10);exports.Mat33=__webpack_require__(15);exports.Transform=__webpack_require__(5);exports.Rot=__webpack_require__(3);exports.AABB=__webpack_require__(17);exports.Shape=__webpack_require__(16);exports.Fixture=__webpack_require__(32);exports.Body=__webpack_require__(8);exports.Contact=__webpack_require__(18);exports.Joint=__webpack_require__(12);exports.World=__webpack_require__(30);exports.Circle=__webpack_require__(23);exports.Edge=__webpack_require__(24);exports.Polygon=__webpack_require__(21);exports.Chain=__webpack_require__(28);exports.Box=__webpack_require__(45);__webpack_require__(46);__webpack_require__(47);exports.internal.CollidePolygons=__webpack_require__(48);__webpack_require__(49);__webpack_require__(50);exports.DistanceJoint=__webpack_require__(51);exports.FrictionJoint=__webpack_require__(52);exports.GearJoint=__webpack_require__(53);exports.MotorJoint=__webpack_require__(54);exports.MouseJoint=__webpack_require__(55);exports.PrismaticJoint=__webpack_require__(35);exports.PulleyJoint=__webpack_require__(56);exports.RevoluteJoint=__webpack_require__(34);exports.RopeJoint=__webpack_require__(57);exports.WeldJoint=__webpack_require__(58);exports.WheelJoint=__webpack_require__(59);exports.internal.Sweep=__webpack_require__(9);exports.internal.stats=__webpack_require__(27);exports.internal.Manifold=__webpack_require__(19);exports.internal.Distance=__webpack_require__(22);exports.internal.TimeOfImpact=__webpack_require__(33);exports.internal.DynamicTree=__webpack_require__(31);exports.internal.Settings=__webpack_require__(4)},function(module,exports,__webpack_require__){var World=__webpack_require__(30);var Body=__webpack_require__(8);var Joint=__webpack_require__(12);var Shape=__webpack_require__(16);var SID=0;function Serializer(opts){opts=opts||{};var stringify=opts.stringify||JSON.stringify;var parse=opts.parse||JSON.parse;var rootClass=opts.rootClass||World;var preSerialize=opts.preSerialize||function(obj){return obj};var postSerialize=opts.postSerialize||function(data,obj){return data};var preDeserialize=opts.preDeserialize||function(data){return data};var postDeserialize=opts.postDeserialize||function(obj,data){return obj};var refTypes={World:World,Body:Body,Joint:Joint};this.toJson=function(root){var flat=[];var queue=[root];var refMap={};function storeRef(value,typeName){value.__sid=value.__sid||++SID;if(!refMap[value.__sid]){queue.push(value);var index=flat.length+queue.length;var ref={refIndex:index,refType:typeName};refMap[value.__sid]=ref}return refMap[value.__sid]}function serialize(obj){obj=preSerialize(obj);var data=obj._serialize();data=postSerialize(data,obj);return data}while(queue.length){var obj=queue.shift();var str=stringify(obj,function(key,value){if(typeof value!=="object"||value===null){return value}if(typeof value._serialize!=="function"){return value}if(value===obj){return serialize(value)}for(var typeName in refTypes){if(value instanceof refTypes[typeName]){return storeRef(value,typeName)}}return serialize(value)}," ");flat.push(str)}var result=`[${flat.join(",")}]`;return result};this.fromJson=function(string){var flat=parse(string);var refMap={};function deserialize(cls,data,ctx){data=preDeserialize(data);var obj=cls._deserialize(data,ctx,restoreRef);obj=postDeserialize(obj,data);return obj}function restoreRef(cls,ref,ctx){if(!ref.refIndex){return cls&&cls._deserialize&&deserialize(cls,ref,ctx)}cls=refTypes[ref.refType]||cls;var index=ref.refIndex;if(!refMap[index]){var data=flat[index];var obj=deserialize(cls,data,ctx);refMap[index]=obj}return refMap[index]}var root=rootClass._deserialize(flat[0],null,restoreRef);return root}}module.exports=Serializer;var serializer=new Serializer;module.exports.toJson=serializer.toJson;module.exports.fromJson=serializer.fromJson},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;var Settings=__webpack_require__(4);var common=__webpack_require__(2);var Math=__webpack_require__(1);var AABB=__webpack_require__(17);var DynamicTree=__webpack_require__(31);module.exports=BroadPhase;function BroadPhase(){this.m_tree=new DynamicTree;this.m_proxyCount=0;this.m_moveBuffer=[];this.queryCallback=this.queryCallback.bind(this)}BroadPhase.prototype.getUserData=function(proxyId){return this.m_tree.getUserData(proxyId)};BroadPhase.prototype.testOverlap=function(proxyIdA,proxyIdB){var aabbA=this.m_tree.getFatAABB(proxyIdA);var aabbB=this.m_tree.getFatAABB(proxyIdB);return AABB.testOverlap(aabbA,aabbB)};BroadPhase.prototype.getFatAABB=function(proxyId){return this.m_tree.getFatAABB(proxyId)};BroadPhase.prototype.getProxyCount=function(){return this.m_proxyCount};BroadPhase.prototype.getTreeHeight=function(){return this.m_tree.getHeight()};BroadPhase.prototype.getTreeBalance=function(){return this.m_tree.getMaxBalance()};BroadPhase.prototype.getTreeQuality=function(){return this.m_tree.getAreaRatio()};BroadPhase.prototype.query=function(aabb,queryCallback){this.m_tree.query(aabb,queryCallback)};BroadPhase.prototype.rayCast=function(input,rayCastCallback){this.m_tree.rayCast(input,rayCastCallback)};BroadPhase.prototype.shiftOrigin=function(newOrigin){this.m_tree.shiftOrigin(newOrigin)};BroadPhase.prototype.createProxy=function(aabb,userData){_ASSERT&&common.assert(AABB.isValid(aabb));var proxyId=this.m_tree.createProxy(aabb,userData);this.m_proxyCount++;this.bufferMove(proxyId);return proxyId};BroadPhase.prototype.destroyProxy=function(proxyId){this.unbufferMove(proxyId);this.m_proxyCount--;this.m_tree.destroyProxy(proxyId)};BroadPhase.prototype.moveProxy=function(proxyId,aabb,displacement){_ASSERT&&common.assert(AABB.isValid(aabb));var changed=this.m_tree.moveProxy(proxyId,aabb,displacement);if(changed){this.bufferMove(proxyId)}};BroadPhase.prototype.touchProxy=function(proxyId){this.bufferMove(proxyId)};BroadPhase.prototype.bufferMove=function(proxyId){this.m_moveBuffer.push(proxyId)};BroadPhase.prototype.unbufferMove=function(proxyId){for(var i=0;i0){this.m_queryProxyId=this.m_moveBuffer.pop();if(this.m_queryProxyId===null){continue}var fatAABB=this.m_tree.getFatAABB(this.m_queryProxyId);this.m_tree.query(fatAABB,this.queryCallback)}};BroadPhase.prototype.queryCallback=function(proxyId){if(proxyId==this.m_queryProxyId){return true}var proxyIdA=Math.min(proxyId,this.m_queryProxyId);var proxyIdB=Math.max(proxyId,this.m_queryProxyId);var userDataA=this.m_tree.getUserData(proxyIdA);var userDataB=this.m_tree.getUserData(proxyIdB);this.m_callback(userDataA,userDataB);return true}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Pool;function Pool(opts){var _list=[];var _max=opts.max||Infinity;var _createFn=opts.create;var _outFn=opts.allocate;var _inFn=opts.release;var _discardFn=opts.discard;var _createCount=0;var _outCount=0;var _inCount=0;var _discardCount=0;this.max=function(n){if(typeof n==="number"){_max=n;return this}return _max};this.size=function(){return _list.length};this.allocate=function(){var item;if(_list.length>0){item=_list.shift()}else{_createCount++;if(typeof _createFn==="function"){item=_createFn()}else{item={}}}_outCount++;if(typeof _outFn==="function"){_outFn(item)}return item};this.release=function(item){if(_list.length<_max){_inCount++;if(typeof _inFn==="function"){_inFn(item)}_list.push(item)}else{_discardCount++;if(typeof _discardFn==="function"){item=_discardFn(item)}}};this.toString=function(){return` +${_createCount} >${_outCount} <${_inCount} -${_discardCount} =${_list.length}/${_max}`}}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=Solver;module.exports.TimeStep=TimeStep;var Settings=__webpack_require__(4);var common=__webpack_require__(2);var Vec2=__webpack_require__(0);var Math=__webpack_require__(1);var Body=__webpack_require__(8);var Contact=__webpack_require__(18);var Joint=__webpack_require__(12);var TimeOfImpact=__webpack_require__(33);var TOIInput=TimeOfImpact.Input;var TOIOutput=TimeOfImpact.Output;var Distance=__webpack_require__(22);var DistanceInput=Distance.Input;var DistanceOutput=Distance.Output;var DistanceProxy=Distance.Proxy;var SimplexCache=Distance.Cache;function TimeStep(dt){this.dt=0;this.inv_dt=0;this.velocityIterations=0;this.positionIterations=0;this.warmStarting=false;this.blockSolve=true;this.inv_dt0=0;this.dtRatio=1}TimeStep.prototype.reset=function(dt){if(this.dt>0){this.inv_dt0=this.inv_dt}this.dt=dt;this.inv_dt=dt==0?0:1/dt;this.dtRatio=dt*this.inv_dt0};function Solver(world){this.m_world=world;this.m_stack=[];this.m_bodies=[];this.m_contacts=[];this.m_joints=[]}Solver.prototype.clear=function(){this.m_stack.length=0;this.m_bodies.length=0;this.m_contacts.length=0;this.m_joints.length=0};Solver.prototype.addBody=function(body){_ASSERT&&common.assert(body instanceof Body,"Not a Body!",body);this.m_bodies.push(body)};Solver.prototype.addContact=function(contact){_ASSERT&&common.assert(contact instanceof Contact,"Not a Contact!",contact);this.m_contacts.push(contact)};Solver.prototype.addJoint=function(joint){_ASSERT&&common.assert(joint instanceof Joint,"Not a Joint!",joint);this.m_joints.push(joint)};Solver.prototype.solveWorld=function(step){var world=this.m_world;for(var b=world.m_bodyList;b;b=b.m_next){b.m_islandFlag=false}for(var c=world.m_contactList;c;c=c.m_next){c.m_islandFlag=false}for(var j=world.m_jointList;j;j=j.m_next){j.m_islandFlag=false}var stack=this.m_stack;var loop=-1;for(var seed=world.m_bodyList;seed;seed=seed.m_next){loop++;if(seed.m_islandFlag){continue}if(seed.isAwake()==false||seed.isActive()==false){continue}if(seed.isStatic()){continue}this.clear();stack.push(seed);seed.m_islandFlag=true;while(stack.length>0){var b=stack.pop();_ASSERT&&common.assert(b.isActive()==true);this.addBody(b);b.setAwake(true);if(b.isStatic()){continue}for(var ce=b.m_contactList;ce;ce=ce.next){var contact=ce.contact;if(contact.m_islandFlag){continue}if(contact.isEnabled()==false||contact.isTouching()==false){continue}var sensorA=contact.m_fixtureA.m_isSensor;var sensorB=contact.m_fixtureB.m_isSensor;if(sensorA||sensorB){continue}this.addContact(contact);contact.m_islandFlag=true;var other=ce.other;if(other.m_islandFlag){continue}stack.push(other);other.m_islandFlag=true}for(var je=b.m_jointList;je;je=je.next){if(je.joint.m_islandFlag==true){continue}var other=je.other;if(other.isActive()==false){continue}this.addJoint(je.joint);je.joint.m_islandFlag=true;if(other.m_islandFlag){continue}stack.push(other);other.m_islandFlag=true}}this.solveIsland(step);for(var i=0;iSettings.maxTranslationSquared){var ratio=Settings.maxTranslation/translation.length();v.mul(ratio)}var rotation=h*w;if(rotation*rotation>Settings.maxRotationSquared){var ratio=Settings.maxRotation/Math.abs(rotation);w*=ratio}c.addMul(h,v);a+=h*w;body.c_position.c.set(c);body.c_position.a=a;body.c_velocity.v.set(v);body.c_velocity.w=w}_DEBUG&&this.printBodies("B: ");var positionSolved=false;for(var i=0;i=-3*Settings.linearSlop;var jointsOkay=true;for(var j=0;jangTolSqr||Vec2.lengthSquared(body.m_linearVelocity)>linTolSqr){body.m_sleepTime=0;minSleepTime=0}else{body.m_sleepTime+=h;minSleepTime=Math.min(minSleepTime,body.m_sleepTime)}}if(minSleepTime>=Settings.timeToSleep&&positionSolved){for(var i=0;iSettings.maxSubSteps){continue}var alpha=1;if(c.m_toiFlag){alpha=c.m_toi}else{var fA=c.getFixtureA();var fB=c.getFixtureB();if(fA.isSensor()||fB.isSensor()){continue}var bA=fA.getBody();var bB=fB.getBody();_ASSERT&&common.assert(bA.isDynamic()||bB.isDynamic());var activeA=bA.isAwake()&&!bA.isStatic();var activeB=bB.isAwake()&&!bB.isStatic();if(activeA==false&&activeB==false){continue}var collideA=bA.isBullet()||!bA.isDynamic();var collideB=bB.isBullet()||!bB.isDynamic();if(collideA==false&&collideB==false){continue}var alpha0=bA.m_sweep.alpha0;if(bA.m_sweep.alpha0=-1.5*Settings.linearSlop;if(contactsOkay){break}}if(false){var cache,output,input,indexB,indexA,bB,bA,fB,fA,c,i}toiA.m_sweep.c0.set(toiA.c_position.c);toiA.m_sweep.a0=toiA.c_position.a;toiB.m_sweep.c0.set(toiB.c_position.c);toiB.m_sweep.a0=toiB.c_position.a;for(var i=0;iSettings.maxTranslationSquared){var ratio=Settings.maxTranslation/translation.length();v.mul(ratio)}var rotation=h*w;if(rotation*rotation>Settings.maxRotationSquared){var ratio=Settings.maxRotation/Math.abs(rotation);w*=ratio}c.addMul(h,v);a+=h*w;body.c_position.c=c;body.c_position.a=a;body.c_velocity.v=v;body.c_velocity.w=w;body.m_sweep.c=c;body.m_sweep.a=a;body.m_linearVelocity=v;body.m_angularVelocity=w;body.synchronizeTransform()}this.postSolveIsland()};function ContactImpulse(){this.normalImpulses=[];this.tangentImpulses=[]}Solver.prototype.postSolveIsland=function(){var impulse=new ContactImpulse;for(var c=0;cradius*radius){return}manifold.type=Manifold.e_circles;manifold.localPoint.set(circleA.m_p);manifold.localNormal.setZero();manifold.pointCount=1;manifold.points[0].localPoint.set(circleB.m_p);manifold.points[0].id.cf.indexA=0;manifold.points[0].id.cf.typeA=Manifold.e_vertex;manifold.points[0].id.cf.indexB=0;manifold.points[0].id.cf.typeB=Manifold.e_vertex}exports.CollideCircles=CollideCircles},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;var common=__webpack_require__(2);var create=__webpack_require__(6);var Math=__webpack_require__(1);var Transform=__webpack_require__(5);var Vec2=__webpack_require__(0);var Rot=__webpack_require__(3);var Settings=__webpack_require__(4);var Shape=__webpack_require__(16);var Contact=__webpack_require__(18);var Manifold=__webpack_require__(19);var EdgeShape=__webpack_require__(24);var ChainShape=__webpack_require__(28);var CircleShape=__webpack_require__(23);Contact.addType(EdgeShape.TYPE,CircleShape.TYPE,EdgeCircleContact);Contact.addType(ChainShape.TYPE,CircleShape.TYPE,ChainCircleContact);function EdgeCircleContact(manifold,xfA,fixtureA,indexA,xfB,fixtureB,indexB){_ASSERT&&common.assert(fixtureA.getType()==EdgeShape.TYPE);_ASSERT&&common.assert(fixtureB.getType()==CircleShape.TYPE);var shapeA=fixtureA.getShape();var shapeB=fixtureB.getShape();CollideEdgeCircle(manifold,shapeA,xfA,shapeB,xfB)}function ChainCircleContact(manifold,xfA,fixtureA,indexA,xfB,fixtureB,indexB){_ASSERT&&common.assert(fixtureA.getType()==ChainShape.TYPE);_ASSERT&&common.assert(fixtureB.getType()==CircleShape.TYPE);var chain=fixtureA.getShape();var edge=new EdgeShape;chain.getChildEdge(edge,indexA);var shapeA=edge;var shapeB=fixtureB.getShape();CollideEdgeCircle(manifold,shapeA,xfA,shapeB,xfB)}function CollideEdgeCircle(manifold,edgeA,xfA,circleB,xfB){manifold.pointCount=0;var Q=Transform.mulTVec2(xfA,Transform.mulVec2(xfB,circleB.m_p));var A=edgeA.m_vertex1;var B=edgeA.m_vertex2;var e=Vec2.sub(B,A);var u=Vec2.dot(e,Vec2.sub(B,Q));var v=Vec2.dot(e,Vec2.sub(Q,A));var radius=edgeA.m_radius+circleB.m_radius;if(v<=0){var P=Vec2.clone(A);var d=Vec2.sub(Q,P);var dd=Vec2.dot(d,d);if(dd>radius*radius){return}if(edgeA.m_hasVertex0){var A1=edgeA.m_vertex0;var B1=A;var e1=Vec2.sub(B1,A1);var u1=Vec2.dot(e1,Vec2.sub(B1,Q));if(u1>0){return}}manifold.type=Manifold.e_circles;manifold.localNormal.setZero();manifold.localPoint.set(P);manifold.pointCount=1;manifold.points[0].localPoint.set(circleB.m_p);manifold.points[0].id.cf.indexA=0;manifold.points[0].id.cf.typeA=Manifold.e_vertex;manifold.points[0].id.cf.indexB=0;manifold.points[0].id.cf.typeB=Manifold.e_vertex;return}if(u<=0){var P=Vec2.clone(B);var d=Vec2.sub(Q,P);var dd=Vec2.dot(d,d);if(dd>radius*radius){return}if(edgeA.m_hasVertex3){var B2=edgeA.m_vertex3;var A2=B;var e2=Vec2.sub(B2,A2);var v2=Vec2.dot(e2,Vec2.sub(Q,A2));if(v2>0){return}}manifold.type=Manifold.e_circles;manifold.localNormal.setZero();manifold.localPoint.set(P);manifold.pointCount=1;manifold.points[0].localPoint.set(circleB.m_p);manifold.points[0].id.cf.indexA=1;manifold.points[0].id.cf.typeA=Manifold.e_vertex;manifold.points[0].id.cf.indexB=0;manifold.points[0].id.cf.typeB=Manifold.e_vertex;return}var den=Vec2.dot(e,e);_ASSERT&&common.assert(den>0);var P=Vec2.combine(u/den,A,v/den,B);var d=Vec2.sub(Q,P);var dd=Vec2.dot(d,d);if(dd>radius*radius){return}var n=Vec2.neo(-e.y,e.x);if(Vec2.dot(n,Vec2.sub(Q,A))<0){n.set(-n.x,-n.y)}n.normalize();manifold.type=Manifold.e_faceA;manifold.localNormal=n;manifold.localPoint.set(A);manifold.pointCount=1;manifold.points[0].localPoint.set(circleB.m_p);manifold.points[0].id.cf.indexA=0;manifold.points[0].id.cf.typeA=Manifold.e_face;manifold.points[0].id.cf.indexB=0;manifold.points[0].id.cf.typeB=Manifold.e_vertex}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;var common=__webpack_require__(2);var Math=__webpack_require__(1);var Transform=__webpack_require__(5);var Rot=__webpack_require__(3);var Vec2=__webpack_require__(0);var AABB=__webpack_require__(17);var Settings=__webpack_require__(4);var Manifold=__webpack_require__(19);var Contact=__webpack_require__(18);var Shape=__webpack_require__(16);var PolygonShape=__webpack_require__(21);module.exports=CollidePolygons;Contact.addType(PolygonShape.TYPE,PolygonShape.TYPE,PolygonContact);function PolygonContact(manifold,xfA,fixtureA,indexA,xfB,fixtureB,indexB){_ASSERT&&common.assert(fixtureA.getType()==PolygonShape.TYPE);_ASSERT&&common.assert(fixtureB.getType()==PolygonShape.TYPE);CollidePolygons(manifold,fixtureA.getShape(),xfA,fixtureB.getShape(),xfB)}function FindMaxSeparation(poly1,xf1,poly2,xf2){var count1=poly1.m_count;var count2=poly2.m_count;var n1s=poly1.m_normals;var v1s=poly1.m_vertices;var v2s=poly2.m_vertices;var xf=Transform.mulTXf(xf2,xf1);var bestIndex=0;var maxSeparation=-Infinity;for(var i=0;imaxSeparation){maxSeparation=si;bestIndex=i}}FindMaxSeparation._maxSeparation=maxSeparation;FindMaxSeparation._bestIndex=bestIndex}function FindIncidentEdge(c,poly1,xf1,edge1,poly2,xf2){var normals1=poly1.m_normals;var count2=poly2.m_count;var vertices2=poly2.m_vertices;var normals2=poly2.m_normals;_ASSERT&&common.assert(edge1>=0&&edge1totalRadius)return;FindMaxSeparation(polyB,xfB,polyA,xfA);var edgeB=FindMaxSeparation._bestIndex;var separationB=FindMaxSeparation._maxSeparation;if(separationB>totalRadius)return;var poly1;var poly2;var xf1;var xf2;var edge1;var flip;var k_tol=0.1*Settings.linearSlop;if(separationB>separationA+k_tol){poly1=polyB;poly2=polyA;xf1=xfB;xf2=xfA;edge1=edgeB;manifold.type=Manifold.e_faceB;flip=1}else{poly1=polyA;poly2=polyB;xf1=xfA;xf2=xfB;edge1=edgeA;manifold.type=Manifold.e_faceA;flip=0}var incidentEdge=[new Manifold.clipVertex,new Manifold.clipVertex];FindIncidentEdge(incidentEdge,poly1,xf1,edge1,poly2,xf2);var count1=poly1.m_count;var vertices1=poly1.m_vertices;var iv1=edge1;var iv2=edge1+1radius){return}if(s>separation){separation=s;normalIndex=i}}var vertIndex1=normalIndex;var vertIndex2=vertIndex1+1radius*radius){return}manifold.pointCount=1;manifold.type=Manifold.e_faceA;manifold.localNormal.setCombine(1,cLocal,-1,v1);manifold.localNormal.normalize();manifold.localPoint=v1;manifold.points[0].localPoint.set(circleB.m_p);manifold.points[0].id.cf.indexA=0;manifold.points[0].id.cf.typeA=Manifold.e_vertex;manifold.points[0].id.cf.indexB=0;manifold.points[0].id.cf.typeB=Manifold.e_vertex}else if(u2<=0){if(Vec2.distanceSquared(cLocal,v2)>radius*radius){return}manifold.pointCount=1;manifold.type=Manifold.e_faceA;manifold.localNormal.setCombine(1,cLocal,-1,v2);manifold.localNormal.normalize();manifold.localPoint.set(v2);manifold.points[0].localPoint.set(circleB.m_p);manifold.points[0].id.cf.indexA=0;manifold.points[0].id.cf.typeA=Manifold.e_vertex;manifold.points[0].id.cf.indexB=0;manifold.points[0].id.cf.typeB=Manifold.e_vertex}else{var faceCenter=Vec2.mid(v1,v2);var separation=Vec2.dot(cLocal,normals[vertIndex1])-Vec2.dot(faceCenter,normals[vertIndex1]);if(separation>radius){return}manifold.pointCount=1;manifold.type=Manifold.e_faceA;manifold.localNormal.set(normals[vertIndex1]);manifold.localPoint.set(faceCenter);manifold.points[0].localPoint.set(circleB.m_p);manifold.points[0].id.cf.indexA=0;manifold.points[0].id.cf.typeA=Manifold.e_vertex;manifold.points[0].id.cf.indexB=0;manifold.points[0].id.cf.typeB=Manifold.e_vertex}}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;var common=__webpack_require__(2);var create=__webpack_require__(6);var Math=__webpack_require__(1);var Transform=__webpack_require__(5);var Vec2=__webpack_require__(0);var Rot=__webpack_require__(3);var Settings=__webpack_require__(4);var Shape=__webpack_require__(16);var Contact=__webpack_require__(18);var Manifold=__webpack_require__(19);var EdgeShape=__webpack_require__(24);var ChainShape=__webpack_require__(28);var PolygonShape=__webpack_require__(21);Contact.addType(EdgeShape.TYPE,PolygonShape.TYPE,EdgePolygonContact);Contact.addType(ChainShape.TYPE,PolygonShape.TYPE,ChainPolygonContact);function EdgePolygonContact(manifold,xfA,fA,indexA,xfB,fB,indexB){_ASSERT&&common.assert(fA.getType()==EdgeShape.TYPE);_ASSERT&&common.assert(fB.getType()==PolygonShape.TYPE);CollideEdgePolygon(manifold,fA.getShape(),xfA,fB.getShape(),xfB)}function ChainPolygonContact(manifold,xfA,fA,indexA,xfB,fB,indexB){_ASSERT&&common.assert(fA.getType()==ChainShape.TYPE);_ASSERT&&common.assert(fB.getType()==PolygonShape.TYPE);var chain=fA.getShape();var edge=new EdgeShape;chain.getChildEdge(edge,indexA);CollideEdgePolygon(manifold,edge,xfA,fB.getShape(),xfB)}var e_unknown=-1;var e_edgeA=1;var e_edgeB=2;var e_isolated=0;var e_concave=1;var e_convex=2;function EPAxis(){this.type;this.index;this.separation}function TempPolygon(){this.vertices=[];this.normals=[];this.count=0}function ReferenceFace(){this.i1,this.i2;this.v1,this.v2;this.normal=Vec2.zero();this.sideNormal1=Vec2.zero();this.sideOffset1;this.sideNormal2=Vec2.zero();this.sideOffset2}var edgeAxis=new EPAxis;var polygonAxis=new EPAxis;var polygonBA=new TempPolygon;var rf=new ReferenceFace;function CollideEdgePolygon(manifold,edgeA,xfA,polygonB,xfB){var m_type1,m_type2;var xf=Transform.mulTXf(xfA,xfB);var centroidB=Transform.mulVec2(xf,polygonB.m_centroid);var v0=edgeA.m_vertex0;var v1=edgeA.m_vertex1;var v2=edgeA.m_vertex2;var v3=edgeA.m_vertex3;var hasVertex0=edgeA.m_hasVertex0;var hasVertex3=edgeA.m_hasVertex3;var edge1=Vec2.sub(v2,v1);edge1.normalize();var normal1=Vec2.neo(edge1.y,-edge1.x);var offset1=Vec2.dot(normal1,Vec2.sub(centroidB,v1));var offset0=0;var offset2=0;var convex1=false;var convex2=false;if(hasVertex0){var edge0=Vec2.sub(v1,v0);edge0.normalize();var normal0=Vec2.neo(edge0.y,-edge0.x);convex1=Vec2.cross(edge0,edge1)>=0;offset0=Vec2.dot(normal0,centroidB)-Vec2.dot(normal0,v0)}if(hasVertex3){var edge2=Vec2.sub(v3,v2);edge2.normalize();var normal2=Vec2.neo(edge2.y,-edge2.x);convex2=Vec2.cross(edge1,edge2)>0;offset2=Vec2.dot(normal2,centroidB)-Vec2.dot(normal2,v2)}var front;var normal=Vec2.zero();var lowerLimit=Vec2.zero();var upperLimit=Vec2.zero();if(hasVertex0&&hasVertex3){if(convex1&&convex2){front=offset0>=0||offset1>=0||offset2>=0;if(front){normal.set(normal1);lowerLimit.set(normal0);upperLimit.set(normal2)}else{normal.setMul(-1,normal1);lowerLimit.setMul(-1,normal1);upperLimit.setMul(-1,normal1)}}else if(convex1){front=offset0>=0||offset1>=0&&offset2>=0;if(front){normal.set(normal1);lowerLimit.set(normal0);upperLimit.set(normal1)}else{normal.setMul(-1,normal1);lowerLimit.setMul(-1,normal2);upperLimit.setMul(-1,normal1)}}else if(convex2){front=offset2>=0||offset0>=0&&offset1>=0;if(front){normal.set(normal1);lowerLimit.set(normal1);upperLimit.set(normal2)}else{normal.setMul(-1,normal1);lowerLimit.setMul(-1,normal1);upperLimit.setMul(-1,normal0)}}else{front=offset0>=0&&offset1>=0&&offset2>=0;if(front){normal.set(normal1);lowerLimit.set(normal1);upperLimit.set(normal1)}else{normal.setMul(-1,normal1);lowerLimit.setMul(-1,normal2);upperLimit.setMul(-1,normal0)}}}else if(hasVertex0){if(convex1){front=offset0>=0||offset1>=0;if(front){normal.set(normal1);lowerLimit.set(normal0);upperLimit.setMul(-1,normal1)}else{normal.setMul(-1,normal1);lowerLimit.set(normal1);upperLimit.setMul(-1,normal1)}}else{front=offset0>=0&&offset1>=0;if(front){normal.set(normal1);lowerLimit.set(normal1);upperLimit.setMul(-1,normal1)}else{normal.setMul(-1,normal1);lowerLimit.set(normal1);upperLimit.setMul(-1,normal0)}}}else if(hasVertex3){if(convex2){front=offset1>=0||offset2>=0;if(front){normal.set(normal1);lowerLimit.setMul(-1,normal1);upperLimit.set(normal2)}else{normal.setMul(-1,normal1);lowerLimit.setMul(-1,normal1);upperLimit.set(normal1)}}else{front=offset1>=0&&offset2>=0;if(front){normal.set(normal1);lowerLimit.setMul(-1,normal1);upperLimit.set(normal1)}else{normal.setMul(-1,normal1);lowerLimit.setMul(-1,normal2);upperLimit.set(normal1)}}}else{front=offset1>=0;if(front){normal.set(normal1);lowerLimit.setMul(-1,normal1);upperLimit.setMul(-1,normal1)}else{normal.setMul(-1,normal1);lowerLimit.set(normal1);upperLimit.set(normal1)}}polygonBA.count=polygonB.m_count;for(var i=0;iradius){return}{polygonAxis.type=e_unknown;polygonAxis.index=-1;polygonAxis.separation=-Infinity;var perp=Vec2.neo(-normal.y,normal.x);for(var i=0;iradius){polygonAxis.type=e_edgeB;polygonAxis.index=i;polygonAxis.separation=s;break}if(Vec2.dot(n,perp)>=0){if(Vec2.dot(Vec2.sub(n,upperLimit),normal)<-Settings.angularSlop){continue}}else{if(Vec2.dot(Vec2.sub(n,lowerLimit),normal)<-Settings.angularSlop){continue}}if(s>polygonAxis.separation){polygonAxis.type=e_edgeB;polygonAxis.index=i;polygonAxis.separation=s}}}if(polygonAxis.type!=e_unknown&&polygonAxis.separation>radius){return}var k_relativeTol=0.98;var k_absoluteTol=0.001;var primaryAxis;if(polygonAxis.type==e_unknown){primaryAxis=edgeAxis}else if(polygonAxis.separation>k_relativeTol*edgeAxis.separation+k_absoluteTol){primaryAxis=polygonAxis}else{primaryAxis=edgeAxis}var ie=[new Manifold.clipVertex,new Manifold.clipVertex];if(primaryAxis.type==e_edgeA){manifold.type=Manifold.e_faceA;var bestIndex=0;var bestValue=Vec2.dot(normal,polygonBA.normals[0]);for(var i=1;i0){this.m_length=+def.length}else if(def.length<0){}else if(def.anchorA||def.anchorA||def.anchorA||def.anchorA){this.m_length=Vec2.distance(this.m_bodyA.getWorldPoint(this.m_localAnchorA),this.m_bodyB.getWorldPoint(this.m_localAnchorB))}};DistanceJoint.prototype.getLocalAnchorA=function(){return this.m_localAnchorA};DistanceJoint.prototype.getLocalAnchorB=function(){return this.m_localAnchorB};DistanceJoint.prototype.setLength=function(length){this.m_length=length};DistanceJoint.prototype.getLength=function(){return this.m_length};DistanceJoint.prototype.setFrequency=function(hz){this.m_frequencyHz=hz};DistanceJoint.prototype.getFrequency=function(){return this.m_frequencyHz};DistanceJoint.prototype.setDampingRatio=function(ratio){this.m_dampingRatio=ratio};DistanceJoint.prototype.getDampingRatio=function(){return this.m_dampingRatio};DistanceJoint.prototype.getAnchorA=function(){return this.m_bodyA.getWorldPoint(this.m_localAnchorA)};DistanceJoint.prototype.getAnchorB=function(){return this.m_bodyB.getWorldPoint(this.m_localAnchorB)};DistanceJoint.prototype.getReactionForce=function(inv_dt){return Vec2.mul(this.m_impulse,this.m_u).mul(inv_dt)};DistanceJoint.prototype.getReactionTorque=function(inv_dt){return 0};DistanceJoint.prototype.initVelocityConstraints=function(step){this.m_localCenterA=this.m_bodyA.m_sweep.localCenter;this.m_localCenterB=this.m_bodyB.m_sweep.localCenter;this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var qA=Rot.neo(aA);var qB=Rot.neo(aB);this.m_rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));this.m_rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));this.m_u=Vec2.sub(Vec2.add(cB,this.m_rB),Vec2.add(cA,this.m_rA));var length=this.m_u.length();if(length>Settings.linearSlop){this.m_u.mul(1/length)}else{this.m_u.set(0,0)}var crAu=Vec2.cross(this.m_rA,this.m_u);var crBu=Vec2.cross(this.m_rB,this.m_u);var invMass=this.m_invMassA+this.m_invIA*crAu*crAu+this.m_invMassB+this.m_invIB*crBu*crBu;this.m_mass=invMass!=0?1/invMass:0;if(this.m_frequencyHz>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;var h=step.dt;this.m_gamma=h*(d+h*k);this.m_gamma=this.m_gamma!=0?1/this.m_gamma:0;this.m_bias=C*h*k*this.m_gamma;invMass+=this.m_gamma;this.m_mass=invMass!=0?1/invMass:0}else{this.m_gamma=0;this.m_bias=0}if(step.warmStarting){this.m_impulse*=step.dtRatio;var P=Vec2.mul(this.m_impulse,this.m_u);vA.subMul(this.m_invMassA,P);wA-=this.m_invIA*Vec2.cross(this.m_rA,P);vB.addMul(this.m_invMassB,P);wB+=this.m_invIB*Vec2.cross(this.m_rB,P)}else{this.m_impulse=0}this.m_bodyA.c_velocity.v.set(vA);this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v.set(vB);this.m_bodyB.c_velocity.w=wB};DistanceJoint.prototype.solveVelocityConstraints=function(step){var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var vpA=Vec2.add(vA,Vec2.cross(wA,this.m_rA));var vpB=Vec2.add(vB,Vec2.cross(wB,this.m_rB));var Cdot=Vec2.dot(this.m_u,vpB)-Vec2.dot(this.m_u,vpA);var impulse=-this.m_mass*(Cdot+this.m_bias+this.m_gamma*this.m_impulse);this.m_impulse+=impulse;var P=Vec2.mul(impulse,this.m_u);vA.subMul(this.m_invMassA,P);wA-=this.m_invIA*Vec2.cross(this.m_rA,P);vB.addMul(this.m_invMassB,P);wB+=this.m_invIB*Vec2.cross(this.m_rB,P);this.m_bodyA.c_velocity.v.set(vA);this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v.set(vB);this.m_bodyB.c_velocity.w=wB};DistanceJoint.prototype.solvePositionConstraints=function(step){if(this.m_frequencyHz>0){return true}var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var rA=Rot.mulSub(qA,this.m_localAnchorA,this.m_localCenterA);var rB=Rot.mulSub(qB,this.m_localAnchorB,this.m_localCenterB);var u=Vec2.sub(Vec2.add(cB,rB),Vec2.add(cA,rA));var length=u.normalize();var C=length-this.m_length;C=Math.clamp(C,-Settings.maxLinearCorrection,Settings.maxLinearCorrection);var impulse=-this.m_mass*C;var P=Vec2.mul(impulse,u);cA.subMul(this.m_invMassA,P);aA-=this.m_invIA*Vec2.cross(rA,P);cB.addMul(this.m_invMassB,P);aB+=this.m_invIB*Vec2.cross(rB,P);this.m_bodyA.c_position.c.set(cA);this.m_bodyA.c_position.a=aA;this.m_bodyB.c_position.c.set(cB);this.m_bodyB.c_position.a=aB;return Math.abs(C)=0);this.m_maxForce=force};FrictionJoint.prototype.getMaxForce=function(){return this.m_maxForce};FrictionJoint.prototype.setMaxTorque=function(torque){_ASSERT&&common.assert(Math.isFinite(torque)&&torque>=0);this.m_maxTorque=torque};FrictionJoint.prototype.getMaxTorque=function(){return this.m_maxTorque};FrictionJoint.prototype.getAnchorA=function(){return this.m_bodyA.getWorldPoint(this.m_localAnchorA)};FrictionJoint.prototype.getAnchorB=function(){return this.m_bodyB.getWorldPoint(this.m_localAnchorB)};FrictionJoint.prototype.getReactionForce=function(inv_dt){return Vec2.mul(inv_dt,this.m_linearImpulse)};FrictionJoint.prototype.getReactionTorque=function(inv_dt){return inv_dt*this.m_angularImpulse};FrictionJoint.prototype.initVelocityConstraints=function(step){this.m_localCenterA=this.m_bodyA.m_sweep.localCenter;this.m_localCenterB=this.m_bodyB.m_sweep.localCenter;this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var aA=this.m_bodyA.c_position.a;var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var aB=this.m_bodyB.c_position.a;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var qA=Rot.neo(aA);var qB=Rot.neo(aB);this.m_rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));this.m_rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var K=new Mat22;K.ex.x=mA+mB+iA*this.m_rA.y*this.m_rA.y+iB*this.m_rB.y*this.m_rB.y;K.ex.y=-iA*this.m_rA.x*this.m_rA.y-iB*this.m_rB.x*this.m_rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*this.m_rA.x*this.m_rA.x+iB*this.m_rB.x*this.m_rB.x;this.m_linearMass=K.getInverse();this.m_angularMass=iA+iB;if(this.m_angularMass>0){this.m_angularMass=1/this.m_angularMass}if(step.warmStarting){this.m_linearImpulse.mul(step.dtRatio);this.m_angularImpulse*=step.dtRatio;var P=Vec2.neo(this.m_linearImpulse.x,this.m_linearImpulse.y);vA.subMul(mA,P);wA-=iA*(Vec2.cross(this.m_rA,P)+this.m_angularImpulse);vB.addMul(mB,P);wB+=iB*(Vec2.cross(this.m_rB,P)+this.m_angularImpulse)}else{this.m_linearImpulse.setZero();this.m_angularImpulse=0}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};FrictionJoint.prototype.solveVelocityConstraints=function(step){var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var h=step.dt;{var Cdot=wB-wA;var impulse=-this.m_angularMass*Cdot;var oldImpulse=this.m_angularImpulse;var maxImpulse=h*this.m_maxTorque;this.m_angularImpulse=Math.clamp(this.m_angularImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_angularImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse}{var Cdot=Vec2.sub(Vec2.add(vB,Vec2.cross(wB,this.m_rB)),Vec2.add(vA,Vec2.cross(wA,this.m_rA)));var impulse=Vec2.neg(Mat22.mulVec2(this.m_linearMass,Cdot));var oldImpulse=this.m_linearImpulse;this.m_linearImpulse.add(impulse);var maxImpulse=h*this.m_maxForce;if(this.m_linearImpulse.lengthSquared()>maxImpulse*maxImpulse){this.m_linearImpulse.normalize();this.m_linearImpulse.mul(maxImpulse)}impulse=Vec2.sub(this.m_linearImpulse,oldImpulse);vA.subMul(mA,impulse);wA-=iA*Vec2.cross(this.m_rA,impulse);vB.addMul(mB,impulse);wB+=iB*Vec2.cross(this.m_rB,impulse)}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};FrictionJoint.prototype.solvePositionConstraints=function(step){return true}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=GearJoint;var common=__webpack_require__(2);var options=__webpack_require__(7);var create=__webpack_require__(6);var Settings=__webpack_require__(4);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var Vec3=__webpack_require__(11);var Mat22=__webpack_require__(10);var Mat33=__webpack_require__(15);var Rot=__webpack_require__(3);var Sweep=__webpack_require__(9);var Transform=__webpack_require__(5);var Velocity=__webpack_require__(13);var Position=__webpack_require__(14);var Joint=__webpack_require__(12);var Body=__webpack_require__(8);var RevoluteJoint=__webpack_require__(34);var PrismaticJoint=__webpack_require__(35);GearJoint.TYPE="gear-joint";Joint.TYPES[GearJoint.TYPE]=GearJoint;GearJoint._super=Joint;GearJoint.prototype=create(GearJoint._super.prototype);var DEFAULTS={ratio:1};function GearJoint(def,bodyA,bodyB,joint1,joint2,ratio){if(!(this instanceof GearJoint)){return new GearJoint(def,bodyA,bodyB,joint1,joint2,ratio)}def=options(def,DEFAULTS);Joint.call(this,def,bodyA,bodyB);bodyA=this.m_bodyA;bodyB=this.m_bodyB;this.m_type=GearJoint.TYPE;_ASSERT&&common.assert(joint1.m_type===RevoluteJoint.TYPE||joint1.m_type===PrismaticJoint.TYPE);_ASSERT&&common.assert(joint2.m_type===RevoluteJoint.TYPE||joint2.m_type===PrismaticJoint.TYPE);this.m_joint1=joint1||def.joint1;this.m_joint2=joint2||def.joint2;this.m_ratio=Math.isFinite(ratio)?ratio:def.ratio;this.m_type1=this.m_joint1.getType();this.m_type2=this.m_joint2.getType();var coordinateA,coordinateB;this.m_bodyC=this.m_joint1.getBodyA();this.m_bodyA=this.m_joint1.getBodyB();var xfA=this.m_bodyA.m_xf;var aA=this.m_bodyA.m_sweep.a;var xfC=this.m_bodyC.m_xf;var aC=this.m_bodyC.m_sweep.a;if(this.m_type1===RevoluteJoint.TYPE){var revolute=this.m_joint1;this.m_localAnchorC=revolute.m_localAnchorA;this.m_localAnchorA=revolute.m_localAnchorB;this.m_referenceAngleA=revolute.m_referenceAngle;this.m_localAxisC=Vec2.zero();coordinateA=aA-aC-this.m_referenceAngleA}else{var prismatic=this.m_joint1;this.m_localAnchorC=prismatic.m_localAnchorA;this.m_localAnchorA=prismatic.m_localAnchorB;this.m_referenceAngleA=prismatic.m_referenceAngle;this.m_localAxisC=prismatic.m_localXAxisA;var pC=this.m_localAnchorC;var pA=Rot.mulTVec2(xfC.q,Vec2.add(Rot.mul(xfA.q,this.m_localAnchorA),Vec2.sub(xfA.p,xfC.p)));coordinateA=Vec2.dot(pA,this.m_localAxisC)-Vec2.dot(pC,this.m_localAxisC)}this.m_bodyD=this.m_joint2.getBodyA();this.m_bodyB=this.m_joint2.getBodyB();var xfB=this.m_bodyB.m_xf;var aB=this.m_bodyB.m_sweep.a;var xfD=this.m_bodyD.m_xf;var aD=this.m_bodyD.m_sweep.a;if(this.m_type2===RevoluteJoint.TYPE){var revolute=this.m_joint2;this.m_localAnchorD=revolute.m_localAnchorA;this.m_localAnchorB=revolute.m_localAnchorB;this.m_referenceAngleB=revolute.m_referenceAngle;this.m_localAxisD=Vec2.zero();coordinateB=aB-aD-this.m_referenceAngleB}else{var prismatic=this.m_joint2;this.m_localAnchorD=prismatic.m_localAnchorA;this.m_localAnchorB=prismatic.m_localAnchorB;this.m_referenceAngleB=prismatic.m_referenceAngle;this.m_localAxisD=prismatic.m_localXAxisA;var pD=this.m_localAnchorD;var pB=Rot.mulTVec2(xfD.q,Vec2.add(Rot.mul(xfB.q,this.m_localAnchorB),Vec2.sub(xfB.p,xfD.p)));coordinateB=Vec2.dot(pB,this.m_localAxisD)-Vec2.dot(pD,this.m_localAxisD)}this.m_constant=coordinateA+this.m_ratio*coordinateB;this.m_impulse=0;this.m_lcA,this.m_lcB,this.m_lcC,this.m_lcD;this.m_mA,this.m_mB,this.m_mC,this.m_mD;this.m_iA,this.m_iB,this.m_iC,this.m_iD;this.m_JvAC,this.m_JvBD;this.m_JwA,this.m_JwB,this.m_JwC,this.m_JwD;this.m_mass}GearJoint.prototype._serialize=function(){return{type:this.m_type,bodyA:this.m_bodyA,bodyB:this.m_bodyB,collideConnected:this.m_collideConnected,joint1:this.m_joint1,joint2:this.m_joint2,ratio:this.m_ratio,_constant:this.m_constant}};GearJoint._deserialize=function(data,world,restore){data.bodyA=restore(Body,data.bodyA,world);data.bodyB=restore(Body,data.bodyB,world);data.joint1=restore(Joint,data.joint1,world);data.joint2=restore(Joint,data.joint2,world);var joint=new GearJoint(data);if(data._constant)joint.m_constant=data._constant;return joint};GearJoint.prototype.getJoint1=function(){return this.m_joint1};GearJoint.prototype.getJoint2=function(){return this.m_joint2};GearJoint.prototype.setRatio=function(ratio){_ASSERT&&common.assert(Math.isFinite(ratio));this.m_ratio=ratio};GearJoint.prototype.getRatio=function(){return this.m_ratio};GearJoint.prototype.getAnchorA=function(){return this.m_bodyA.getWorldPoint(this.m_localAnchorA)};GearJoint.prototype.getAnchorB=function(){return this.m_bodyB.getWorldPoint(this.m_localAnchorB)};GearJoint.prototype.getReactionForce=function(inv_dt){return Vec2.mul(this.m_impulse,this.m_JvAC).mul(inv_dt)};GearJoint.prototype.getReactionTorque=function(inv_dt){var L=this.m_impulse*this.m_JwA;return inv_dt*L};GearJoint.prototype.initVelocityConstraints=function(step){this.m_lcA=this.m_bodyA.m_sweep.localCenter;this.m_lcB=this.m_bodyB.m_sweep.localCenter;this.m_lcC=this.m_bodyC.m_sweep.localCenter;this.m_lcD=this.m_bodyD.m_sweep.localCenter;this.m_mA=this.m_bodyA.m_invMass;this.m_mB=this.m_bodyB.m_invMass;this.m_mC=this.m_bodyC.m_invMass;this.m_mD=this.m_bodyD.m_invMass;this.m_iA=this.m_bodyA.m_invI;this.m_iB=this.m_bodyB.m_invI;this.m_iC=this.m_bodyC.m_invI;this.m_iD=this.m_bodyD.m_invI;var aA=this.m_bodyA.c_position.a;var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var aB=this.m_bodyB.c_position.a;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var aC=this.m_bodyC.c_position.a;var vC=this.m_bodyC.c_velocity.v;var wC=this.m_bodyC.c_velocity.w;var aD=this.m_bodyD.c_position.a;var vD=this.m_bodyD.c_velocity.v;var wD=this.m_bodyD.c_velocity.w;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var qC=Rot.neo(aC);var qD=Rot.neo(aD);this.m_mass=0;if(this.m_type1==RevoluteJoint.TYPE){this.m_JvAC=Vec2.zero();this.m_JwA=1;this.m_JwC=1;this.m_mass+=this.m_iA+this.m_iC}else{var u=Rot.mulVec2(qC,this.m_localAxisC);var rC=Rot.mulSub(qC,this.m_localAnchorC,this.m_lcC);var rA=Rot.mulSub(qA,this.m_localAnchorA,this.m_lcA);this.m_JvAC=u;this.m_JwC=Vec2.cross(rC,u);this.m_JwA=Vec2.cross(rA,u);this.m_mass+=this.m_mC+this.m_mA+this.m_iC*this.m_JwC*this.m_JwC+this.m_iA*this.m_JwA*this.m_JwA}if(this.m_type2==RevoluteJoint.TYPE){this.m_JvBD=Vec2.zero();this.m_JwB=this.m_ratio;this.m_JwD=this.m_ratio;this.m_mass+=this.m_ratio*this.m_ratio*(this.m_iB+this.m_iD)}else{var u=Rot.mulVec2(qD,this.m_localAxisD);var rD=Rot.mulSub(qD,this.m_localAnchorD,this.m_lcD);var rB=Rot.mulSub(qB,this.m_localAnchorB,this.m_lcB);this.m_JvBD=Vec2.mul(this.m_ratio,u);this.m_JwD=this.m_ratio*Vec2.cross(rD,u);this.m_JwB=this.m_ratio*Vec2.cross(rB,u);this.m_mass+=this.m_ratio*this.m_ratio*(this.m_mD+this.m_mB)+this.m_iD*this.m_JwD*this.m_JwD+this.m_iB*this.m_JwB*this.m_JwB}this.m_mass=this.m_mass>0?1/this.m_mass:0;if(step.warmStarting){vA.addMul(this.m_mA*this.m_impulse,this.m_JvAC);wA+=this.m_iA*this.m_impulse*this.m_JwA;vB.addMul(this.m_mB*this.m_impulse,this.m_JvBD);wB+=this.m_iB*this.m_impulse*this.m_JwB;vC.subMul(this.m_mC*this.m_impulse,this.m_JvAC);wC-=this.m_iC*this.m_impulse*this.m_JwC;vD.subMul(this.m_mD*this.m_impulse,this.m_JvBD);wD-=this.m_iD*this.m_impulse*this.m_JwD}else{this.m_impulse=0}this.m_bodyA.c_velocity.v.set(vA);this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v.set(vB);this.m_bodyB.c_velocity.w=wB;this.m_bodyC.c_velocity.v.set(vC);this.m_bodyC.c_velocity.w=wC;this.m_bodyD.c_velocity.v.set(vD);this.m_bodyD.c_velocity.w=wD};GearJoint.prototype.solveVelocityConstraints=function(step){var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var vC=this.m_bodyC.c_velocity.v;var wC=this.m_bodyC.c_velocity.w;var vD=this.m_bodyD.c_velocity.v;var wD=this.m_bodyD.c_velocity.w;var Cdot=Vec2.dot(this.m_JvAC,vA)-Vec2.dot(this.m_JvAC,vC)+Vec2.dot(this.m_JvBD,vB)-Vec2.dot(this.m_JvBD,vD);Cdot+=this.m_JwA*wA-this.m_JwC*wC+(this.m_JwB*wB-this.m_JwD*wD);var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;vA.addMul(this.m_mA*impulse,this.m_JvAC);wA+=this.m_iA*impulse*this.m_JwA;vB.addMul(this.m_mB*impulse,this.m_JvBD);wB+=this.m_iB*impulse*this.m_JwB;vC.subMul(this.m_mC*impulse,this.m_JvAC);wC-=this.m_iC*impulse*this.m_JwC;vD.subMul(this.m_mD*impulse,this.m_JvBD);wD-=this.m_iD*impulse*this.m_JwD;this.m_bodyA.c_velocity.v.set(vA);this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v.set(vB);this.m_bodyB.c_velocity.w=wB;this.m_bodyC.c_velocity.v.set(vC);this.m_bodyC.c_velocity.w=wC;this.m_bodyD.c_velocity.v.set(vD);this.m_bodyD.c_velocity.w=wD};GearJoint.prototype.solvePositionConstraints=function(step){var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var cC=this.m_bodyC.c_position.c;var aC=this.m_bodyC.c_position.a;var cD=this.m_bodyD.c_position.c;var aD=this.m_bodyD.c_position.a;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var qC=Rot.neo(aC);var qD=Rot.neo(aD);var linearError=0;var coordinateA,coordinateB;var JvAC,JvBD;var JwA,JwB,JwC,JwD;var mass=0;if(this.m_type1==RevoluteJoint.TYPE){JvAC=Vec2.zero();JwA=1;JwC=1;mass+=this.m_iA+this.m_iC;coordinateA=aA-aC-this.m_referenceAngleA}else{var u=Rot.mulVec2(qC,this.m_localAxisC);var rC=Rot.mulSub(qC,this.m_localAnchorC,this.m_lcC);var rA=Rot.mulSub(qA,this.m_localAnchorA,this.m_lcA);JvAC=u;JwC=Vec2.cross(rC,u);JwA=Vec2.cross(rA,u);mass+=this.m_mC+this.m_mA+this.m_iC*JwC*JwC+this.m_iA*JwA*JwA;var pC=Vec2.sub(this.m_localAnchorC,this.m_lcC);var pA=Rot.mulTVec2(qC,Vec2.add(rA,Vec2.sub(cA,cC)));coordinateA=Vec2.dot(Vec2.sub(pA,pC),this.m_localAxisC)}if(this.m_type2==RevoluteJoint.TYPE){JvBD=Vec2.zero();JwB=this.m_ratio;JwD=this.m_ratio;mass+=this.m_ratio*this.m_ratio*(this.m_iB+this.m_iD);coordinateB=aB-aD-this.m_referenceAngleB}else{var u=Rot.mulVec2(qD,this.m_localAxisD);var rD=Rot.mulSub(qD,this.m_localAnchorD,this.m_lcD);var rB=Rot.mulSub(qB,this.m_localAnchorB,this.m_lcB);JvBD=Vec2.mul(this.m_ratio,u);JwD=this.m_ratio*Vec2.cross(rD,u);JwB=this.m_ratio*Vec2.cross(rB,u);mass+=this.m_ratio*this.m_ratio*(this.m_mD+this.m_mB)+this.m_iD*JwD*JwD+this.m_iB*JwB*JwB;var pD=Vec2.sub(this.m_localAnchorD,this.m_lcD);var pB=Rot.mulTVec2(qD,Vec2.add(rB,Vec2.sub(cB,cD)));coordinateB=Vec2.dot(pB,this.m_localAxisD)-Vec2.dot(pD,this.m_localAxisD)}var C=coordinateA+this.m_ratio*coordinateB-this.m_constant;var impulse=0;if(mass>0){impulse=-C/mass}cA.addMul(this.m_mA*impulse,JvAC);aA+=this.m_iA*impulse*JwA;cB.addMul(this.m_mB*impulse,JvBD);aB+=this.m_iB*impulse*JwB;cC.subMul(this.m_mC*impulse,JvAC);aC-=this.m_iC*impulse*JwC;cD.subMul(this.m_mD*impulse,JvBD);aD-=this.m_iD*impulse*JwD;this.m_bodyA.c_position.c.set(cA);this.m_bodyA.c_position.a=aA;this.m_bodyB.c_position.c.set(cB);this.m_bodyB.c_position.a=aB;this.m_bodyC.c_position.c.set(cC);this.m_bodyC.c_position.a=aC;this.m_bodyD.c_position.c.set(cD);this.m_bodyD.c_position.a=aD;return linearError=0);this.m_maxForce=force};MotorJoint.prototype.getMaxForce=function(){return this.m_maxForce};MotorJoint.prototype.setMaxTorque=function(torque){_ASSERT&&common.assert(Math.isFinite(torque)&&torque>=0);this.m_maxTorque=torque};MotorJoint.prototype.getMaxTorque=function(){return this.m_maxTorque};MotorJoint.prototype.setCorrectionFactor=function(factor){_ASSERT&&common.assert(Math.isFinite(factor)&&factor>=0&&factor<=1);this.m_correctionFactor=factor};MotorJoint.prototype.getCorrectionFactor=function(){return this.m_correctionFactor};MotorJoint.prototype.setLinearOffset=function(linearOffset){if(linearOffset.x!=this.m_linearOffset.x||linearOffset.y!=this.m_linearOffset.y){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_linearOffset=linearOffset}};MotorJoint.prototype.getLinearOffset=function(){return this.m_linearOffset};MotorJoint.prototype.setAngularOffset=function(angularOffset){if(angularOffset!=this.m_angularOffset){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_angularOffset=angularOffset}};MotorJoint.prototype.getAngularOffset=function(){return this.m_angularOffset};MotorJoint.prototype.getAnchorA=function(){return this.m_bodyA.getPosition()};MotorJoint.prototype.getAnchorB=function(){return this.m_bodyB.getPosition()};MotorJoint.prototype.getReactionForce=function(inv_dt){return Vec2.mul(inv_dt,this.m_linearImpulse)};MotorJoint.prototype.getReactionTorque=function(inv_dt){return inv_dt*this.m_angularImpulse};MotorJoint.prototype.initVelocityConstraints=function(step){this.m_localCenterA=this.m_bodyA.m_sweep.localCenter;this.m_localCenterB=this.m_bodyB.m_sweep.localCenter;this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var qA=Rot.neo(aA);var qB=Rot.neo(aB);this.m_rA=Rot.mulVec2(qA,Vec2.neg(this.m_localCenterA));this.m_rB=Rot.mulVec2(qB,Vec2.neg(this.m_localCenterB));var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var K=new Mat22;K.ex.x=mA+mB+iA*this.m_rA.y*this.m_rA.y+iB*this.m_rB.y*this.m_rB.y;K.ex.y=-iA*this.m_rA.x*this.m_rA.y-iB*this.m_rB.x*this.m_rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*this.m_rA.x*this.m_rA.x+iB*this.m_rB.x*this.m_rB.x;this.m_linearMass=K.getInverse();this.m_angularMass=iA+iB;if(this.m_angularMass>0){this.m_angularMass=1/this.m_angularMass}this.m_linearError=Vec2.zero();this.m_linearError.addCombine(1,cB,1,this.m_rB);this.m_linearError.subCombine(1,cA,1,this.m_rA);this.m_linearError.sub(Rot.mulVec2(qA,this.m_linearOffset));this.m_angularError=aB-aA-this.m_angularOffset;if(step.warmStarting){this.m_linearImpulse.mul(step.dtRatio);this.m_angularImpulse*=step.dtRatio;var P=Vec2.neo(this.m_linearImpulse.x,this.m_linearImpulse.y);vA.subMul(mA,P);wA-=iA*(Vec2.cross(this.m_rA,P)+this.m_angularImpulse);vB.addMul(mB,P);wB+=iB*(Vec2.cross(this.m_rB,P)+this.m_angularImpulse)}else{this.m_linearImpulse.setZero();this.m_angularImpulse=0}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};MotorJoint.prototype.solveVelocityConstraints=function(step){var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var h=step.dt;var inv_h=step.inv_dt;{var Cdot=wB-wA+inv_h*this.m_correctionFactor*this.m_angularError;var impulse=-this.m_angularMass*Cdot;var oldImpulse=this.m_angularImpulse;var maxImpulse=h*this.m_maxTorque;this.m_angularImpulse=Math.clamp(this.m_angularImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_angularImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse}{var Cdot=Vec2.zero();Cdot.addCombine(1,vB,1,Vec2.cross(wB,this.m_rB));Cdot.subCombine(1,vA,1,Vec2.cross(wA,this.m_rA));Cdot.addMul(inv_h*this.m_correctionFactor,this.m_linearError);var impulse=Vec2.neg(Mat22.mulVec2(this.m_linearMass,Cdot));var oldImpulse=Vec2.clone(this.m_linearImpulse);this.m_linearImpulse.add(impulse);var maxImpulse=h*this.m_maxForce;this.m_linearImpulse.clamp(maxImpulse);impulse=Vec2.sub(this.m_linearImpulse,oldImpulse);vA.subMul(mA,impulse);wA-=iA*Vec2.cross(this.m_rA,impulse);vB.addMul(mB,impulse);wB+=iB*Vec2.cross(this.m_rB,impulse)}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};MotorJoint.prototype.solvePositionConstraints=function(step){return true}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=MouseJoint;var common=__webpack_require__(2);var options=__webpack_require__(7);var create=__webpack_require__(6);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var Vec3=__webpack_require__(11);var Mat22=__webpack_require__(10);var Mat33=__webpack_require__(15);var Rot=__webpack_require__(3);var Sweep=__webpack_require__(9);var Transform=__webpack_require__(5);var Velocity=__webpack_require__(13);var Position=__webpack_require__(14);var Joint=__webpack_require__(12);var Body=__webpack_require__(8);MouseJoint.TYPE="mouse-joint";Joint.TYPES[MouseJoint.TYPE]=MouseJoint;MouseJoint._super=Joint;MouseJoint.prototype=create(MouseJoint._super.prototype);var DEFAULTS={maxForce:0,frequencyHz:5,dampingRatio:0.7};function MouseJoint(def,bodyA,bodyB,target){if(!(this instanceof MouseJoint)){return new MouseJoint(def,bodyA,bodyB,target)}def=options(def,DEFAULTS);Joint.call(this,def,bodyA,bodyB);bodyA=this.m_bodyA;bodyB=this.m_bodyB;this.m_type=MouseJoint.TYPE;_ASSERT&&common.assert(Math.isFinite(def.maxForce)&&def.maxForce>=0);_ASSERT&&common.assert(Math.isFinite(def.frequencyHz)&&def.frequencyHz>=0);_ASSERT&&common.assert(Math.isFinite(def.dampingRatio)&&def.dampingRatio>=0);this.m_targetA=target?Vec2.clone(target):def.target||Vec2.zero();this.m_localAnchorB=Transform.mulTVec2(bodyB.getTransform(),this.m_targetA);this.m_maxForce=def.maxForce;this.m_impulse=Vec2.zero();this.m_frequencyHz=def.frequencyHz;this.m_dampingRatio=def.dampingRatio;this.m_beta=0;this.m_gamma=0;this.m_rB=Vec2.zero();this.m_localCenterB=Vec2.zero();this.m_invMassB=0;this.m_invIB=0;this.mass=new Mat22;this.m_C=Vec2.zero()}MouseJoint.prototype._serialize=function(){return{type:this.m_type,bodyA:this.m_bodyA,bodyB:this.m_bodyB,collideConnected:this.m_collideConnected,target:this.m_targetA,maxForce:this.m_maxForce,frequencyHz:this.m_frequencyHz,dampingRatio:this.m_dampingRatio,_localAnchorB:this.m_localAnchorB}};MouseJoint._deserialize=function(data,world,restore){data.bodyA=restore(Body,data.bodyA,world);data.bodyB=restore(Body,data.bodyB,world);data.target=Vec2(data.target);var joint=new MouseJoint(data);if(data._localAnchorB)joint.m_localAnchorB=data._localAnchorB;return joint};MouseJoint.prototype.setTarget=function(target){if(this.m_bodyB.isAwake()==false){this.m_bodyB.setAwake(true)}this.m_targetA=Vec2.clone(target)};MouseJoint.prototype.getTarget=function(){return this.m_targetA};MouseJoint.prototype.setMaxForce=function(force){this.m_maxForce=force};MouseJoint.getMaxForce=function(){return this.m_maxForce};MouseJoint.prototype.setFrequency=function(hz){this.m_frequencyHz=hz};MouseJoint.prototype.getFrequency=function(){return this.m_frequencyHz};MouseJoint.prototype.setDampingRatio=function(ratio){this.m_dampingRatio=ratio};MouseJoint.prototype.getDampingRatio=function(){return this.m_dampingRatio};MouseJoint.prototype.getAnchorA=function(){return Vec2.clone(this.m_targetA)};MouseJoint.prototype.getAnchorB=function(){return this.m_bodyB.getWorldPoint(this.m_localAnchorB)};MouseJoint.prototype.getReactionForce=function(inv_dt){return Vec2.mul(inv_dt,this.m_impulse)};MouseJoint.prototype.getReactionTorque=function(inv_dt){return inv_dt*0};MouseJoint.prototype.shiftOrigin=function(newOrigin){this.m_targetA.sub(newOrigin)};MouseJoint.prototype.initVelocityConstraints=function(step){this.m_localCenterB=this.m_bodyB.m_sweep.localCenter;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIB=this.m_bodyB.m_invI;var position=this.m_bodyB.c_position;var velocity=this.m_bodyB.c_velocity;var cB=position.c;var aB=position.a;var vB=velocity.v;var wB=velocity.w;var qB=Rot.neo(aB);var mass=this.m_bodyB.getMass();var omega=2*Math.PI*this.m_frequencyHz;var d=2*mass*this.m_dampingRatio*omega;var k=mass*(omega*omega);var h=step.dt;_ASSERT&&common.assert(d+h*k>Math.EPSILON);this.m_gamma=h*(d+h*k);if(this.m_gamma!=0){this.m_gamma=1/this.m_gamma}this.m_beta=h*k*this.m_gamma;this.m_rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var K=new Mat22;K.ex.x=this.m_invMassB+this.m_invIB*this.m_rB.y*this.m_rB.y+this.m_gamma;K.ex.y=-this.m_invIB*this.m_rB.x*this.m_rB.y;K.ey.x=K.ex.y;K.ey.y=this.m_invMassB+this.m_invIB*this.m_rB.x*this.m_rB.x+this.m_gamma;this.m_mass=K.getInverse();this.m_C.set(cB);this.m_C.addCombine(1,this.m_rB,-1,this.m_targetA);this.m_C.mul(this.m_beta);wB*=0.98;if(step.warmStarting){this.m_impulse.mul(step.dtRatio);vB.addMul(this.m_invMassB,this.m_impulse);wB+=this.m_invIB*Vec2.cross(this.m_rB,this.m_impulse)}else{this.m_impulse.setZero()}velocity.v.set(vB);velocity.w=wB};MouseJoint.prototype.solveVelocityConstraints=function(step){var velocity=this.m_bodyB.c_velocity;var vB=Vec2.clone(velocity.v);var wB=velocity.w;var Cdot=Vec2.cross(wB,this.m_rB);Cdot.add(vB);Cdot.addCombine(1,this.m_C,this.m_gamma,this.m_impulse);Cdot.neg();var impulse=Mat22.mulVec2(this.m_mass,Cdot);var oldImpulse=Vec2.clone(this.m_impulse);this.m_impulse.add(impulse);var maxImpulse=step.dt*this.m_maxForce;this.m_impulse.clamp(maxImpulse);impulse=Vec2.sub(this.m_impulse,oldImpulse);vB.addMul(this.m_invMassB,impulse);wB+=this.m_invIB*Vec2.cross(this.m_rB,impulse);velocity.v.set(vB);velocity.w=wB};MouseJoint.prototype.solvePositionConstraints=function(step){return true}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=PulleyJoint;var common=__webpack_require__(2);var options=__webpack_require__(7);var create=__webpack_require__(6);var Settings=__webpack_require__(4);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var Vec3=__webpack_require__(11);var Mat22=__webpack_require__(10);var Mat33=__webpack_require__(15);var Rot=__webpack_require__(3);var Sweep=__webpack_require__(9);var Transform=__webpack_require__(5);var Velocity=__webpack_require__(13);var Position=__webpack_require__(14);var Joint=__webpack_require__(12);var Body=__webpack_require__(8);PulleyJoint.TYPE="pulley-joint";PulleyJoint.MIN_PULLEY_LENGTH=2;Joint.TYPES[PulleyJoint.TYPE]=PulleyJoint;PulleyJoint._super=Joint;PulleyJoint.prototype=create(PulleyJoint._super.prototype);var PulleyJointDef={collideConnected:true};function PulleyJoint(def,bodyA,bodyB,groundA,groundB,anchorA,anchorB,ratio){if(!(this instanceof PulleyJoint)){return new PulleyJoint(def,bodyA,bodyB,groundA,groundB,anchorA,anchorB,ratio)}def=options(def,PulleyJointDef);Joint.call(this,def,bodyA,bodyB);bodyA=this.m_bodyA;bodyB=this.m_bodyB;this.m_type=PulleyJoint.TYPE;this.m_groundAnchorA=groundA||def.groundAnchorA||Vec2.neo(-1,1);this.m_groundAnchorB=groundB||def.groundAnchorB||Vec2.neo(1,1);this.m_localAnchorA=anchorA?bodyA.getLocalPoint(anchorA):def.localAnchorA||Vec2.neo(-1,0);this.m_localAnchorB=anchorB?bodyB.getLocalPoint(anchorB):def.localAnchorB||Vec2.neo(1,0);this.m_lengthA=Math.isFinite(def.lengthA)?def.lengthA:Vec2.distance(anchorA,groundA);this.m_lengthB=Math.isFinite(def.lengthB)?def.lengthB:Vec2.distance(anchorB,groundB);this.m_ratio=Math.isFinite(ratio)?ratio:def.ratio;_ASSERT&&common.assert(ratio>Math.EPSILON);this.m_constant=this.m_lengthA+this.m_ratio*this.m_lengthB;this.m_impulse=0;this.m_uA;this.m_uB;this.m_rA;this.m_rB;this.m_localCenterA;this.m_localCenterB;this.m_invMassA;this.m_invMassB;this.m_invIA;this.m_invIB;this.m_mass}PulleyJoint.prototype._serialize=function(){return{type:this.m_type,bodyA:this.m_bodyA,bodyB:this.m_bodyB,collideConnected:this.m_collideConnected,groundAnchorA:this.m_groundAnchorA,groundAnchorB:this.m_groundAnchorB,localAnchorA:this.m_localAnchorA,localAnchorB:this.m_localAnchorB,lengthA:this.m_lengthA,lengthB:this.m_lengthB,ratio:this.m_ratio}};PulleyJoint._deserialize=function(data,world,restore){data.bodyA=restore(Body,data.bodyA,world);data.bodyB=restore(Body,data.bodyB,world);var joint=new PulleyJoint(data);return joint};PulleyJoint.prototype.getGroundAnchorA=function(){return this.m_groundAnchorA};PulleyJoint.prototype.getGroundAnchorB=function(){return this.m_groundAnchorB};PulleyJoint.prototype.getLengthA=function(){return this.m_lengthA};PulleyJoint.prototype.getLengthB=function(){return this.m_lengthB};PulleyJoint.prototype.getRatio=function(){return this.m_ratio};PulleyJoint.prototype.getCurrentLengthA=function(){var p=this.m_bodyA.getWorldPoint(this.m_localAnchorA);var s=this.m_groundAnchorA;return Vec2.distance(p,s)};PulleyJoint.prototype.getCurrentLengthB=function(){var p=this.m_bodyB.getWorldPoint(this.m_localAnchorB);var s=this.m_groundAnchorB;return Vec2.distance(p,s)};PulleyJoint.prototype.shiftOrigin=function(newOrigin){this.m_groundAnchorA.sub(newOrigin);this.m_groundAnchorB.sub(newOrigin)};PulleyJoint.prototype.getAnchorA=function(){return this.m_bodyA.getWorldPoint(this.m_localAnchorA)};PulleyJoint.prototype.getAnchorB=function(){return this.m_bodyB.getWorldPoint(this.m_localAnchorB)};PulleyJoint.prototype.getReactionForce=function(inv_dt){return Vec2.mul(this.m_impulse,this.m_uB).mul(inv_dt)};PulleyJoint.prototype.getReactionTorque=function(inv_dt){return 0};PulleyJoint.prototype.initVelocityConstraints=function(step){this.m_localCenterA=this.m_bodyA.m_sweep.localCenter;this.m_localCenterB=this.m_bodyB.m_sweep.localCenter;this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var qA=Rot.neo(aA);var qB=Rot.neo(aB);this.m_rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));this.m_rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));this.m_uA=Vec2.sub(Vec2.add(cA,this.m_rA),this.m_groundAnchorA);this.m_uB=Vec2.sub(Vec2.add(cB,this.m_rB),this.m_groundAnchorB);var lengthA=this.m_uA.length();var lengthB=this.m_uB.length();if(lengthA>10*Settings.linearSlop){this.m_uA.mul(1/lengthA)}else{this.m_uA.setZero()}if(lengthB>10*Settings.linearSlop){this.m_uB.mul(1/lengthB)}else{this.m_uB.setZero()}var ruA=Vec2.cross(this.m_rA,this.m_uA);var ruB=Vec2.cross(this.m_rB,this.m_uB);var mA=this.m_invMassA+this.m_invIA*ruA*ruA;var mB=this.m_invMassB+this.m_invIB*ruB*ruB;this.m_mass=mA+this.m_ratio*this.m_ratio*mB;if(this.m_mass>0){this.m_mass=1/this.m_mass}if(step.warmStarting){this.m_impulse*=step.dtRatio;var PA=Vec2.mul(-this.m_impulse,this.m_uA);var PB=Vec2.mul(-this.m_ratio*this.m_impulse,this.m_uB);vA.addMul(this.m_invMassA,PA);wA+=this.m_invIA*Vec2.cross(this.m_rA,PA);vB.addMul(this.m_invMassB,PB);wB+=this.m_invIB*Vec2.cross(this.m_rB,PB)}else{this.m_impulse=0}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};PulleyJoint.prototype.solveVelocityConstraints=function(step){var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var vpA=Vec2.add(vA,Vec2.cross(wA,this.m_rA));var vpB=Vec2.add(vB,Vec2.cross(wB,this.m_rB));var Cdot=-Vec2.dot(this.m_uA,vpA)-this.m_ratio*Vec2.dot(this.m_uB,vpB);var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;var PA=Vec2.mul(-impulse,this.m_uA);var PB=Vec2.mul(-this.m_ratio*impulse,this.m_uB);vA.addMul(this.m_invMassA,PA);wA+=this.m_invIA*Vec2.cross(this.m_rA,PA);vB.addMul(this.m_invMassB,PB);wB+=this.m_invIB*Vec2.cross(this.m_rB,PB);this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};PulleyJoint.prototype.solvePositionConstraints=function(step){var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));var rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var uA=Vec2.sub(Vec2.add(cA,this.m_rA),this.m_groundAnchorA);var uB=Vec2.sub(Vec2.add(cB,this.m_rB),this.m_groundAnchorB);var lengthA=uA.length();var lengthB=uB.length();if(lengthA>10*Settings.linearSlop){uA.mul(1/lengthA)}else{uA.setZero()}if(lengthB>10*Settings.linearSlop){uB.mul(1/lengthB)}else{uB.setZero()}var ruA=Vec2.cross(rA,uA);var ruB=Vec2.cross(rB,uB);var mA=this.m_invMassA+this.m_invIA*ruA*ruA;var mB=this.m_invMassB+this.m_invIB*ruB*ruB;var mass=mA+this.m_ratio*this.m_ratio*mB;if(mass>0){mass=1/mass}var C=this.m_constant-lengthA-this.m_ratio*lengthB;var linearError=Math.abs(C);var impulse=-mass*C;var PA=Vec2.mul(-impulse,uA);var PB=Vec2.mul(-this.m_ratio*impulse,uB);cA.addMul(this.m_invMassA,PA);aA+=this.m_invIA*Vec2.cross(rA,PA);cB.addMul(this.m_invMassB,PB);aB+=this.m_invIB*Vec2.cross(rB,PB);this.m_bodyA.c_position.c=cA;this.m_bodyA.c_position.a=aA;this.m_bodyB.c_position.c=cB;this.m_bodyB.c_position.a=aB;return linearError0){this.m_state=atUpperLimit}else{this.m_state=inactiveLimit}if(this.m_length>Settings.linearSlop){this.m_u.mul(1/this.m_length)}else{this.m_u.setZero();this.m_mass=0;this.m_impulse=0;return}var crA=Vec2.cross(this.m_rA,this.m_u);var crB=Vec2.cross(this.m_rB,this.m_u);var invMass=this.m_invMassA+this.m_invIA*crA*crA+this.m_invMassB+this.m_invIB*crB*crB;this.m_mass=invMass!=0?1/invMass:0;if(step.warmStarting){this.m_impulse*=step.dtRatio;var P=Vec2.mul(this.m_impulse,this.m_u);vA.subMul(this.m_invMassA,P);wA-=this.m_invIA*Vec2.cross(this.m_rA,P);vB.addMul(this.m_invMassB,P);wB+=this.m_invIB*Vec2.cross(this.m_rB,P)}else{this.m_impulse=0}this.m_bodyA.c_velocity.v.set(vA);this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v.set(vB);this.m_bodyB.c_velocity.w=wB};RopeJoint.prototype.solveVelocityConstraints=function(step){var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var vpA=Vec2.addCross(vA,wA,this.m_rA);var vpB=Vec2.addCross(vB,wB,this.m_rB);var C=this.m_length-this.m_maxLength;var Cdot=Vec2.dot(this.m_u,Vec2.sub(vpB,vpA));if(C<0){Cdot+=step.inv_dt*C}var impulse=-this.m_mass*Cdot;var oldImpulse=this.m_impulse;this.m_impulse=Math.min(0,this.m_impulse+impulse);impulse=this.m_impulse-oldImpulse;var P=Vec2.mul(impulse,this.m_u);vA.subMul(this.m_invMassA,P);wA-=this.m_invIA*Vec2.cross(this.m_rA,P);vB.addMul(this.m_invMassB,P);wB+=this.m_invIB*Vec2.cross(this.m_rB,P);this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};RopeJoint.prototype.solvePositionConstraints=function(step){var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var rA=Rot.mulSub(qA,this.m_localAnchorA,this.m_localCenterA);var rB=Rot.mulSub(qB,this.m_localAnchorB,this.m_localCenterB);var u=Vec2.zero();u.addCombine(1,cB,1,rB);u.subCombine(1,cA,1,rA);var length=u.normalize();var C=length-this.m_maxLength;C=Math.clamp(C,0,Settings.maxLinearCorrection);var impulse=-this.m_mass*C;var P=Vec2.mul(impulse,u);cA.subMul(this.m_invMassA,P);aA-=this.m_invIA*Vec2.cross(rA,P);cB.addMul(this.m_invMassB,P);aB+=this.m_invIB*Vec2.cross(rB,P);this.m_bodyA.c_position.c.set(cA);this.m_bodyA.c_position.a=aA;this.m_bodyB.c_position.c.set(cB);this.m_bodyB.c_position.a=aB;return length-this.m_maxLength0){K.getInverse22(this.m_mass);var invM=iA+iB;var m=invM>0?1/invM:0;var C=aB-aA-this.m_referenceAngle;var omega=2*Math.PI*this.m_frequencyHz;var d=2*m*this.m_dampingRatio*omega;var k=m*omega*omega;var h=step.dt;this.m_gamma=h*(d+h*k);this.m_gamma=this.m_gamma!=0?1/this.m_gamma:0;this.m_bias=C*h*k*this.m_gamma;invM+=this.m_gamma;this.m_mass.ez.z=invM!=0?1/invM:0}else if(K.ez.z==0){K.getInverse22(this.m_mass);this.m_gamma=0;this.m_bias=0}else{K.getSymInverse33(this.m_mass);this.m_gamma=0;this.m_bias=0}if(step.warmStarting){this.m_impulse.mul(step.dtRatio);var P=Vec2.neo(this.m_impulse.x,this.m_impulse.y);vA.subMul(mA,P);wA-=iA*(Vec2.cross(this.m_rA,P)+this.m_impulse.z);vB.addMul(mB,P);wB+=iB*(Vec2.cross(this.m_rB,P)+this.m_impulse.z)}else{this.m_impulse.setZero()}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};WeldJoint.prototype.solveVelocityConstraints=function(step){var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;if(this.m_frequencyHz>0){var Cdot2=wB-wA;var impulse2=-this.m_mass.ez.z*(Cdot2+this.m_bias+this.m_gamma*this.m_impulse.z);this.m_impulse.z+=impulse2;wA-=iA*impulse2;wB+=iB*impulse2;var Cdot1=Vec2.zero();Cdot1.addCombine(1,vB,1,Vec2.cross(wB,this.m_rB));Cdot1.subCombine(1,vA,1,Vec2.cross(wA,this.m_rA));var impulse1=Vec2.neg(Mat33.mulVec2(this.m_mass,Cdot1));this.m_impulse.x+=impulse1.x;this.m_impulse.y+=impulse1.y;var P=Vec2.clone(impulse1);vA.subMul(mA,P);wA-=iA*Vec2.cross(this.m_rA,P);vB.addMul(mB,P);wB+=iB*Vec2.cross(this.m_rB,P)}else{var Cdot1=Vec2.zero();Cdot1.addCombine(1,vB,1,Vec2.cross(wB,this.m_rB));Cdot1.subCombine(1,vA,1,Vec2.cross(wA,this.m_rA));var Cdot2=wB-wA;var Cdot=Vec3(Cdot1.x,Cdot1.y,Cdot2);var impulse=Vec3.neg(Mat33.mulVec3(this.m_mass,Cdot));this.m_impulse.add(impulse);var P=Vec2.neo(impulse.x,impulse.y);vA.subMul(mA,P);wA-=iA*(Vec2.cross(this.m_rA,P)+impulse.z);vB.addMul(mB,P);wB+=iB*(Vec2.cross(this.m_rB,P)+impulse.z)}this.m_bodyA.c_velocity.v=vA;this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v=vB;this.m_bodyB.c_velocity.w=wB};WeldJoint.prototype.solvePositionConstraints=function(step){var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));var rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var positionError,angularError;var K=new Mat33;K.ex.x=mA+mB+rA.y*rA.y*iA+rB.y*rB.y*iB;K.ey.x=-rA.y*rA.x*iA-rB.y*rB.x*iB;K.ez.x=-rA.y*iA-rB.y*iB;K.ex.y=K.ey.x;K.ey.y=mA+mB+rA.x*rA.x*iA+rB.x*rB.x*iB;K.ez.y=rA.x*iA+rB.x*iB;K.ex.z=K.ez.x;K.ey.z=K.ez.y;K.ez.z=iA+iB;if(this.m_frequencyHz>0){var C1=Vec2.zero();C1.addCombine(1,cB,1,rB);C1.subCombine(1,cA,1,rA);positionError=C1.length();angularError=0;var P=Vec2.neg(K.solve22(C1));cA.subMul(mA,P);aA-=iA*Vec2.cross(rA,P);cB.addMul(mB,P);aB+=iB*Vec2.cross(rB,P)}else{var C1=Vec2.zero();C1.addCombine(1,cB,1,rB);C1.subCombine(1,cA,1,rA);var C2=aB-aA-this.m_referenceAngle;positionError=C1.length();angularError=Math.abs(C2);var C=Vec3(C1.x,C1.y,C2);var impulse=Vec3();if(K.ez.z>0){impulse=Vec3.neg(K.solve33(C))}else{var impulse2=Vec2.neg(K.solve22(C1));impulse.set(impulse2.x,impulse2.y,0)}var P=Vec2.neo(impulse.x,impulse.y);cA.subMul(mA,P);aA-=iA*(Vec2.cross(rA,P)+impulse.z);cB.addMul(mB,P);aB+=iB*(Vec2.cross(rB,P)+impulse.z)}this.m_bodyA.c_position.c=cA;this.m_bodyA.c_position.a=aA;this.m_bodyB.c_position.c=cB;this.m_bodyB.c_position.a=aB;return positionError<=Settings.linearSlop&&angularError<=Settings.angularSlop}},function(module,exports,__webpack_require__){var _DEBUG=false?undefined:false;var _ASSERT=false?undefined:false;module.exports=WheelJoint;var options=__webpack_require__(7);var create=__webpack_require__(6);var Settings=__webpack_require__(4);var Math=__webpack_require__(1);var Vec2=__webpack_require__(0);var Vec3=__webpack_require__(11);var Mat22=__webpack_require__(10);var Mat33=__webpack_require__(15);var Rot=__webpack_require__(3);var Sweep=__webpack_require__(9);var Transform=__webpack_require__(5);var Velocity=__webpack_require__(13);var Position=__webpack_require__(14);var Joint=__webpack_require__(12);var Body=__webpack_require__(8);WheelJoint.TYPE="wheel-joint";Joint.TYPES[WheelJoint.TYPE]=WheelJoint;WheelJoint._super=Joint;WheelJoint.prototype=create(WheelJoint._super.prototype);var DEFAULTS={enableMotor:false,maxMotorTorque:0,motorSpeed:0,frequencyHz:2,dampingRatio:0.7};function WheelJoint(def,bodyA,bodyB,anchor,axis){if(!(this instanceof WheelJoint)){return new WheelJoint(def,bodyA,bodyB,anchor,axis)}def=options(def,DEFAULTS);Joint.call(this,def,bodyA,bodyB);bodyA=this.m_bodyA;bodyB=this.m_bodyB;this.m_type=WheelJoint.TYPE;this.m_localAnchorA=Vec2.clone(anchor?bodyA.getLocalPoint(anchor):def.localAnchorA||Vec2.zero());this.m_localAnchorB=Vec2.clone(anchor?bodyB.getLocalPoint(anchor):def.localAnchorB||Vec2.zero());this.m_localXAxisA=Vec2.clone(axis?bodyA.getLocalVector(axis):def.localAxisA||def.localAxis||Vec2.neo(1,0));this.m_localYAxisA=Vec2.cross(1,this.m_localXAxisA);this.m_mass=0;this.m_impulse=0;this.m_motorMass=0;this.m_motorImpulse=0;this.m_springMass=0;this.m_springImpulse=0;this.m_maxMotorTorque=def.maxMotorTorque;this.m_motorSpeed=def.motorSpeed;this.m_enableMotor=def.enableMotor;this.m_frequencyHz=def.frequencyHz;this.m_dampingRatio=def.dampingRatio;this.m_bias=0;this.m_gamma=0;this.m_localCenterA;this.m_localCenterB;this.m_invMassA;this.m_invMassB;this.m_invIA;this.m_invIB;this.m_ax=Vec2.zero();this.m_ay=Vec2.zero();this.m_sAx;this.m_sBx;this.m_sAy;this.m_sBy}WheelJoint.prototype._serialize=function(){return{type:this.m_type,bodyA:this.m_bodyA,bodyB:this.m_bodyB,collideConnected:this.m_collideConnected,enableMotor:this.m_enableMotor,maxMotorTorque:this.m_maxMotorTorque,motorSpeed:this.m_motorSpeed,frequencyHz:this.m_frequencyHz,dampingRatio:this.m_dampingRatio,localAnchorA:this.m_localAnchorA,localAnchorB:this.m_localAnchorB,localAxisA:this.m_localXAxisA}};WheelJoint._deserialize=function(data,world,restore){data.bodyA=restore(Body,data.bodyA,world);data.bodyB=restore(Body,data.bodyB,world);var joint=new WheelJoint(data);return joint};WheelJoint.prototype._setAnchors=function(def){if(def.anchorA){this.m_localAnchorA.set(this.m_bodyA.getLocalPoint(def.anchorA))}else if(def.localAnchorA){this.m_localAnchorA.set(def.localAnchorA)}if(def.anchorB){this.m_localAnchorB.set(this.m_bodyB.getLocalPoint(def.anchorB))}else if(def.localAnchorB){this.m_localAnchorB.set(def.localAnchorB)}if(def.localAxisA){this.m_localXAxisA.set(def.localAxisA);this.m_localYAxisA.set(Vec2.cross(1,def.localAxisA))}};WheelJoint.prototype.getLocalAnchorA=function(){return this.m_localAnchorA};WheelJoint.prototype.getLocalAnchorB=function(){return this.m_localAnchorB};WheelJoint.prototype.getLocalAxisA=function(){return this.m_localXAxisA};WheelJoint.prototype.getJointTranslation=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var pA=bA.getWorldPoint(this.m_localAnchorA);var pB=bB.getWorldPoint(this.m_localAnchorB);var d=Vec2.sub(pB,pA);var axis=bA.getWorldVector(this.m_localXAxisA);var translation=Vec2.dot(d,axis);return translation};WheelJoint.prototype.getJointSpeed=function(){var wA=this.m_bodyA.m_angularVelocity;var wB=this.m_bodyB.m_angularVelocity;return wB-wA};WheelJoint.prototype.isMotorEnabled=function(){return this.m_enableMotor};WheelJoint.prototype.enableMotor=function(flag){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_enableMotor=flag};WheelJoint.prototype.setMotorSpeed=function(speed){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_motorSpeed=speed};WheelJoint.prototype.getMotorSpeed=function(){return this.m_motorSpeed};WheelJoint.prototype.setMaxMotorTorque=function(torque){this.m_bodyA.setAwake(true);this.m_bodyB.setAwake(true);this.m_maxMotorTorque=torque};WheelJoint.prototype.getMaxMotorTorque=function(){return this.m_maxMotorTorque};WheelJoint.prototype.getMotorTorque=function(inv_dt){return inv_dt*this.m_motorImpulse};WheelJoint.prototype.setSpringFrequencyHz=function(hz){this.m_frequencyHz=hz};WheelJoint.prototype.getSpringFrequencyHz=function(){return this.m_frequencyHz};WheelJoint.prototype.setSpringDampingRatio=function(ratio){this.m_dampingRatio=ratio};WheelJoint.prototype.getSpringDampingRatio=function(){return this.m_dampingRatio};WheelJoint.prototype.getAnchorA=function(){return this.m_bodyA.getWorldPoint(this.m_localAnchorA)};WheelJoint.prototype.getAnchorB=function(){return this.m_bodyB.getWorldPoint(this.m_localAnchorB)};WheelJoint.prototype.getReactionForce=function(inv_dt){return Vec2.combine(this.m_impulse,this.m_ay,this.m_springImpulse,this.m_ax).mul(inv_dt)};WheelJoint.prototype.getReactionTorque=function(inv_dt){return inv_dt*this.m_motorImpulse};WheelJoint.prototype.initVelocityConstraints=function(step){this.m_localCenterA=this.m_bodyA.m_sweep.localCenter;this.m_localCenterB=this.m_bodyB.m_sweep.localCenter;this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));var rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var d=Vec2.zero();d.addCombine(1,cB,1,rB);d.subCombine(1,cA,1,rA);{this.m_ay=Rot.mulVec2(qA,this.m_localYAxisA);this.m_sAy=Vec2.cross(Vec2.add(d,rA),this.m_ay);this.m_sBy=Vec2.cross(rB,this.m_ay);this.m_mass=mA+mB+iA*this.m_sAy*this.m_sAy+iB*this.m_sBy*this.m_sBy;if(this.m_mass>0){this.m_mass=1/this.m_mass}}this.m_springMass=0;this.m_bias=0;this.m_gamma=0;if(this.m_frequencyHz>0){this.m_ax=Rot.mulVec2(qA,this.m_localXAxisA);this.m_sAx=Vec2.cross(Vec2.add(d,rA),this.m_ax);this.m_sBx=Vec2.cross(rB,this.m_ax);var invMass=mA+mB+iA*this.m_sAx*this.m_sAx+iB*this.m_sBx*this.m_sBx;if(invMass>0){this.m_springMass=1/invMass;var C=Vec2.dot(d,this.m_ax);var omega=2*Math.PI*this.m_frequencyHz;var d=2*this.m_springMass*this.m_dampingRatio*omega;var k=this.m_springMass*omega*omega;var h=step.dt;this.m_gamma=h*(d+h*k);if(this.m_gamma>0){this.m_gamma=1/this.m_gamma}this.m_bias=C*h*k*this.m_gamma;this.m_springMass=invMass+this.m_gamma;if(this.m_springMass>0){this.m_springMass=1/this.m_springMass}}}else{this.m_springImpulse=0}if(this.m_enableMotor){this.m_motorMass=iA+iB;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass}}else{this.m_motorMass=0;this.m_motorImpulse=0}if(step.warmStarting){this.m_impulse*=step.dtRatio;this.m_springImpulse*=step.dtRatio;this.m_motorImpulse*=step.dtRatio;var P=Vec2.combine(this.m_impulse,this.m_ay,this.m_springImpulse,this.m_ax);var LA=this.m_impulse*this.m_sAy+this.m_springImpulse*this.m_sAx+this.m_motorImpulse;var LB=this.m_impulse*this.m_sBy+this.m_springImpulse*this.m_sBx+this.m_motorImpulse;vA.subMul(this.m_invMassA,P);wA-=this.m_invIA*LA;vB.addMul(this.m_invMassB,P);wB+=this.m_invIB*LB}else{this.m_impulse=0;this.m_springImpulse=0;this.m_motorImpulse=0}this.m_bodyA.c_velocity.v.set(vA);this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v.set(vB);this.m_bodyB.c_velocity.w=wB};WheelJoint.prototype.solveVelocityConstraints=function(step){var mA=this.m_invMassA;var mB=this.m_invMassB;var iA=this.m_invIA;var iB=this.m_invIB;var vA=this.m_bodyA.c_velocity.v;var wA=this.m_bodyA.c_velocity.w;var vB=this.m_bodyB.c_velocity.v;var wB=this.m_bodyB.c_velocity.w;{var Cdot=Vec2.dot(this.m_ax,vB)-Vec2.dot(this.m_ax,vA)+this.m_sBx*wB-this.m_sAx*wA;var impulse=-this.m_springMass*(Cdot+this.m_bias+this.m_gamma*this.m_springImpulse);this.m_springImpulse+=impulse;var P=Vec2.mul(impulse,this.m_ax);var LA=impulse*this.m_sAx;var LB=impulse*this.m_sBx;vA.subMul(mA,P);wA-=iA*LA;vB.addMul(mB,P);wB+=iB*LB}{var Cdot=wB-wA-this.m_motorSpeed;var impulse=-this.m_motorMass*Cdot;var oldImpulse=this.m_motorImpulse;var maxImpulse=step.dt*this.m_maxMotorTorque;this.m_motorImpulse=Math.clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse}{var Cdot=Vec2.dot(this.m_ay,vB)-Vec2.dot(this.m_ay,vA)+this.m_sBy*wB-this.m_sAy*wA;var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;var P=Vec2.mul(impulse,this.m_ay);var LA=impulse*this.m_sAy;var LB=impulse*this.m_sBy;vA.subMul(mA,P);wA-=iA*LA;vB.addMul(mB,P);wB+=iB*LB}this.m_bodyA.c_velocity.v.set(vA);this.m_bodyA.c_velocity.w=wA;this.m_bodyB.c_velocity.v.set(vB);this.m_bodyB.c_velocity.w=wB};WheelJoint.prototype.solvePositionConstraints=function(step){var cA=this.m_bodyA.c_position.c;var aA=this.m_bodyA.c_position.a;var cB=this.m_bodyB.c_position.c;var aB=this.m_bodyB.c_position.a;var qA=Rot.neo(aA);var qB=Rot.neo(aB);var rA=Rot.mulVec2(qA,Vec2.sub(this.m_localAnchorA,this.m_localCenterA));var rB=Rot.mulVec2(qB,Vec2.sub(this.m_localAnchorB,this.m_localCenterB));var d=Vec2.zero();d.addCombine(1,cB,1,rB);d.subCombine(1,cA,1,rA);var ay=Rot.mulVec2(qA,this.m_localYAxisA);var sAy=Vec2.cross(Vec2.add(d,rA),ay);var sBy=Vec2.cross(rB,ay);var C=Vec2.dot(d,ay);var k=this.m_invMassA+this.m_invMassB+this.m_invIA*this.m_sAy*this.m_sAy+this.m_invIB*this.m_sBy*this.m_sBy;var impulse;if(k!=0){impulse=-C/k}else{impulse=0}var P=Vec2.mul(impulse,ay);var LA=impulse*sAy;var LB=impulse*sBy;cA.subMul(this.m_invMassA,P);aA-=this.m_invIA*LA;cB.addMul(this.m_invMassB,P);aB+=this.m_invIB*LB;this.m_bodyA.c_position.c.set(cA);this.m_bodyA.c_position.a=aA;this.m_bodyB.c_position.c.set(cB);this.m_bodyB.c_position.a=aB;return Math.abs(C)<=Settings.linearSlop}}]);if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=$i_107}var $i_108={};(function(a2j,undefined){if(!(Object.defineProperty instanceof Function)&&Object.__defineGetter__ instanceof Function&&Object.__defineSetter__ instanceof Function){Object.defineProperty=function(obj,p,cfg){if(cfg.get instanceof Function)obj.__defineGetter__(p,cfg.get);if(cfg.set instanceof Function)obj.__defineSetter__(p,cfg.set)}}function emptyFn(){}a2j.inherit=function(cls,base){var tmpCtr=cls;emptyFn.prototype=base.prototype;cls.prototype=new emptyFn;cls.prototype.constructor=tmpCtr};a2j.generateCallback=function generateCallback(context,cb){return function(){cb.apply(context,arguments)}};a2j.NVector=function NVector(length){if(length===undefined)length=0;var tmp=new Array(length||0);for(var i=0;i=0&&dY>=0;valid=valid&&this.lowerBound.IsValid()&&this.upperBound.IsValid();return valid};b2AABB.prototype.GetCenter=function(){return new b2Vec2((this.lowerBound.x+this.upperBound.x)/2,(this.lowerBound.y+this.upperBound.y)/2)};b2AABB.prototype.GetExtents=function(){return new b2Vec2((this.upperBound.x-this.lowerBound.x)/2,(this.upperBound.y-this.lowerBound.y)/2)};b2AABB.prototype.Contains=function(aabb){var result=true;result=result&&this.lowerBound.x<=aabb.lowerBound.x;result=result&&this.lowerBound.y<=aabb.lowerBound.y;result=result&&aabb.upperBound.x<=this.upperBound.x;result=result&&aabb.upperBound.y<=this.upperBound.y;return result};b2AABB.prototype.RayCast=function(output,input){var tmin=-Number.MAX_VALUE;var tmax=Number.MAX_VALUE;var pX=input.p1.x;var pY=input.p1.y;var dX=input.p2.x-input.p1.x;var dY=input.p2.y-input.p1.y;var absDX=Math.abs(dX);var absDY=Math.abs(dY);var normal=output.normal;var inv_d=0;var t1=0;var t2=0;var t3=0;var s=0;{if(absDXt2){t3=t1;t1=t2;t2=t3;s=1}if(t1>tmin){normal.x=s;normal.y=0;tmin=t1}tmax=Math.min(tmax,t2);if(tmin>tmax)return false}}{if(absDYt2){t3=t1;t1=t2;t2=t3;s=1}if(t1>tmin){normal.y=s;normal.x=0;tmin=t1}tmax=Math.min(tmax,t2);if(tmin>tmax)return false}}output.fraction=tmin;return true};b2AABB.prototype.TestOverlap=function(other){var d1X=other.lowerBound.x-this.upperBound.x;var d1Y=other.lowerBound.y-this.upperBound.y;var d2X=this.lowerBound.x-other.upperBound.x;var d2Y=this.lowerBound.y-other.upperBound.y;if(other.lowerBound.z||this.lowerBound.z)console.log(d1X,d1Y," ",d2X,d2Y);if(d1X>0||d1Y>0)return false;if(d2X>0||d2Y>0)return false;return true};b2AABB.Combine=function(aabb1,aabb2){var aabb=new b2AABB;aabb.Combine(aabb1,aabb2);return aabb};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)};b2Bound.b2Bound=function(){};b2Bound.prototype.IsLower=function(){return(this.value&1)==0};b2Bound.prototype.IsUpper=function(){return(this.value&1)==1};b2Bound.prototype.Swap=function(b){var tempValue=this.value;var tempProxy=this.proxy;var tempStabbingCount=this.stabbingCount;this.value=b.value;this.proxy=b.proxy;this.stabbingCount=b.stabbingCount;b.value=tempValue;b.proxy=tempProxy;b.stabbingCount=tempStabbingCount};b2BoundValues.b2BoundValues=function(){};b2BoundValues.prototype.b2BoundValues=function(){this.lowerValues=new Vector_a2j_Number;this.lowerValues[0]=0;this.lowerValues[1]=0;this.upperValues=new Vector_a2j_Number;this.upperValues[0]=0;this.upperValues[1]=0};b2Collision.b2Collision=function(){};b2Collision.ClipSegmentToLine=function(vOut,vIn,normal,offset){if(offset===undefined)offset=0;var cv;var numOut=0;cv=vIn[0];var vIn0=cv.v;cv=vIn[1];var vIn1=cv.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<=0)vOut[numOut++].Set(vIn[0]);if(distance1<=0)vOut[numOut++].Set(vIn[1]);if(distance0*distance1<0){var interp=distance0/(distance0-distance1);cv=vOut[numOut];var tVec=cv.v;tVec.x=vIn0.x+interp*(vIn1.x-vIn0.x);tVec.y=vIn0.y+interp*(vIn1.y-vIn0.y);cv=vOut[numOut];var cv2;if(distance0>0){cv2=vIn[0];cv.id=cv2.id}else{cv2=vIn[1];cv.id=cv2.id}++numOut}return numOut};b2Collision.EdgeSeparation=function(poly1,xf1,edge1,poly2,xf2){if(edge1===undefined)edge1=0;var count1=parseInt(poly1.m_vertexCount);var vertices1=poly1.m_vertices;var normals1=poly1.m_normals;var count2=parseInt(poly2.m_vertexCount);var vertices2=poly2.m_vertices;var tMat;var tVec;tMat=xf1.R;tVec=normals1[edge1];var normal1WorldX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var normal1WorldY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=xf2.R;var normal1X=tMat.col1.x*normal1WorldX+tMat.col1.y*normal1WorldY;var normal1Y=tMat.col2.x*normal1WorldX+tMat.col2.y*normal1WorldY;var index=0;var minDot=Number.MAX_VALUE;for(var i=0;imaxDot){maxDot=dot;edge=i}}var s=b2Collision.EdgeSeparation(poly1,xf1,edge,poly2,xf2);var prevEdge=parseInt(edge-1>=0?edge-1:count1-1);var sPrev=b2Collision.EdgeSeparation(poly1,xf1,prevEdge,poly2,xf2);var nextEdge=parseInt(edge+1s&&sPrev>sNext){increment=-1;bestEdge=prevEdge;bestSeparation=sPrev}else if(sNext>s){increment=1;bestEdge=nextEdge;bestSeparation=sNext}else{edgeIndex[0]=edge;return s}var x=0;while(true){x++;if(x>10000){console.log("961")}if(increment==-1)edge=bestEdge-1>=0?bestEdge-1:count1-1;else edge=bestEdge+1bestSeparation){bestEdge=edge;bestSeparation=s}else{break}}edgeIndex[0]=bestEdge;return bestSeparation};b2Collision.FindIncidentEdge=function(c,poly1,xf1,edge1,poly2,xf2){if(edge1===undefined)edge1=0;var count1=parseInt(poly1.m_vertexCount);var normals1=poly1.m_normals;var count2=parseInt(poly2.m_vertexCount);var vertices2=poly2.m_vertices;var normals2=poly2.m_normals;var tMat;var tVec;tMat=xf1.R;tVec=normals1[edge1];var normal1X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var normal1Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=xf2.R;var tX=tMat.col1.x*normal1X+tMat.col1.y*normal1Y;normal1Y=tMat.col2.x*normal1X+tMat.col2.y*normal1Y;normal1X=tX;var index=0;var minDot=Number.MAX_VALUE;for(var i=0;itotalRadius)return;var edgeB=0;b2Collision.s_edgeBO[0]=edgeB;var separationB=b2Collision.FindMaxSeparation(b2Collision.s_edgeBO,polyB,xfB,polyA,xfA);edgeB=b2Collision.s_edgeBO[0];if(separationB>totalRadius)return;var poly1;var poly2;var xf1;var xf2;var edge1=0;var flip=0;var k_relativeTol=0.98;var k_absoluteTol=0.001;var tMat;if(separationB>k_relativeTol*separationA+k_absoluteTol){poly1=polyB;poly2=polyA;xf1=xfB;xf2=xfA;edge1=edgeB;manifold.m_type=b2Manifold.e_faceB;flip=1}else{poly1=polyA;poly2=polyB;xf1=xfA;xf2=xfB;edge1=edgeA;manifold.m_type=b2Manifold.e_faceA;flip=0}var incidentEdge=b2Collision.s_incidentEdge;b2Collision.FindIncidentEdge(incidentEdge,poly1,xf1,edge1,poly2,xf2);var count1=parseInt(poly1.m_vertexCount);var vertices1=poly1.m_vertices;var local_v11=vertices1[edge1];var local_v12;if(edge1+1radius*radius){return}manifold.m_type=b2Manifold.e_circles;manifold.m_localPoint.SetV(circle1.m_p);manifold.m_localPlaneNormal.SetZero();manifold.m_pointCount=1;manifold.m_points[0].m_localPoint.SetV(circle2.m_p);manifold.m_points[0].m_id.key=0};b2Collision.CollidePolygonAndCircle=function(manifold,polygon,xf1,circle,xf2){if(!polygon)return;manifold.m_pointCount=0;var tPoint;var dX=0;var dY=0;var positionX=0;var positionY=0;var tVec;var tMat;tMat=xf2.R;tVec=circle.m_p;var cX=xf2.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var cY=xf2.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);dX=cX-xf1.position.x;dY=cY-xf1.position.y;tMat=xf1.R;var cLocalX=dX*tMat.col1.x+dY*tMat.col1.y;var cLocalY=dX*tMat.col2.x+dY*tMat.col2.y;var dist=0;var normalIndex=0;var separation=-Number.MAX_VALUE;var radius=polygon.m_radius+circle.m_radius;var vertexCount=parseInt(polygon.m_vertexCount);var vertices=polygon.m_vertices;var normals=polygon.m_normals;for(var i=0;iradius){return}if(s>separation){separation=s;normalIndex=i}}var vertIndex1=parseInt(normalIndex);var vertIndex2=parseInt(vertIndex1+1radius*radius)return;manifold.m_pointCount=1;manifold.m_type=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.m_p);manifold.m_points[0].m_id.key=0}else if(u2<=0){if((cLocalX-v2.x)*(cLocalX-v2.x)+(cLocalY-v2.y)*(cLocalY-v2.y)>radius*radius)return;manifold.m_pointCount=1;manifold.m_type=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.m_p);manifold.m_points[0].m_id.key=0}else{var faceCenterX=0.5*(v1.x+v2.x);var faceCenterY=0.5*(v1.y+v2.y);separation=(cLocalX-faceCenterX)*normals[vertIndex1].x+(cLocalY-faceCenterY)*normals[vertIndex1].y;if(separation>radius)return;manifold.m_pointCount=1;manifold.m_type=b2Manifold.e_faceA;manifold.m_localPlaneNormal.x=normals[vertIndex1].x;manifold.m_localPlaneNormal.y=normals[vertIndex1].y;manifold.m_localPlaneNormal.Normalize();manifold.m_localPoint.Set(faceCenterX,faceCenterY);manifold.m_points[0].m_localPoint.SetV(circle.m_p);manifold.m_points[0].m_id.key=0}};b2Collision.TestOverlap=function(a,b){var t1=b.lowerBound;var t2=a.upperBound;var d1X=t1.x-t2.x;var d1Y=t1.y-t2.y;t1=a.lowerBound;t2=b.upperBound;var d2X=t1.x-t2.x;var d2Y=t1.y-t2.y;if(d1X>0||d1Y>0)return false;if(d2X>0||d2Y>0)return false;return true};$i_108.postDefs.push(function(){$i_108.Collision.b2Collision.s_incidentEdge=b2Collision.MakeClipPointVector();$i_108.Collision.b2Collision.s_clipPoints1=b2Collision.MakeClipPointVector();$i_108.Collision.b2Collision.s_clipPoints2=b2Collision.MakeClipPointVector();$i_108.Collision.b2Collision.s_edgeAO=new Vector_a2j_Number(1);$i_108.Collision.b2Collision.s_edgeBO=new Vector_a2j_Number(1);$i_108.Collision.b2Collision.s_localTangent=new b2Vec2;$i_108.Collision.b2Collision.s_localNormal=new b2Vec2;$i_108.Collision.b2Collision.s_planePoint=new b2Vec2;$i_108.Collision.b2Collision.s_normal=new b2Vec2;$i_108.Collision.b2Collision.s_tangent=new b2Vec2;$i_108.Collision.b2Collision.s_tangent2=new b2Vec2;$i_108.Collision.b2Collision.s_v11=new b2Vec2;$i_108.Collision.b2Collision.s_v12=new b2Vec2;$i_108.Collision.b2Collision.b2CollidePolyTempVec=new b2Vec2;$i_108.Collision.b2Collision.b2_nullFeature=255});b2ContactID.b2ContactID=function(){this.features=new Features};b2ContactID.prototype.b2ContactID=function(){this.features._m_id=this};b2ContactID.prototype.Set=function(id){this.key=id._key};b2ContactID.prototype.Copy=function(){var id=new b2ContactID;id.key=this.key;return id};Object.defineProperty(b2ContactID.prototype,"key",{enumerable:false,configurable:true,get:function(){return this._key}});Object.defineProperty(b2ContactID.prototype,"key",{enumerable:false,configurable:true,set:function(value){if(value===undefined)value=0;this._key=value;this.features._referenceEdge=this._key&255;this.features._incidentEdge=(this._key&65280)>>8&255;this.features._incidentVertex=(this._key&16711680)>>16&255;this.features._flip=(this._key&4278190080)>>24&255}});b2ContactPoint.b2ContactPoint=function(){this.position=new b2Vec2;this.velocity=new b2Vec2;this.normal=new b2Vec2;this.id=new b2ContactID};b2Distance.b2Distance=function(){};b2Distance.Distance=function(output,cache,input){++b2Distance.b2_gjkCalls;var proxyA=input.proxyA;var proxyB=input.proxyB;var transformA=input.transformA;var transformB=input.transformB;var simplex=b2Distance.s_simplex;simplex.ReadCache(cache,proxyA,transformA,proxyB,transformB);var vertices=simplex.m_vertices;var k_maxIters=20;var saveA=b2Distance.s_saveA;var saveB=b2Distance.s_saveB;var saveCount=0;var closestPoint=simplex.GetClosestPoint();var distanceSqr1=closestPoint.LengthSquared();var distanceSqr2=distanceSqr1;var i=0;var p;var iter=0;var x=0;while(iter10000){console.log("1346")}saveCount=simplex.m_count;for(i=0;idistanceSqr1){}distanceSqr1=distanceSqr2;var d=simplex.GetSearchDirection();if(d.LengthSquared()rA+rB&&output.distance>Number.MIN_VALUE){output.distance-=rA+rB;var normal=b2Math.SubtractVV(output.pointB,output.pointA);normal.Normalize();output.pointA.x+=rA*normal.x;output.pointA.y+=rA*normal.y;output.pointB.x-=rB*normal.x;output.pointB.y-=rB*normal.y}else{p=new b2Vec2;p.x=0.5*(output.pointA.x+output.pointB.x);p.y=0.5*(output.pointA.y+output.pointB.y);output.pointA.x=output.pointB.x=p.x;output.pointA.y=output.pointB.y=p.y;output.distance=0}}};$i_108.postDefs.push(function(){$i_108.Collision.b2Distance.s_simplex=new b2Simplex;$i_108.Collision.b2Distance.s_saveA=new Vector_a2j_Number(3);$i_108.Collision.b2Distance.s_saveB=new Vector_a2j_Number(3)});b2DistanceInput.b2DistanceInput=function(){};b2DistanceOutput.b2DistanceOutput=function(){this.pointA=new b2Vec2;this.pointB=new b2Vec2};b2DistanceProxy.b2DistanceProxy=function(){};b2DistanceProxy.prototype.Set=function(shape){switch(shape.GetType()){case b2Shape.e_circleShape:{var circle=shape instanceof b2CircleShape?shape:null;this.m_vertices=new Vector(1,true);this.m_vertices[0]=circle.m_p;this.m_count=1;this.m_radius=circle.m_radius}break;case b2Shape.e_polygonShape:{var polygon=shape instanceof b2PolygonShape?shape:null;this.m_vertices=polygon.m_vertices;this.m_count=polygon.m_vertexCount;this.m_radius=polygon.m_radius}break;default:b2Settings.b2Assert(false);}};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;ibestValue){bestIndex=i;bestValue=value}}return bestIndex};b2DistanceProxy.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;ibestValue){bestIndex=i;bestValue=value}}return this.m_vertices[bestIndex]};b2DistanceProxy.prototype.GetVertexCount=function(){return this.m_count};b2DistanceProxy.prototype.GetVertex=function(index){if(index===undefined)index=0;b2Settings.b2Assert(index>=0&&index0?displacement.x:-displacement.x);var extendY=b2Settings.b2_aabbExtension+b2Settings.b2_aabbMultiplier*(displacement.y>0?displacement.y:-displacement.y);proxy.aabb.lowerBound.x=aabb.lowerBound.x-extendX;proxy.aabb.lowerBound.y=aabb.lowerBound.y-extendY;proxy.aabb.upperBound.x=aabb.upperBound.x+extendX;proxy.aabb.upperBound.y=aabb.upperBound.y+extendY;this.InsertLeaf(proxy);return true};b2DynamicTree.prototype.Rebalance=function(iterations){if(iterations===undefined)iterations=0;if(this.m_root==null)return;for(var i=0;i10000){console.log("1537")}node=this.m_path>>bit&1?node.child2:node.child1;bit=bit+1&31}++this.m_path;this.RemoveLeaf(node);this.InsertLeaf(node)}};b2DynamicTree.prototype.GetFatAABB=function(proxy){return proxy.aabb};b2DynamicTree.prototype.GetUserData=function(proxy){return proxy.userData};b2DynamicTree.prototype.Query=function(callback,aabb){if(this.m_root==null)return;var stack=new Vector;var count=0;stack[count++]=this.m_root;var x=0;while(count>0){x++;if(x>10000){console.log("1560")}var node=stack[--count];if(node.aabb.TestOverlap(aabb)){if(node.IsLeaf()){var proceed=callback(node);if(!proceed)return}else{stack[count++]=node.child1;stack[count++]=node.child2}}}};b2DynamicTree.prototype.RayCast=function(callback,input){if(this.m_root==null)return;var p1=input.p1;var p2=input.p2;var r=b2Math.SubtractVV(p1,p2);r.Normalize();var v=b2Math.CrossFV(1,r);var abs_v=b2Math.AbsV(v);var maxFraction=input.maxFraction;var segmentAABB=new b2AABB;var tX=0;var tY=0;{tX=p1.x+maxFraction*(p2.x-p1.x);tY=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=Math.min(p1.x,tX);segmentAABB.lowerBound.y=Math.min(p1.y,tY);segmentAABB.upperBound.x=Math.max(p1.x,tX);segmentAABB.upperBound.y=Math.max(p1.y,tY)}var stack=new Vector;var count=0;stack[count++]=this.m_root;var x=0;while(count>0){x++;if(x>10000){console.log("1599");return}var node=stack[--count];if(node.aabb.TestOverlap(segmentAABB)==false){continue}var c=node.aabb.GetCenter();var h=node.aabb.GetExtents();var separation=Math.abs(v.x*(p1.x-c.x)+v.y*(p1.y-c.y))-abs_v.x*h.x-abs_v.y*h.y;if(separation>0)continue;if(node.IsLeaf()){var subInput=new b2RayCastInput;subInput.p1=input.p1;subInput.p2=input.p2;subInput.maxFraction=maxFraction;var value=callback(subInput,node);if(value==0)return;if(value>0){maxFraction=value;tX=p1.x+maxFraction*(p2.x-p1.x);tY=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=Math.min(p1.x,tX);segmentAABB.lowerBound.y=Math.min(p1.y,tY);segmentAABB.upperBound.x=Math.max(p1.x,tX);segmentAABB.upperBound.y=Math.max(p1.y,tY)}}else{stack[count++]=node.child1;stack[count++]=node.child2}}};b2DynamicTree.prototype.AllocateNode=function(){if(this.m_freeList){var node=this.m_freeList;this.m_freeList=node.parent;node.parent=null;node.child1=null;node.child2=null;return node}return new b2DynamicTreeNode};b2DynamicTree.prototype.FreeNode=function(node){node.parent=this.m_freeList;this.m_freeList=node};b2DynamicTree.prototype.InsertLeaf=function(leaf){++this.m_insertionCount;if(this.m_root==null){this.m_root=leaf;this.m_root.parent=null;return}var center=leaf.aabb.GetCenter();var sibling=this.m_root;if(sibling.IsLeaf()==false){var x=0;do{x++;if(x>10000){console.log("1667")}var child1=sibling.child1;var child2=sibling.child2;var norm1=Math.abs((child1.aabb.lowerBound.x+child1.aabb.upperBound.x)/2-center.x)+Math.abs((child1.aabb.lowerBound.y+child1.aabb.upperBound.y)/2-center.y);var norm2=Math.abs((child2.aabb.lowerBound.x+child2.aabb.upperBound.x)/2-center.x)+Math.abs((child2.aabb.lowerBound.y+child2.aabb.upperBound.y)/2-center.y);if(norm110000){console.log("1699")}if(node1.aabb.Contains(node2.aabb))break;node1.aabb.Combine(node1.child1.aabb,node1.child2.aabb);node2=node1;node1=node1.parent}while(node1)}else{node2.child1=sibling;node2.child2=leaf;sibling.parent=node2;leaf.parent=node2;this.m_root=node2}};b2DynamicTree.prototype.RemoveLeaf=function(leaf){if(leaf==this.m_root){this.m_root=null;return}var node2=leaf.parent;var node1=node2.parent;var sibling;if(node2.child1==leaf){sibling=node2.child2}else{sibling=node2.child1}if(node1){if(node1.child1==node2){node1.child1=sibling}else{node1.child2=sibling}sibling.parent=node1;this.FreeNode(node2);var x=0;while(node1){x++;if(x>10000){console.log("1741")}var oldAABB=node1.aabb;node1.aabb=b2AABB.Combine(node1.child1.aabb,node1.child2.aabb);if(oldAABB.Contains(node1.aabb))break;node1=node1.parent}}else{this.m_root=sibling;sibling.parent=null;this.FreeNode(node2)}};b2DynamicTreeBroadPhase.b2DynamicTreeBroadPhase=function(){this.m_tree=new b2DynamicTree;this.m_moveBuffer=new Vector;this.m_pairBuffer=new Vector;this.m_pairCount=0};b2DynamicTreeBroadPhase.prototype.CreateProxy=function(aabb,userData){var proxy=this.m_tree.CreateProxy(aabb,userData);++this.m_proxyCount;this.BufferMove(proxy);return proxy};b2DynamicTreeBroadPhase.prototype.DestroyProxy=function(proxy){this.UnBufferMove(proxy);--this.m_proxyCount;this.m_tree.DestroyProxy(proxy)};b2DynamicTreeBroadPhase.prototype.MoveProxy=function(proxy,aabb,displacement){var buffer=this.m_tree.MoveProxy(proxy,aabb,displacement);if(buffer){this.BufferMove(proxy)}};b2DynamicTreeBroadPhase.prototype.TestOverlap=function(proxyA,proxyB){var aabbA=this.m_tree.GetFatAABB(proxyA);var aabbB=this.m_tree.GetFatAABB(proxyB);return aabbA.TestOverlap(aabbB)};b2DynamicTreeBroadPhase.prototype.GetUserData=function(proxy){return this.m_tree.GetUserData(proxy)};b2DynamicTreeBroadPhase.prototype.GetFatAABB=function(proxy){return this.m_tree.GetFatAABB(proxy)};b2DynamicTreeBroadPhase.prototype.GetProxyCount=function(){return this.m_proxyCount};b2DynamicTreeBroadPhase.prototype.UpdatePairs=function(callback){var __this=this;__this.m_pairCount=0;var i=0;var queryProxy;for(i=0;i<__this.m_moveBuffer.length;++i){queryProxy=__this.m_moveBuffer[i];function QueryCallback(proxy){if(proxy==queryProxy)return true;if(__this.m_pairCount==__this.m_pairBuffer.length){__this.m_pairBuffer[__this.m_pairCount]=new b2DynamicTreePair}var pair=__this.m_pairBuffer[__this.m_pairCount];pair.proxyA=proxy=queryProxy?proxy:queryProxy;++__this.m_pairCount;return true}var fatAABB=__this.m_tree.GetFatAABB(queryProxy);__this.m_tree.Query(QueryCallback,fatAABB)}__this.m_moveBuffer.length=0;for(var i=0;i<__this.m_pairCount;){var primaryPair=__this.m_pairBuffer[i];var userDataA=__this.m_tree.GetUserData(primaryPair.proxyA);var userDataB=__this.m_tree.GetUserData(primaryPair.proxyB);callback(userDataA,userDataB);++i;var x=0;while(i<__this.m_pairCount){x++;if(x>10000){console.log("1824")}var pair=__this.m_pairBuffer[i];if(pair.proxyA!=primaryPair.proxyA||pair.proxyB!=primaryPair.proxyB){break}++i}}};b2DynamicTreeBroadPhase.prototype.Query=function(callback,aabb){this.m_tree.Query(callback,aabb)};b2DynamicTreeBroadPhase.prototype.RayCast=function(callback,input){this.m_tree.RayCast(callback,input)};b2DynamicTreeBroadPhase.prototype.Validate=function(){};b2DynamicTreeBroadPhase.prototype.Rebalance=function(iterations){if(iterations===undefined)iterations=0;this.m_tree.Rebalance(iterations)};b2DynamicTreeBroadPhase.prototype.BufferMove=function(proxy){this.m_moveBuffer[this.m_moveBuffer.length]=proxy};b2DynamicTreeBroadPhase.prototype.UnBufferMove=function(proxy){var i=parseInt(this.m_moveBuffer.indexOf(proxy));this.m_moveBuffer.splice(i,1)};b2DynamicTreeBroadPhase.prototype.ComparePairs=function(pair1,pair2){return 0};b2DynamicTreeBroadPhase.__implements={};b2DynamicTreeBroadPhase.__implements[IBroadPhase]=true;b2DynamicTreeNode.b2DynamicTreeNode=function(){this.aabb=new b2AABB};b2DynamicTreeNode.prototype.IsLeaf=function(){return this.child1==null};b2DynamicTreePair.b2DynamicTreePair=function(){};b2Manifold.b2Manifold=function(){this.m_pointCount=0};b2Manifold.prototype.b2Manifold=function(){this.m_points=new Vector(b2Settings.b2_maxManifoldPoints);for(var i=0;ik_slop){var bX=s.x-this.p1.x;var bY=s.y-this.p1.y;var a=bX*nX+bY*nY;if(a>=0&&a<=maxLambda*denom){var mu2=-rX*bY+rY*bX;if(-k_slop*denom<=mu2&&mu2<=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};b2Segment.prototype.Extend=function(aabb){this.ExtendForward(aabb);this.ExtendBackward(aabb)};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>0?(aabb.upperBound.x-this.p1.x)/dX:dX<0?(aabb.lowerBound.x-this.p1.x)/dX:Number.POSITIVE_INFINITY,dY>0?(aabb.upperBound.y-this.p1.y)/dY:dY<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};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>0?(aabb.upperBound.x-this.p2.x)/dX:dX<0?(aabb.lowerBound.x-this.p2.x)/dX:Number.POSITIVE_INFINITY,dY>0?(aabb.upperBound.y-this.p2.y)/dY:dY<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};b2SeparationFunction.b2SeparationFunction=function(){this.m_localPoint=new b2Vec2;this.m_axis=new b2Vec2};b2SeparationFunction.prototype.Initialize=function(cache,proxyA,transformA,proxyB,transformB){this.m_proxyA=proxyA;this.m_proxyB=proxyB;var count=parseInt(cache.count);b2Settings.b2Assert(count>0&&count<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=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=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=0.5*(localPointA1.x+localPointA2.x);this.m_localPoint.y=0.5*(localPointA1.y+localPointA2.y);this.m_axis=b2Math.CrossVF(b2Math.SubtractVV(localPointA2,localPointA1),1);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<0){this.m_axis.NegativeSelf()}}else if(cache.indexA[0]==cache.indexA[0]){this.m_type=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=0.5*(localPointB1.x+localPointB2.x);this.m_localPoint.y=0.5*(localPointB1.y+localPointB2.y);this.m_axis=b2Math.CrossVF(b2Math.SubtractVV(localPointB2,localPointB1),1);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<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 pA=b2Math.MulX(transformA,localPointA);var dA=b2Math.MulMV(transformA.R,b2Math.SubtractVV(localPointA2,localPointA1));var pB=b2Math.MulX(transformB,localPointB);var dB=b2Math.MulMV(transformB.R,b2Math.SubtractVV(localPointB2,localPointB1));var a=dA.x*dA.x+dA.y*dA.y;var e=dB.x*dB.x+dB.y*dB.y;var r=b2Math.SubtractVV(dB,dA);var c=dA.x*r.x+dA.y*r.y;var f=dB.x*r.x+dB.y*r.y;var b=dA.x*dB.x+dA.y*dB.y;var denom=a*e-b*b;s=0;if(denom!=0){s=b2Math.Clamp((b*f-c*e)/denom,0,1)}var t=(b*s+f)/e;if(t<0){t=0;s=b2Math.Clamp((b-c)/a,0,1)}localPointA=new b2Vec2;localPointA.x=localPointA1.x+s*(localPointA2.x-localPointA1.x);localPointA.y=localPointA1.y+s*(localPointA2.y-localPointA1.y);localPointB=new b2Vec2;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=b2SeparationFunction.e_faceB;this.m_axis=b2Math.CrossVF(b2Math.SubtractVV(localPointB2,localPointB1),1);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<0){this.m_axis.NegativeSelf()}}else{this.m_type=b2SeparationFunction.e_faceA;this.m_axis=b2Math.CrossVF(b2Math.SubtractVV(localPointA2,localPointA1),1);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<0){this.m_axis.NegativeSelf()}}}};b2SeparationFunction.prototype.Evaluate=function(transformA,transformB){var axisA;var axisB;var localPointA;var localPointB;var pointA;var pointB;var seperation=0;var normal;switch(this.m_type){case b2SeparationFunction.e_points:{axisA=b2Math.MulTMV(transformA.R,this.m_axis);axisB=b2Math.MulTMV(transformB.R,this.m_axis.GetNegative());localPointA=this.m_proxyA.GetSupportVertex(axisA);localPointB=this.m_proxyB.GetSupportVertex(axisB);pointA=b2Math.MulX(transformA,localPointA);pointB=b2Math.MulX(transformB,localPointB);seperation=(pointB.x-pointA.x)*this.m_axis.x+(pointB.y-pointA.y)*this.m_axis.y;return seperation}case b2SeparationFunction.e_faceA:{normal=b2Math.MulMV(transformA.R,this.m_axis);pointA=b2Math.MulX(transformA,this.m_localPoint);axisB=b2Math.MulTMV(transformB.R,normal.GetNegative());localPointB=this.m_proxyB.GetSupportVertex(axisB);pointB=b2Math.MulX(transformB,localPointB);seperation=(pointB.x-pointA.x)*normal.x+(pointB.y-pointA.y)*normal.y;return seperation}case b2SeparationFunction.e_faceB:{normal=b2Math.MulMV(transformB.R,this.m_axis);pointB=b2Math.MulX(transformB,this.m_localPoint);axisA=b2Math.MulTMV(transformA.R,normal.GetNegative());localPointA=this.m_proxyA.GetSupportVertex(axisA);pointA=b2Math.MulX(transformA,localPointA);seperation=(pointA.x-pointB.x)*normal.x+(pointA.y-pointB.y)*normal.y;return seperation}default:b2Settings.b2Assert(false);return 0;}};$i_108.postDefs.push(function(){$i_108.Collision.b2SeparationFunction.e_points=1;$i_108.Collision.b2SeparationFunction.e_faceA=2;$i_108.Collision.b2SeparationFunction.e_faceB=4});b2Simplex.b2Simplex=function(){this.m_v1=new b2SimplexVertex;this.m_v2=new b2SimplexVertex;this.m_v3=new b2SimplexVertex;this.m_vertices=new Vector(3)};b2Simplex.prototype.b2Simplex=function(){this.m_vertices[0]=this.m_v1;this.m_vertices[1]=this.m_v2;this.m_vertices[2]=this.m_v3};b2Simplex.prototype.ReadCache=function(cache,proxyA,transformA,proxyB,transformB){b2Settings.b2Assert(cache.count>=0&&cache.count<=3);var wALocal;var wBLocal;this.m_count=cache.count;var vertices=this.m_vertices;for(var i=0;i1){var metric1=cache.metric;var metric2=this.GetMetric();if(metric2<0.5*metric1||2*metric10){return b2Math.CrossFV(1,e12)}else{return b2Math.CrossVF(e12,1)}}default:b2Settings.b2Assert(false);return new b2Vec2;}};b2Simplex.prototype.GetClosestPoint=function(){switch(this.m_count){case 0:b2Settings.b2Assert(false);return new b2Vec2;case 1:return this.m_v1.w;case 2:return new b2Vec2(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);default:b2Settings.b2Assert(false);return new b2Vec2;}};b2Simplex.prototype.GetWitnessPoints=function(pA,pB){switch(this.m_count){case 0:b2Settings.b2Assert(false);break;case 1:pA.SetV(this.m_v1.wA);pB.SetV(this.m_v1.wB);break;case 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;break;case 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;break;default:b2Settings.b2Assert(false);break;}};b2Simplex.prototype.GetMetric=function(){switch(this.m_count){case 0:b2Settings.b2Assert(false);return 0;case 1:return 0;case 2:return b2Math.SubtractVV(this.m_v1.w,this.m_v2.w).Length();case 3:return b2Math.CrossVV(b2Math.SubtractVV(this.m_v2.w,this.m_v1.w),b2Math.SubtractVV(this.m_v3.w,this.m_v1.w));default:b2Settings.b2Assert(false);return 0;}};b2Simplex.prototype.Solve2=function(){var w1=this.m_v1.w;var w2=this.m_v2.w;var e12=b2Math.SubtractVV(w2,w1);var d12_2=-(w1.x*e12.x+w1.y*e12.y);if(d12_2<=0){this.m_v1.a=1;this.m_count=1;return}var d12_1=w2.x*e12.x+w2.y*e12.y;if(d12_1<=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};b2Simplex.prototype.Solve3=function(){var w1=this.m_v1.w;var w2=this.m_v2.w;var w3=this.m_v3.w;var e12=b2Math.SubtractVV(w2,w1);var w1e12=b2Math.Dot(w1,e12);var w2e12=b2Math.Dot(w2,e12);var d12_1=w2e12;var d12_2=-w1e12;var e13=b2Math.SubtractVV(w3,w1);var w1e13=b2Math.Dot(w1,e13);var w3e13=b2Math.Dot(w3,e13);var d13_1=w3e13;var d13_2=-w1e13;var e23=b2Math.SubtractVV(w3,w2);var w2e23=b2Math.Dot(w2,e23);var w3e23=b2Math.Dot(w3,e23);var d23_1=w3e23;var d23_2=-w2e23;var n123=b2Math.CrossVV(e12,e13);var d123_1=n123*b2Math.CrossVV(w2,w3);var d123_2=n123*b2Math.CrossVV(w3,w1);var d123_3=n123*b2Math.CrossVV(w1,w2);if(d12_2<=0&&d13_2<=0){this.m_v1.a=1;this.m_count=1;return}if(d12_1>0&&d12_2>0&&d123_3<=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>0&&d13_2>0&&d123_2<=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<=0&&d23_2<=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Set(this.m_v2);return}if(d13_1<=0&&d23_1<=0){this.m_v3.a=1;this.m_count=1;this.m_v1.Set(this.m_v3);return}if(d23_1>0&&d23_2>0&&d123_1<=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};b2SimplexCache.b2SimplexCache=function(){this.indexA=new Vector_a2j_Number(3);this.indexB=new Vector_a2j_Number(3)};b2SimplexVertex.b2SimplexVertex=function(){};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};b2TimeOfImpact.b2TimeOfImpact=function(){};b2TimeOfImpact.TimeOfImpact=function(input){++b2TimeOfImpact.b2_toiCalls;var proxyA=input.proxyA;var proxyB=input.proxyB;var sweepA=input.sweepA;var sweepB=input.sweepB;b2Settings.b2Assert(sweepA.t0==sweepB.t0);b2Settings.b2Assert(1-sweepA.t0>Number.MIN_VALUE);var radius=proxyA.m_radius+proxyB.m_radius;var tolerance=input.tolerance;var alpha=0;var k_maxIterations=1000;var iter=0;var target=0;b2TimeOfImpact.s_cache.count=0;b2TimeOfImpact.s_distanceInput.useRadii=false;for(;;){sweepA.GetTransform(b2TimeOfImpact.s_xfA,alpha);sweepB.GetTransform(b2TimeOfImpact.s_xfB,alpha);b2TimeOfImpact.s_distanceInput.proxyA=proxyA;b2TimeOfImpact.s_distanceInput.proxyB=proxyB;b2TimeOfImpact.s_distanceInput.transformA=b2TimeOfImpact.s_xfA;b2TimeOfImpact.s_distanceInput.transformB=b2TimeOfImpact.s_xfB;b2Distance.Distance(b2TimeOfImpact.s_distanceOutput,b2TimeOfImpact.s_cache,b2TimeOfImpact.s_distanceInput);if(b2TimeOfImpact.s_distanceOutput.distance<=0){alpha=1;break}b2TimeOfImpact.s_fcn.Initialize(b2TimeOfImpact.s_cache,proxyA,b2TimeOfImpact.s_xfA,proxyB,b2TimeOfImpact.s_xfB);var separation=b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA,b2TimeOfImpact.s_xfB);if(separation<=0){alpha=1;break}if(iter==0){if(separation>radius){target=b2Math.Max(radius-tolerance,0.75*radius)}else{target=b2Math.Max(separation-tolerance,0.02*radius)}}if(separation-target<0.5*tolerance){if(iter==0){alpha=1;break}break}var newAlpha=alpha;{var x1=alpha;var x2=1;var f1=separation;sweepA.GetTransform(b2TimeOfImpact.s_xfA,x2);sweepB.GetTransform(b2TimeOfImpact.s_xfB,x2);var f2=b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA,b2TimeOfImpact.s_xfB);if(f2>=target){alpha=1;break}var rootIterCount=0;for(;;){var x=0;if(rootIterCount&1){x=x1+(target-f1)*(x2-x1)/(f2-f1)}else{x=0.5*(x1+x2)}sweepA.GetTransform(b2TimeOfImpact.s_xfA,x);sweepB.GetTransform(b2TimeOfImpact.s_xfB,x);var f=b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA,b2TimeOfImpact.s_xfB);if(b2Math.Abs(f-target)<0.025*tolerance){newAlpha=x;break}if(f>target){x1=x;f1=f}else{x2=x;f2=f}++rootIterCount;++b2TimeOfImpact.b2_toiRootIters;if(rootIterCount==50){break}}b2TimeOfImpact.b2_toiMaxRootIters=b2Math.Max(b2TimeOfImpact.b2_toiMaxRootIters,rootIterCount)}if(newAlpha<(1+100*Number.MIN_VALUE)*alpha){break}alpha=newAlpha;iter++;++b2TimeOfImpact.b2_toiIters;if(iter==k_maxIterations){break}}b2TimeOfImpact.b2_toiMaxIters=b2Math.Max(b2TimeOfImpact.b2_toiMaxIters,iter);return alpha};$i_108.postDefs.push(function(){$i_108.Collision.b2TimeOfImpact.b2_toiCalls=0;$i_108.Collision.b2TimeOfImpact.b2_toiIters=0;$i_108.Collision.b2TimeOfImpact.b2_toiMaxIters=0;$i_108.Collision.b2TimeOfImpact.b2_toiRootIters=0;$i_108.Collision.b2TimeOfImpact.b2_toiMaxRootIters=0;$i_108.Collision.b2TimeOfImpact.s_cache=new b2SimplexCache;$i_108.Collision.b2TimeOfImpact.s_distanceInput=new b2DistanceInput;$i_108.Collision.b2TimeOfImpact.s_xfA=new b2Transform;$i_108.Collision.b2TimeOfImpact.s_xfB=new b2Transform;$i_108.Collision.b2TimeOfImpact.s_fcn=new b2SeparationFunction;$i_108.Collision.b2TimeOfImpact.s_distanceOutput=new b2DistanceOutput});b2TOIInput.b2TOIInput=function(){this.proxyA=new b2DistanceProxy;this.proxyB=new b2DistanceProxy;this.sweepA=new b2Sweep;this.sweepB=new b2Sweep};b2WorldManifold.b2WorldManifold=function(){this.m_normal=new b2Vec2};b2WorldManifold.prototype.b2WorldManifold=function(){this.m_points=new Vector(b2Settings.b2_maxManifoldPoints);for(var i=0;iNumber.MIN_VALUE*Number.MIN_VALUE){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=0.5*(cAX+cBX);this.m_points[0].y=0.5*(cAY+cBY)}break;case 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=0&&a<=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};b2CircleShape.prototype.ComputeAABB=function(aabb,transform){var tMat=transform.R;var pX=transform.position.x+(tMat.col1.x*this.m_p.x+tMat.col2.x*this.m_p.y);var pY=transform.position.y+(tMat.col1.y*this.m_p.x+tMat.col2.y*this.m_p.y);aabb.lowerBound.Set(pX-this.m_radius,pY-this.m_radius);aabb.upperBound.Set(pX+this.m_radius,pY+this.m_radius)};b2CircleShape.prototype.ComputeMass=function(massData,density){if(density===undefined)density=0;massData.mass=density*b2Settings.b2_pi*this.m_radius*this.m_radius;massData.center.SetV(this.m_p);massData.I=massData.mass*(0.5*this.m_radius*this.m_radius+(this.m_p.x*this.m_p.x+this.m_p.y*this.m_p.y))};b2CircleShape.prototype.ComputeSubmergedArea=function(normal,offset,xf,c){if(offset===undefined)offset=0;var p=b2Math.MulX(xf,this.m_p);var l=-(b2Math.Dot(normal,p)-offset);if(l<-this.m_radius+Number.MIN_VALUE){return 0}if(l>this.m_radius){c.SetV(p);return Math.PI*this.m_radius*this.m_radius}var r2=this.m_radius*this.m_radius;var l2=l*l;var area=r2*(Math.asin(l/this.m_radius)+Math.PI/2)+l*Math.sqrt(r2-l2);var com=-2/3*Math.pow(r2-l2,1.5)/area;c.x=p.x+normal.x*com;c.y=p.y+normal.y*com;return area};b2CircleShape.prototype.GetLocalPosition=function(){return this.m_p};b2CircleShape.prototype.SetLocalPosition=function(position){this.m_p.SetV(position)};b2CircleShape.prototype.GetRadius=function(){return this.m_radius};b2CircleShape.prototype.SetRadius=function(radius){if(radius===undefined)radius=0;this.m_radius=radius};b2CircleShape.prototype.b2CircleShape=function(radius){if(radius===undefined)radius=0;this.__super.b2Shape.call(this);this.m_type=b2Shape.e_circleShape;this.m_radius=radius};b2EdgeChainDef.b2EdgeChainDef=function(){};b2EdgeChainDef.prototype.b2EdgeChainDef=function(){this.vertexCount=0;this.isALoop=true;this.vertices=[]};$i_108.inherit(b2EdgeShape,$i_108.Collision.Shapes.b2Shape);b2EdgeShape.prototype.__super=$i_108.Collision.Shapes.b2Shape.prototype;b2EdgeShape.b2EdgeShape=function(){$i_108.Collision.Shapes.b2Shape.b2Shape.apply(this,arguments);this.s_supportVec=new b2Vec2;this.m_v1=new b2Vec2;this.m_v2=new b2Vec2;this.m_coreV1=new b2Vec2;this.m_coreV2=new b2Vec2;this.m_normal=new b2Vec2;this.m_direction=new b2Vec2;this.m_cornerDir1=new b2Vec2;this.m_cornerDir2=new b2Vec2};b2EdgeShape.prototype.TestPoint=function(transform,p){return false};b2EdgeShape.prototype.RayCast=function(output,input,transform){var tMat;var rX=input.p2.x-input.p1.x;var rY=input.p2.y-input.p1.y;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>k_slop){var bX=input.p1.x-v1X;var bY=input.p1.y-v1Y;var a=bX*nX+bY*nY;if(a>=0&&a<=input.maxFraction*denom){var mu2=-rX*bY+rY*bX;if(-k_slop*denom<=mu2&&mu2<=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};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(v1X0){if(d2>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>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}else{}}c.x=(v0.x+v1.x+v2.x)/3;c.y=(v0.y+v1.y+v2.y)/3;return 0.5*((v1.x-v0.x)*(v2.y-v0.y)-(v1.y-v0.y)*(v2.x-v0.x))};b2EdgeShape.prototype.GetLength=function(){return this.m_length};b2EdgeShape.prototype.GetVertex1=function(){return this.m_v1};b2EdgeShape.prototype.GetVertex2=function(){return this.m_v2};b2EdgeShape.prototype.GetCoreVertex1=function(){return this.m_coreV1};b2EdgeShape.prototype.GetCoreVertex2=function(){return this.m_coreV2};b2EdgeShape.prototype.GetNormalVector=function(){return this.m_normal};b2EdgeShape.prototype.GetDirectionVector=function(){return this.m_direction};b2EdgeShape.prototype.GetCorner1Vector=function(){return this.m_cornerDir1};b2EdgeShape.prototype.GetCorner2Vector=function(){return this.m_cornerDir2};b2EdgeShape.prototype.Corner1IsConvex=function(){return this.m_cornerConvex1};b2EdgeShape.prototype.Corner2IsConvex=function(){return this.m_cornerConvex2};b2EdgeShape.prototype.GetFirstVertex=function(xf){var tMat=xf.R;return new b2Vec2(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))};b2EdgeShape.prototype.GetNextEdge=function(){return this.m_nextEdge};b2EdgeShape.prototype.GetPrevEdge=function(){return this.m_prevEdge};b2EdgeShape.prototype.Support=function(xf,dX,dY){if(dX===undefined)dX=0;if(dY===undefined)dY=0;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>v2X*dX+v2Y*dY){this.s_supportVec.x=v1X;this.s_supportVec.y=v1Y}else{this.s_supportVec.x=v2X;this.s_supportVec.y=v2Y}return this.s_supportVec};b2EdgeShape.prototype.b2EdgeShape=function(v1,v2){this.__super.b2Shape.call(this);this.m_type=b2Shape.e_edgeShape;this.m_prevEdge=null;this.m_nextEdge=null;this.m_v1=v1;this.m_v2=v2;this.m_direction.Set(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.Set(this.m_direction.y,-this.m_direction.x);this.m_coreV1.Set(-b2Settings.b2_toiSlop*(this.m_normal.x-this.m_direction.x)+this.m_v1.x,-b2Settings.b2_toiSlop*(this.m_normal.y-this.m_direction.y)+this.m_v1.y);this.m_coreV2.Set(-b2Settings.b2_toiSlop*(this.m_normal.x+this.m_direction.x)+this.m_v2.x,-b2Settings.b2_toiSlop*(this.m_normal.y+this.m_direction.y)+this.m_v2.y);this.m_cornerDir1=this.m_normal;this.m_cornerDir2.Set(-this.m_normal.x,-this.m_normal.y)};b2EdgeShape.prototype.SetPrevEdge=function(edge,core,cornerDir,convex){this.m_prevEdge=edge;this.m_coreV1=core;this.m_cornerDir1=cornerDir;this.m_cornerConvex1=convex};b2EdgeShape.prototype.SetNextEdge=function(edge,core,cornerDir,convex){this.m_nextEdge=edge;this.m_coreV2=core;this.m_cornerDir2=cornerDir;this.m_cornerConvex2=convex};b2MassData.b2MassData=function(){this.mass=0;this.center=new b2Vec2(0,0);this.I=0};$i_108.inherit(b2PolygonShape,$i_108.Collision.Shapes.b2Shape);b2PolygonShape.prototype.__super=$i_108.Collision.Shapes.b2Shape.prototype;b2PolygonShape.b2PolygonShape=function(){$i_108.Collision.Shapes.b2Shape.b2Shape.apply(this,arguments)};b2PolygonShape.prototype.Copy=function(){var s=new b2PolygonShape;s.Set(this);return s};b2PolygonShape.prototype.Set=function(other){this.__super.Set.call(this,other);if($i_108.is(other,b2PolygonShape)){var other2=other instanceof b2PolygonShape?other:null;this.m_centroid.SetV(other2.m_centroid);this.m_vertexCount=other2.m_vertexCount;this.Reserve(this.m_vertexCount);for(var i=0;i=2);this.m_vertexCount=vertexCount;this.Reserve(vertexCount);var i=0;for(i=0;iNumber.MIN_VALUE);this.m_normals[i].SetV(b2Math.CrossVF(edge,1));this.m_normals[i].Normalize()}this.m_centroid=b2PolygonShape.ComputeCentroid(this.m_vertices,this.m_vertexCount)};b2PolygonShape.AsVector=function(vertices,vertexCount){if(vertexCount===undefined)vertexCount=0;var polygonShape=new b2PolygonShape;polygonShape.SetAsVector(vertices,vertexCount);return polygonShape};b2PolygonShape.prototype.SetAsBox=function(hx,hy){if(hx===undefined)hx=0;if(hy===undefined)hy=0;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()};b2PolygonShape.AsBox=function(hx,hy){if(hx===undefined)hx=0;if(hy===undefined)hy=0;var polygonShape=new b2PolygonShape;polygonShape.SetAsBox(hx,hy);return polygonShape};b2PolygonShape.prototype.SetAsOrientedBox=function(hx,hy,center,angle){if(hx===undefined)hx=0;if(hy===undefined)hy=0;if(center===undefined)center=null;if(angle===undefined)angle=0;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 xf=new b2Transform;xf.position=center;xf.R.Set(angle);for(var i=0;i0){return false}}return true};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=parseInt(-1);for(var i=0;i0&&numerator=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};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;ivX?upperX:vX;upperY=upperY>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};b2PolygonShape.prototype.ComputeMass=function(massData,density){if(density===undefined)density=0;if(this.m_vertexCount==2){massData.center.x=0.5*(this.m_vertices[0].x+this.m_vertices[1].x);massData.center.y=0.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;i0){if(isSubmerged){if(!lastSubmerged){intoIndex=i-1;diveCount++}}else{if(lastSubmerged){outoIndex=i-1;diveCount++}}}lastSubmerged=isSubmerged}switch(diveCount){case 0:if(lastSubmerged){var md=new b2MassData;this.ComputeMass(md,1);c.SetV(b2Math.MulX(xf,md.center));return md.mass}else{return 0}break;case 1:if(intoIndex==-1){intoIndex=this.m_vertexCount-1}else{outoIndex=this.m_vertexCount-1}break;}var intoIndex2=parseInt((intoIndex+1)%this.m_vertexCount);var outoIndex2=parseInt((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=new b2Vec2(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=new b2Vec2(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=new b2Vec2;var p2=this.m_vertices[intoIndex2];var p3;i=intoIndex2;var x=0;while(i!=outoIndex2){x++;if(x>10000){console.log("3466")}i=(i+1)%this.m_vertexCount;if(i==outoIndex2)p3=outoVec;else p3=this.m_vertices[i];var triangleArea=0.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}center.Multiply(1/area);c.SetV(b2Math.MulX(xf,center));return area};b2PolygonShape.prototype.GetVertexCount=function(){return this.m_vertexCount};b2PolygonShape.prototype.GetVertices=function(){return this.m_vertices};b2PolygonShape.prototype.GetNormals=function(){return this.m_normals};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;ibestValue){bestIndex=i;bestValue=value}}return bestIndex};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;ibestValue){bestIndex=i;bestValue=value}}return this.m_vertices[bestIndex]};b2PolygonShape.prototype.Validate=function(){return false};b2PolygonShape.prototype.b2PolygonShape=function(){this.__super.b2Shape.call(this);this.m_type=b2Shape.e_polygonShape;this.m_centroid=new b2Vec2;this.m_vertices=new Vector;this.m_normals=new Vector};b2PolygonShape.prototype.Reserve=function(count){if(count===undefined)count=0;for(var i=parseInt(this.m_vertices.length);iupperX)upperX=rX;if(rY>upperY)upperY=rY}var area=(upperX-lowerX)*(upperY-lowerY);if(area<0.95*minArea){minArea=area;obb.R.col1.x=uxX;obb.R.col1.y=uxY;obb.R.col2.x=uyX;obb.R.col2.y=uyY;var centerX=0.5*(lowerX+upperX);var centerY=0.5*(lowerY+upperY);var tMat=obb.R;obb.center.x=root.x+(tMat.col1.x*centerX+tMat.col2.x*centerY);obb.center.y=root.y+(tMat.col1.y*centerX+tMat.col2.y*centerY);obb.extents.x=0.5*(upperX-lowerX);obb.extents.y=0.5*(upperY-lowerY)}}};$i_108.postDefs.push(function(){$i_108.Collision.Shapes.b2PolygonShape.s_mat=new b2Mat22});b2Shape.b2Shape=function(){};b2Shape.prototype.Copy=function(){return null};b2Shape.prototype.Set=function(other){this.m_radius=other.m_radius};b2Shape.prototype.GetType=function(){return this.m_type};b2Shape.prototype.TestPoint=function(xf,p){return false};b2Shape.prototype.RayCast=function(output,input,transform){return false};b2Shape.prototype.ComputeAABB=function(aabb,xf){};b2Shape.prototype.ComputeMass=function(massData,density){if(density===undefined)density=0};b2Shape.prototype.ComputeSubmergedArea=function(normal,offset,xf,c){if(offset===undefined)offset=0;return 0};b2Shape.TestOverlap=function(shape1,transform1,shape2,transform2){var input=new b2DistanceInput;input.proxyA=new b2DistanceProxy;input.proxyA.Set(shape1);input.proxyB=new b2DistanceProxy;input.proxyB.Set(shape2);input.transformA=transform1;input.transformB=transform2;input.useRadii=true;var simplexCache=new b2SimplexCache;simplexCache.count=0;var output=new b2DistanceOutput;b2Distance.Distance(output,simplexCache,input);return output.distance<10*Number.MIN_VALUE};b2Shape.prototype.b2Shape=function(){this.m_type=b2Shape.e_unknownShape;this.m_radius=b2Settings.b2_linearSlop};$i_108.postDefs.push(function(){$i_108.Collision.Shapes.b2Shape.e_unknownShape=parseInt(-1);$i_108.Collision.Shapes.b2Shape.e_circleShape=0;$i_108.Collision.Shapes.b2Shape.e_polygonShape=1;$i_108.Collision.Shapes.b2Shape.e_edgeShape=2;$i_108.Collision.Shapes.b2Shape.e_shapeTypeCount=3;$i_108.Collision.Shapes.b2Shape.e_hitCollide=1;$i_108.Collision.Shapes.b2Shape.e_missCollide=0;$i_108.Collision.Shapes.b2Shape.e_startsInsideCollide=parseInt(-1)})})();(function(){var b2Color=$i_108.Common.b2Color;var b2internal=$i_108.Common.b2internal;var b2Settings=$i_108.Common.b2Settings;var b2Mat22=$i_108.Common.Math.b2Mat22;var b2Mat33=$i_108.Common.Math.b2Mat33;var b2Math=$i_108.Common.Math.b2Math;var b2Sweep=$i_108.Common.Math.b2Sweep;var b2Transform=$i_108.Common.Math.b2Transform;var b2Vec2=$i_108.Common.Math.b2Vec2;var b2Vec3=$i_108.Common.Math.b2Vec3;b2Color.b2Color=function(){this._r=0;this._g=0;this._b=0};b2Color.prototype.b2Color=function(rr,gg,bb){if(rr===undefined)rr=0;if(gg===undefined)gg=0;if(bb===undefined)bb=0;this._r=$i_108.parseUInt(255*b2Math.Clamp(rr,0,1));this._g=$i_108.parseUInt(255*b2Math.Clamp(gg,0,1));this._b=$i_108.parseUInt(255*b2Math.Clamp(bb,0,1))};b2Color.prototype.Set=function(rr,gg,bb){if(rr===undefined)rr=0;if(gg===undefined)gg=0;if(bb===undefined)bb=0;this._r=$i_108.parseUInt(255*b2Math.Clamp(rr,0,1));this._g=$i_108.parseUInt(255*b2Math.Clamp(gg,0,1));this._b=$i_108.parseUInt(255*b2Math.Clamp(bb,0,1))};Object.defineProperty(b2Color.prototype,"r",{enumerable:false,configurable:true,set:function(rr){if(rr===undefined)rr=0;this._r=$i_108.parseUInt(255*b2Math.Clamp(rr,0,1))}});Object.defineProperty(b2Color.prototype,"g",{enumerable:false,configurable:true,set:function(gg){if(gg===undefined)gg=0;this._g=$i_108.parseUInt(255*b2Math.Clamp(gg,0,1))}});Object.defineProperty(b2Color.prototype,"b",{enumerable:false,configurable:true,set:function(bb){if(bb===undefined)bb=0;this._b=$i_108.parseUInt(255*b2Math.Clamp(bb,0,1))}});Object.defineProperty(b2Color.prototype,"color",{enumerable:false,configurable:true,get:function(){return this._r<<16|this._g<<8|this._b}});b2Settings.b2Settings=function(){};b2Settings.b2MixFriction=function(friction1,friction2){if(friction1===undefined)friction1=0;if(friction2===undefined)friction2=0;return Math.sqrt(friction1*friction2)};b2Settings.b2MixRestitution=function(restitution1,restitution2){if(restitution1===undefined)restitution1=0;if(restitution2===undefined)restitution2=0;return restitution1>restitution2?restitution1:restitution2};b2Settings.b2Assert=function(a){if(!a){console.log("Assertion Failed",a);throw"Assertion Failed"}};$i_108.postDefs.push(function(){$i_108.Common.b2Settings.VERSION="2.1alpha";$i_108.Common.b2Settings.USHRT_MAX=65535;$i_108.Common.b2Settings.b2_pi=Math.PI;$i_108.Common.b2Settings.b2_maxManifoldPoints=2;$i_108.Common.b2Settings.b2_aabbExtension=0.1;$i_108.Common.b2Settings.b2_aabbMultiplier=2;$i_108.Common.b2Settings.b2_polygonRadius=2*b2Settings.b2_linearSlop;$i_108.Common.b2Settings.b2_linearSlop=0.005;$i_108.Common.b2Settings.b2_angularSlop=2/180*b2Settings.b2_pi;$i_108.Common.b2Settings.b2_toiSlop=8*b2Settings.b2_linearSlop;$i_108.Common.b2Settings.b2_maxTOIContactsPerIsland=32;$i_108.Common.b2Settings.b2_maxTOIJointsPerIsland=32;$i_108.Common.b2Settings.b2_velocityThreshold=1;$i_108.Common.b2Settings.b2_maxLinearCorrection=0.2;$i_108.Common.b2Settings.b2_maxAngularCorrection=8/180*b2Settings.b2_pi;$i_108.Common.b2Settings.b2_maxTranslation=500;$i_108.Common.b2Settings.b2_maxTranslationSquared=b2Settings.b2_maxTranslation*b2Settings.b2_maxTranslation;$i_108.Common.b2Settings.b2_maxRotation=0.5*b2Settings.b2_pi;$i_108.Common.b2Settings.b2_maxRotationSquared=b2Settings.b2_maxRotation*b2Settings.b2_maxRotation;$i_108.Common.b2Settings.b2_contactBaumgarte=0.2;$i_108.Common.b2Settings.b2_timeToSleep=0.5;$i_108.Common.b2Settings.b2_linearSleepTolerance=0.01;$i_108.Common.b2Settings.b2_angularSleepTolerance=2/180*b2Settings.b2_pi})})();(function(){var b2AABB=$i_108.Collision.b2AABB;var b2Color=$i_108.Common.b2Color;var b2internal=$i_108.Common.b2internal;var b2Settings=$i_108.Common.b2Settings;var b2Mat22=$i_108.Common.Math.b2Mat22;var b2Mat33=$i_108.Common.Math.b2Mat33;var b2Math=$i_108.Common.Math.b2Math;var b2Sweep=$i_108.Common.Math.b2Sweep;var b2Transform=$i_108.Common.Math.b2Transform;var b2Vec2=$i_108.Common.Math.b2Vec2;var b2Vec3=$i_108.Common.Math.b2Vec3;b2Mat22.b2Mat22=function(){this.col1=new b2Vec2;this.col2=new b2Vec2};b2Mat22.prototype.b2Mat22=function(){this.SetIdentity()};b2Mat22.FromAngle=function(angle){if(angle===undefined)angle=0;var mat=new b2Mat22;mat.Set(angle);return mat};b2Mat22.FromVV=function(c1,c2){var mat=new b2Mat22;mat.SetVV(c1,c2);return mat};b2Mat22.prototype.Set=function(angle){if(angle===undefined)angle=0;var c=Math.cos(angle);var s=Math.sin(angle);this.col1.x=c;this.col2.x=-s;this.col1.y=s;this.col2.y=c};b2Mat22.prototype.SetVV=function(c1,c2){this.col1.SetV(c1);this.col2.SetV(c2)};b2Mat22.prototype.Copy=function(){var mat=new b2Mat22;mat.SetM(this);return mat};b2Mat22.prototype.SetM=function(m){this.col1.SetV(m.col1);this.col2.SetV(m.col2)};b2Mat22.prototype.AddM=function(m){this.col1.x+=m.col1.x;this.col1.y+=m.col1.y;this.col2.x+=m.col2.x;this.col2.y+=m.col2.y};b2Mat22.prototype.SetIdentity=function(){this.col1.x=1;this.col2.x=0;this.col1.y=0;this.col2.y=1};b2Mat22.prototype.SetZero=function(){this.col1.x=0;this.col2.x=0;this.col1.y=0;this.col2.y=0};b2Mat22.prototype.GetAngle=function(){return Math.atan2(this.col1.y,this.col1.x)};b2Mat22.prototype.GetInverse=function(out){var a=this.col1.x;var b=this.col2.x;var c=this.col1.y;var d=this.col2.y;var det=a*d-b*c;if(det!=0){det=1/det}out.col1.x=det*d;out.col2.x=-det*b;out.col1.y=-det*c;out.col2.y=det*a;return out};b2Mat22.prototype.Solve=function(out,bX,bY){if(bX===undefined)bX=0;if(bY===undefined)bY=0;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};b2Mat22.prototype.Abs=function(){this.col1.Abs();this.col2.Abs()};b2Mat33.b2Mat33=function(){this.col1=new b2Vec3;this.col2=new b2Vec3;this.col3=new b2Vec3};b2Mat33.prototype.b2Mat33=function(c1,c2,c3){if(c1===undefined)c1=null;if(c2===undefined)c2=null;if(c3===undefined)c3=null;if(!c1&&!c2&&!c3){this.col1.SetZero();this.col2.SetZero();this.col3.SetZero()}else{this.col1.SetV(c1);this.col2.SetV(c2);this.col3.SetV(c3)}};b2Mat33.prototype.SetVVV=function(c1,c2,c3){this.col1.SetV(c1);this.col2.SetV(c2);this.col3.SetV(c3)};b2Mat33.prototype.Copy=function(){return new b2Mat33(this.col1,this.col2,this.col3)};b2Mat33.prototype.SetM=function(m){this.col1.SetV(m.col1);this.col2.SetV(m.col2);this.col3.SetV(m.col3)};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};b2Mat33.prototype.SetIdentity=function(){this.col1.x=1;this.col2.x=0;this.col3.x=0;this.col1.y=0;this.col2.y=1;this.col3.y=0;this.col1.z=0;this.col2.z=0;this.col3.z=1};b2Mat33.prototype.SetZero=function(){this.col1.x=0;this.col2.x=0;this.col3.x=0;this.col1.y=0;this.col2.y=0;this.col3.y=0;this.col1.z=0;this.col2.z=0;this.col3.z=0};b2Mat33.prototype.Solve22=function(out,bX,bY){if(bX===undefined)bX=0;if(bY===undefined)bY=0;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};b2Mat33.prototype.Solve33=function(out,bX,bY,bZ){if(bX===undefined)bX=0;if(bY===undefined)bY=0;if(bZ===undefined)bZ=0;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};b2Math.b2Math=function(){};b2Math.IsValid=function(x){if(x===undefined)x=0;return isFinite(x)};b2Math.Dot=function(a,b){return a.x*b.x+a.y*b.y};b2Math.CrossVV=function(a,b){return a.x*b.y-a.y*b.x};b2Math.CrossVF=function(a,s){if(s===undefined)s=0;var v=new b2Vec2(s*a.y,-s*a.x);return v};b2Math.CrossFV=function(s,a){if(s===undefined)s=0;var v=new b2Vec2(-s*a.y,s*a.x);return v};b2Math.MulMV=function(A,v){var u=new b2Vec2(A.col1.x*v.x+A.col2.x*v.y,A.col1.y*v.x+A.col2.y*v.y);return u};b2Math.MulTMV=function(A,v){var u=new b2Vec2(b2Math.Dot(v,A.col1),b2Math.Dot(v,A.col2));return u};b2Math.MulX=function(T,v){var a=b2Math.MulMV(T.R,v);a.x+=T.position.x;a.y+=T.position.y;return a};b2Math.MulXT=function(T,v){var a=b2Math.SubtractVV(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};b2Math.AddVV=function(a,b){var v=new b2Vec2(a.x+b.x,a.y+b.y);return v};b2Math.SubtractVV=function(a,b){var v=new b2Vec2(a.x-b.x,a.y-b.y);return v};b2Math.Distance=function(a,b){var cX=a.x-b.x;var cY=a.y-b.y;return Math.sqrt(cX*cX+cY*cY)};b2Math.DistanceSquared=function(a,b){var cX=a.x-b.x;var cY=a.y-b.y;return cX*cX+cY*cY};b2Math.MulFV=function(s,a){if(s===undefined)s=0;var v=new b2Vec2(s*a.x,s*a.y);return v};b2Math.AddMM=function(A,B){var C=b2Mat22.FromVV(b2Math.AddVV(A.col1,B.col1),b2Math.AddVV(A.col2,B.col2));return C};b2Math.MulMM=function(A,B){var C=b2Mat22.FromVV(b2Math.MulMV(A,B.col1),b2Math.MulMV(A,B.col2));return C};b2Math.MulTMM=function(A,B){var c1=new b2Vec2(b2Math.Dot(A.col1,B.col1),b2Math.Dot(A.col2,B.col1));var c2=new b2Vec2(b2Math.Dot(A.col1,B.col2),b2Math.Dot(A.col2,B.col2));var C=b2Mat22.FromVV(c1,c2);return C};b2Math.Abs=function(a){if(a===undefined)a=0;return a>0?a:-a};b2Math.AbsV=function(a){var b=new b2Vec2(b2Math.Abs(a.x),b2Math.Abs(a.y));return b};b2Math.AbsM=function(A){var B=b2Mat22.FromVV(b2Math.AbsV(A.col1),b2Math.AbsV(A.col2));return B};b2Math.Min=function(a,b){if(a===undefined)a=0;if(b===undefined)b=0;return ab?a:b};b2Math.MaxV=function(a,b){var c=new b2Vec2(b2Math.Max(a.x,b.x),b2Math.Max(a.y,b.y));return c};b2Math.Clamp=function(a,low,high){if(a===undefined)a=0;if(low===undefined)low=0;if(high===undefined)high=0;return ahigh?high:a};b2Math.ClampV=function(a,low,high){return b2Math.MaxV(low,b2Math.MinV(a,high))};b2Math.Swap=function(a,b){var tmp=a[0];a[0]=b[0];b[0]=tmp};b2Math.Random=function(){return Math.random()*2-1};b2Math.RandomRange=function(lo,hi){if(lo===undefined)lo=0;if(hi===undefined)hi=0;var r=Math.random();r=(hi-lo)*r+lo;return r};b2Math.NextPowerOfTwo=function(x){if(x===undefined)x=0;x|=x>>1&2147483647;x|=x>>2&1073741823;x|=x>>4&268435455;x|=x>>8&16777215;x|=x>>16&65535;return x+1};b2Math.IsPowerOfTwo=function(x){if(x===undefined)x=0;var result=x>0&&(x&x-1)==0;return result};$i_108.postDefs.push(function(){$i_108.Common.Math.b2Math.b2Vec2_zero=new b2Vec2(0,0);$i_108.Common.Math.b2Math.b2Mat22_identity=b2Mat22.FromVV(new b2Vec2(1,0),new b2Vec2(0,1));$i_108.Common.Math.b2Math.b2Transform_identity=new b2Transform(b2Math.b2Vec2_zero,b2Math.b2Mat22_identity)});b2Sweep.b2Sweep=function(){this.localCenter=new b2Vec2;this.c0=new b2Vec2;this.c=new b2Vec2};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};b2Sweep.prototype.Copy=function(){var copy=new 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};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};b2Sweep.prototype.Advance=function(t){if(t===undefined)t=0;if(this.t0Number.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}};b2Transform.b2Transform=function(){this.position=new b2Vec2;this.R=new b2Mat22};b2Transform.prototype.b2Transform=function(pos,r){if(pos===undefined)pos=null;if(r===undefined)r=null;if(pos){this.position.SetV(pos);this.R.SetM(r)}};b2Transform.prototype.Initialize=function(pos,r){this.position.SetV(pos);this.R.SetM(r)};b2Transform.prototype.SetIdentity=function(){this.position.SetZero();this.R.SetIdentity()};b2Transform.prototype.Set=function(x){this.position.SetV(x.position);this.R.SetM(x.R)};b2Transform.prototype.GetAngle=function(){return Math.atan2(this.R.col1.y,this.R.col1.x)};b2Vec2.b2Vec2=function(){};b2Vec2.prototype.b2Vec2=function(x_,y_){if(x_===undefined)x_=0;if(y_===undefined)y_=0;this.x=x_;this.y=y_};b2Vec2.prototype.SetZero=function(){this.x=0;this.y=0};b2Vec2.prototype.Set=function(x_,y_){if(x_===undefined)x_=0;if(y_===undefined)y_=0;this.x=x_;this.y=y_};b2Vec2.prototype.SetV=function(v){this.x=v.x;this.y=v.y};b2Vec2.prototype.GetNegative=function(){return new b2Vec2(-this.x,-this.y)};b2Vec2.prototype.NegativeSelf=function(){this.x=-this.x;this.y=-this.y};b2Vec2.Make=function(x_,y_){if(x_===undefined)x_=0;if(y_===undefined)y_=0;return new b2Vec2(x_,y_)};b2Vec2.prototype.Copy=function(){return new b2Vec2(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){if(a===undefined)a=0;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=b2Math.Dot(this,A.col1);this.y=b2Math.Dot(this,A.col2);this.x=tX};b2Vec2.prototype.CrossVF=function(s){if(s===undefined)s=0;var tX=this.x;this.x=s*this.y;this.y=-s*tX};b2Vec2.prototype.CrossFV=function(s){if(s===undefined)s=0;var tX=this.x;this.x=-s*this.y;this.y=s*tX};b2Vec2.prototype.MinV=function(b){this.x=this.xb.x?this.x:b.x;this.y=this.y>b.y?this.y:b.y};b2Vec2.prototype.Abs=function(){if(this.x<0)this.x=-this.x;if(this.y<0)this.y=-this.y};b2Vec2.prototype.Length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)};b2Vec2.prototype.LengthSquared=function(){return this.x*this.x+this.y*this.y};b2Vec2.prototype.Normalize=function(){var length=Math.sqrt(this.x*this.x+this.y*this.y);if(length0;s1.SetNextEdge(s2,core,cornerDir,convex);s2.SetPrevEdge(s1,core,cornerDir,convex);return angle2};b2Body.prototype.CreateFixture=function(def,isLossTolerant){if(this.m_world.IsLocked()==true&&!isLossTolerant){return null}var fixture=new b2Fixture;fixture.Create(this,this.m_xf,def);if(this.m_flags&b2Body.e_activeFlag){var broadPhase=this.m_world.m_contactManager.m_broadPhase;fixture.CreateProxy(broadPhase,this.m_xf)}fixture.m_next=this.m_fixtureList;this.m_fixtureList=fixture;++this.m_fixtureCount;fixture.m_body=this;if(fixture.m_density>0){this.ResetMassData()}this.m_world.m_flags|=b2World.e_newFixture;return fixture};b2Body.prototype.CreateFixture2=function(shape,density){if(density===undefined)density=0;var def=new b2FixtureDef;def.shape=shape;def.density=density;return this.CreateFixture(def)};b2Body.prototype.DestroyFixture=function(fixture){if(this.m_world.IsLocked()==true){return}var node=this.m_fixtureList;var ppF=null;var found=false;var x=0;while(node!=null){x++;if(x>10000){console.log("4514")}if(node==fixture){if(ppF)ppF.m_next=fixture.m_next;else this.m_fixtureList=fixture.m_next;found=true;break}ppF=node;node=node.m_next}var edge=this.m_contactList;var x=0;while(edge){x++;if(x>10000){console.log("4528")}var c=edge.contact;edge=edge.next;var fixtureA=c.GetFixtureA();var fixtureB=c.GetFixtureB();if(fixture==fixtureA||fixture==fixtureB){this.m_world.m_contactManager.Destroy(c)}}if(this.m_flags&b2Body.e_activeFlag){var broadPhase=this.m_world.m_contactManager.m_broadPhase;fixture.DestroyProxy(broadPhase)}else{}fixture.Destroy();fixture.m_body=null;fixture.m_next=null;--this.m_fixtureCount;this.ResetMassData()};b2Body.prototype.SetPositionAndAngle=function(position,angle){if(angle===undefined)angle=0;var f;if(this.m_world&&this.m_world.IsLocked()==true){return}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(f=this.m_fixtureList;f;f=f.m_next){f.Synchronize(broadPhase,this.m_xf,this.m_xf)}this.m_world.m_contactManager.FindNewContacts()};b2Body.prototype.SetTransform=function(xf){this.SetPositionAndAngle(xf.position,xf.GetAngle())};b2Body.prototype.GetTransform=function(){return this.m_xf};b2Body.prototype.GetPosition=function(){return this.m_xf.position};b2Body.prototype.SetPosition=function(position){this.SetPositionAndAngle(position,this.GetAngle())};b2Body.prototype.GetAngle=function(){return this.m_sweep.a};b2Body.prototype.SetAngle=function(angle){if(angle===undefined)angle=0;this.SetPositionAndAngle(this.GetPosition(),angle)};b2Body.prototype.GetWorldCenter=function(){return this.m_sweep.c};b2Body.prototype.GetLocalCenter=function(){return this.m_sweep.localCenter};b2Body.prototype.SetLinearVelocity=function(v){if(this.m_type==b2Body.b2_staticBody){return}this.m_linearVelocity.SetV(v)};b2Body.prototype.GetLinearVelocity=function(){return this.m_linearVelocity};b2Body.prototype.SetAngularVelocity=function(omega){if(omega===undefined)omega=0;if(this.m_type==b2Body.b2_staticBody){return}this.m_angularVelocity=omega};b2Body.prototype.GetAngularVelocity=function(){return this.m_angularVelocity};b2Body.prototype.GetDefinition=function(){var bd=new b2BodyDef;bd.type=this.GetType();bd.allowSleep=(this.m_flags&b2Body.e_allowSleepFlag)==b2Body.e_allowSleepFlag;bd.angle=this.GetAngle();bd.angularDamping=this.m_angularDamping;bd.angularVelocity=this.m_angularVelocity;bd.fixedRotation=(this.m_flags&b2Body.e_fixedRotationFlag)==b2Body.e_fixedRotationFlag;bd.bullet=(this.m_flags&b2Body.e_bulletFlag)==b2Body.e_bulletFlag;bd.awake=(this.m_flags&b2Body.e_awakeFlag)==b2Body.e_awakeFlag;bd.linearDamping=this.m_linearDamping;bd.linearVelocity.SetV(this.GetLinearVelocity());bd.position=this.GetPosition();bd.userData=this.GetUserData();return bd};b2Body.prototype.ApplyForce=function(force,point){if(this.m_type!=b2Body.b2_dynamicBody){return}if(this.IsAwake()==false){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};b2Body.prototype.ApplyTorque=function(torque){if(torque===undefined)torque=0;if(this.m_type!=b2Body.b2_dynamicBody){return}if(this.IsAwake()==false){this.SetAwake(true)}this.m_torque+=torque};b2Body.prototype.ApplyImpulse=function(impulse,point){if(this.m_type!=b2Body.b2_dynamicBody){return}if(this.IsAwake()==false){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)};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());var prev;for(var f=body1.m_fixtureList;f;){if(callback(f)){var next=f.m_next;if(prev){prev.m_next=next}else{body1.m_fixtureList=next}body1.m_fixtureCount--;f.m_next=body2.m_fixtureList;body2.m_fixtureList=f;body2.m_fixtureCount++;f.m_body=body2;f=next}else{prev=f;f=f.m_next}}body1.ResetMassData();body2.ResetMassData();var center1=body1.GetWorldCenter();var center2=body2.GetWorldCenter();var velocity1=b2Math.AddVV(linearVelocity,b2Math.CrossFV(angularVelocity,b2Math.SubtractVV(center1,center)));var velocity2=b2Math.AddVV(linearVelocity,b2Math.CrossFV(angularVelocity,b2Math.SubtractVV(center2,center)));body1.SetLinearVelocity(velocity1);body2.SetLinearVelocity(velocity2);body1.SetAngularVelocity(angularVelocity);body2.SetAngularVelocity(angularVelocity);body1.SynchronizeFixtures();body2.SynchronizeFixtures();return body2};b2Body.prototype.Merge=function(other){var f;for(f=other.m_fixtureList;f;){var next=f.m_next;other.m_fixtureCount--;f.m_next=this.m_fixtureList;this.m_fixtureList=f;this.m_fixtureCount++;f.m_body=body2;f=next}body1.m_fixtureCount=0;var body1=this;var body2=other;var center1=body1.GetWorldCenter();var center2=body2.GetWorldCenter();var velocity1=body1.GetLinearVelocity().Copy();var velocity2=body2.GetLinearVelocity().Copy();var angular1=body1.GetAngularVelocity();var angular=body2.GetAngularVelocity();body1.ResetMassData();this.SynchronizeFixtures()};b2Body.prototype.GetMass=function(){return this.m_mass};b2Body.prototype.GetInertia=function(){return this.m_I};b2Body.prototype.GetMassData=function(data){data.mass=this.m_mass;data.I=this.m_I;data.center.SetV(this.m_sweep.localCenter)};b2Body.prototype.SetMassData=function(massData){b2Settings.b2Assert(this.m_world.IsLocked()==false);if(this.m_world.IsLocked()==true){return}if(this.m_type!=b2Body.b2_dynamicBody){return}this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_mass=massData.mass;if(this.m_mass<=0){this.m_mass=1}this.m_invMass=1/this.m_mass;if(massData.I>0&&(this.m_flags&b2Body.e_fixedRotationFlag)==0){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(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)};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==b2Body.b2_staticBody||this.m_type==b2Body.b2_kinematicBody){return}var center=b2Vec2.Make(0,0);for(var f=this.m_fixtureList;f;f=f.m_next){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}if(this.m_mass>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>0&&(this.m_flags&b2Body.e_fixedRotationFlag)==0){this.m_I-=this.m_mass*(center.x*center.x+center.y*center.y);this.m_I*=this.m_inertiaScale;b2Settings.b2Assert(this.m_I>0);this.m_invI=1/this.m_I}else{this.m_I=0;this.m_invI=0}var oldCenter=this.m_sweep.c.Copy();this.m_sweep.localCenter.SetV(center);this.m_sweep.c0.SetV(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)};b2Body.prototype.GetWorldPoint=function(localPoint){var A=this.m_xf.R;var u=new b2Vec2(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};b2Body.prototype.GetWorldVector=function(localVector){return b2Math.MulMV(this.m_xf.R,localVector)};b2Body.prototype.GetLocalPoint=function(worldPoint){return b2Math.MulXT(this.m_xf,worldPoint)};b2Body.prototype.GetLocalVector=function(worldVector){return b2Math.MulTMV(this.m_xf.R,worldVector)};b2Body.prototype.GetLinearVelocityFromWorldPoint=function(worldPoint){return new b2Vec2(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))};b2Body.prototype.GetLinearVelocityFromLocalPoint=function(localPoint){var A=this.m_xf.R;var worldPoint=new b2Vec2(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;return new b2Vec2(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))};b2Body.prototype.GetLinearDamping=function(){return this.m_linearDamping};b2Body.prototype.SetLinearDamping=function(linearDamping){if(linearDamping===undefined)linearDamping=0;this.m_linearDamping=linearDamping};b2Body.prototype.GetAngularDamping=function(){return this.m_angularDamping};b2Body.prototype.SetAngularDamping=function(angularDamping){if(angularDamping===undefined)angularDamping=0;this.m_angularDamping=angularDamping};b2Body.prototype.SetType=function(type){if(type===undefined)type=0;if(this.m_type==type){return}this.m_type=type;this.ResetMassData();if(this.m_type==b2Body.b2_staticBody){this.m_linearVelocity.SetZero();this.m_angularVelocity=0}this.SetAwake(true);this.m_force.SetZero();this.m_torque=0;for(var ce=this.m_contactList;ce;ce=ce.next){ce.contact.FlagForFiltering()}};b2Body.prototype.GetType=function(){return this.m_type};b2Body.prototype.SetBullet=function(flag){if(flag){this.m_flags|=b2Body.e_bulletFlag}else{this.m_flags&=~b2Body.e_bulletFlag}};b2Body.prototype.IsBullet=function(){return(this.m_flags&b2Body.e_bulletFlag)==b2Body.e_bulletFlag};b2Body.prototype.SetSleepingAllowed=function(flag){if(flag){this.m_flags|=b2Body.e_allowSleepFlag}else{this.m_flags&=~b2Body.e_allowSleepFlag;this.SetAwake(true)}};b2Body.prototype.SetAwake=function(flag){if(flag){this.m_flags|=b2Body.e_awakeFlag;this.m_sleepTime=0}else{this.m_flags&=~b2Body.e_awakeFlag;this.m_sleepTime=0;this.m_linearVelocity.SetZero();this.m_angularVelocity=0;this.m_force.SetZero();this.m_torque=0}};b2Body.prototype.IsAwake=function(){return(this.m_flags&b2Body.e_awakeFlag)==b2Body.e_awakeFlag};b2Body.prototype.SetFixedRotation=function(fixed){if(fixed){this.m_flags|=b2Body.e_fixedRotationFlag}else{this.m_flags&=~b2Body.e_fixedRotationFlag}this.ResetMassData()};b2Body.prototype.IsFixedRotation=function(){return(this.m_flags&b2Body.e_fixedRotationFlag)==b2Body.e_fixedRotationFlag};b2Body.prototype.SetActive=function(flag){if(flag==this.IsActive()){return}var broadPhase;var f;if(flag){this.m_flags|=b2Body.e_activeFlag;broadPhase=this.m_world.m_contactManager.m_broadPhase;for(f=this.m_fixtureList;f;f=f.m_next){f.CreateProxy(broadPhase,this.m_xf)}}else{this.m_flags&=~b2Body.e_activeFlag;broadPhase=this.m_world.m_contactManager.m_broadPhase;for(f=this.m_fixtureList;f;f=f.m_next){f.DestroyProxy(broadPhase)}var ce=this.m_contactList;var x=0;while(ce){x++;if(x>10000){console.log("4948")}var ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact)}this.m_contactList=null}};b2Body.prototype.IsActive=function(){return(this.m_flags&b2Body.e_activeFlag)==b2Body.e_activeFlag};b2Body.prototype.IsSleepingAllowed=function(){return(this.m_flags&b2Body.e_allowSleepFlag)==b2Body.e_allowSleepFlag};b2Body.prototype.GetFixtureList=function(){return this.m_fixtureList};b2Body.prototype.GetJointList=function(){return this.m_jointList};b2Body.prototype.GetControllerList=function(){return this.m_controllerList};b2Body.prototype.GetContactList=function(){return this.m_contactList};b2Body.prototype.GetNext=function(){return this.m_next};b2Body.prototype.GetUserData=function(){return this.m_userData};b2Body.prototype.SetUserData=function(data){this.m_userData=data};b2Body.prototype.GetWorld=function(){return this.m_world};b2Body.prototype.b2Body=function(bd,world){this.m_flags=0;if(bd.bullet){this.m_flags|=b2Body.e_bulletFlag}if(bd.fixedRotation){this.m_flags|=b2Body.e_fixedRotationFlag}if(bd.allowSleep){this.m_flags|=b2Body.e_allowSleepFlag}if(bd.awake){this.m_flags|=b2Body.e_awakeFlag}if(bd.active){this.m_flags|=b2Body.e_activeFlag}this.m_world=world;this.m_xf.position.SetV(bd.position);this.m_xf.R.Set(bd.angle);this.m_sweep.localCenter.SetZero();this.m_sweep.t0=1;this.m_sweep.a0=this.m_sweep.a=bd.angle;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_jointList=null;this.m_controllerList=null;this.m_contactList=null;this.m_controllerCount=0;this.m_prev=null;this.m_next=null;this.m_linearVelocity.SetV(bd.linearVelocity);this.m_angularVelocity=bd.angularVelocity;this.m_linearDamping=bd.linearDamping;this.m_angularDamping=bd.angularDamping;this.m_force.Set(0,0);this.m_torque=0;this.m_sleepTime=0;this.m_type=bd.type;if(this.m_type==b2Body.b2_dynamicBody){this.m_mass=1;this.m_invMass=1}else{this.m_mass=0;this.m_invMass=0}this.m_I=0;this.m_invI=0;this.m_inertiaScale=bd.inertiaScale;this.m_userData=bd.userData;this.m_fixtureList=null;this.m_fixtureCount=0};b2Body.prototype.SynchronizeFixtures=function(){var xf1=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 f;var broadPhase=this.m_world.m_contactManager.m_broadPhase;for(f=this.m_fixtureList;f;f=f.m_next){f.Synchronize(broadPhase,xf1,this.m_xf)}};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)};b2Body.prototype.ShouldCollide=function(other){if(this.m_type!=b2Body.b2_dynamicBody&&other.m_type!=b2Body.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};b2Body.prototype.Advance=function(t){if(t===undefined)t=0;this.m_sweep.Advance(t);this.m_sweep.c.SetV(this.m_sweep.c0);this.m_sweep.a=this.m_sweep.a0;this.SynchronizeTransform()};$i_108.postDefs.push(function(){$i_108.Dynamics.b2Body.s_xf1=new b2Transform;$i_108.Dynamics.b2Body.e_islandFlag=1;$i_108.Dynamics.b2Body.e_awakeFlag=2;$i_108.Dynamics.b2Body.e_allowSleepFlag=4;$i_108.Dynamics.b2Body.e_bulletFlag=8;$i_108.Dynamics.b2Body.e_fixedRotationFlag=16;$i_108.Dynamics.b2Body.e_activeFlag=32;$i_108.Dynamics.b2Body.b2_staticBody=0;$i_108.Dynamics.b2Body.b2_kinematicBody=1;$i_108.Dynamics.b2Body.b2_dynamicBody=2});b2BodyDef.b2BodyDef=function(){this.position=new b2Vec2;this.linearVelocity=new b2Vec2};b2BodyDef.prototype.b2BodyDef=function(){this.userData=null;this.position.Set(0,0);this.angle=0;this.linearVelocity.Set(0,0);this.angularVelocity=0;this.linearDamping=0;this.angularDamping=0;this.allowSleep=true;this.awake=true;this.fixedRotation=false;this.bullet=false;this.type=b2Body.b2_staticBody;this.active=true;this.inertiaScale=1};b2ContactFilter.b2ContactFilter=function(){};b2ContactFilter.prototype.ShouldCollide=function(fixtureA,fixtureB){var filter1=fixtureA.GetFilterData();var filter2=fixtureB.GetFilterData();if(filter1.groupIndex==filter2.groupIndex&&filter1.groupIndex!=0){return filter1.groupIndex>0}var collide=(filter1.maskBits&filter2.categoryBits)!=0&&(filter1.categoryBits&filter2.maskBits)!=0;return collide};b2ContactFilter.prototype.RayCollide=function(userData,fixture){if(!userData)return true;return this.ShouldCollide(userData instanceof b2Fixture?userData:null,fixture)};$i_108.postDefs.push(function(){$i_108.Dynamics.b2ContactFilter.b2_defaultFilter=new b2ContactFilter});b2ContactImpulse.b2ContactImpulse=function(){this.normalImpulses=new Vector_a2j_Number(b2Settings.b2_maxManifoldPoints);this.tangentImpulses=new Vector_a2j_Number(b2Settings.b2_maxManifoldPoints)};b2ContactListener.b2ContactListener=function(){};b2ContactListener.prototype.BeginContact=function(contact){};b2ContactListener.prototype.EndContact=function(contact){};b2ContactListener.prototype.PreSolve=function(contact,oldManifold){};b2ContactListener.prototype.PostSolve=function(contact,impulse){};$i_108.postDefs.push(function(){$i_108.Dynamics.b2ContactListener.b2_defaultListener=new b2ContactListener});b2ContactManager.b2ContactManager=function(){};b2ContactManager.prototype.b2ContactManager=function(){this.m_world=null;this.m_contactCount=0;this.m_contactFilter=b2ContactFilter.b2_defaultFilter;this.m_contactListener=b2ContactListener.b2_defaultListener;this.m_contactFactory=new b2ContactFactory(this.m_allocator);this.m_broadPhase=new b2DynamicTreeBroadPhase};b2ContactManager.prototype.AddPair=function(proxyUserDataA,proxyUserDataB){var fixtureA=proxyUserDataA instanceof b2Fixture?proxyUserDataA:null;var fixtureB=proxyUserDataB instanceof b2Fixture?proxyUserDataB:null;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(bodyA==bodyB)return;var edge=bodyB.GetContactList();var x=0;while(edge){x++;if(x>10000){console.log("5164")}if(edge.other==bodyA){var fA=edge.contact.GetFixtureA();var fB=edge.contact.GetFixtureB();if(fA==fixtureA&&fB==fixtureB)return;if(fA==fixtureB&&fB==fixtureA)return}edge=edge.next}if(bodyB.ShouldCollide(bodyA)==false){return}if(this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)==false){return}var c=this.m_contactFactory.Create(fixtureA,fixtureB);fixtureA=c.GetFixtureA();fixtureB=c.GetFixtureB();bodyA=fixtureA.m_body;bodyB=fixtureB.m_body;c.m_prev=null;c.m_next=this.m_world.m_contactList;if(this.m_world.m_contactList!=null){this.m_world.m_contactList.m_prev=c}this.m_world.m_contactList=c;c.m_nodeA.contact=c;c.m_nodeA.other=bodyB;c.m_nodeA.prev=null;c.m_nodeA.next=bodyA.m_contactList;if(bodyA.m_contactList!=null){bodyA.m_contactList.prev=c.m_nodeA}bodyA.m_contactList=c.m_nodeA;c.m_nodeB.contact=c;c.m_nodeB.other=bodyA;c.m_nodeB.prev=null;c.m_nodeB.next=bodyB.m_contactList;if(bodyB.m_contactList!=null){bodyB.m_contactList.prev=c.m_nodeB}bodyB.m_contactList=c.m_nodeB;++this.m_world.m_contactCount};b2ContactManager.prototype.FindNewContacts=function(){this.m_broadPhase.UpdatePairs($i_108.generateCallback(this,this.AddPair))};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_prev){c.m_prev.m_next=c.m_next}if(c.m_next){c.m_next.m_prev=c.m_prev}if(c==this.m_world.m_contactList){this.m_world.m_contactList=c.m_next}if(c.m_nodeA.prev){c.m_nodeA.prev.next=c.m_nodeA.next}if(c.m_nodeA.next){c.m_nodeA.next.prev=c.m_nodeA.prev}if(c.m_nodeA==bodyA.m_contactList){bodyA.m_contactList=c.m_nodeA.next}if(c.m_nodeB.prev){c.m_nodeB.prev.next=c.m_nodeB.next}if(c.m_nodeB.next){c.m_nodeB.next.prev=c.m_nodeB.prev}if(c.m_nodeB==bodyB.m_contactList){bodyB.m_contactList=c.m_nodeB.next}this.m_contactFactory.Destroy(c);--this.m_contactCount};b2ContactManager.prototype.Collide=function(){var c=this.m_world.m_contactList;var x=0;while(c){x++;if(x>10000){console.log("5271");this.m_world.m_contactList=undefined}var fixtureA=c.GetFixtureA();var fixtureB=c.GetFixtureB();var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(bodyA.IsAwake()==false&&bodyB.IsAwake()==false){c=c.GetNext();continue}if(c.m_flags&b2Contact.e_filterFlag){if(bodyB.ShouldCollide(bodyA)==false){var cNuke=c;c=cNuke.GetNext();this.Destroy(cNuke);continue}if(this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)==false){cNuke=c;c=cNuke.GetNext();this.Destroy(cNuke);continue}c.m_flags&=~b2Contact.e_filterFlag}var proxyA=fixtureA.m_proxy;var proxyB=fixtureB.m_proxy;if(proxyA&&proxyB){var overlap=this.m_broadPhase.TestOverlap(proxyA,proxyB);if(overlap==false){cNuke=c;c=cNuke.GetNext();this.Destroy(cNuke);continue}}c.Update(this.m_contactListener);c=c.GetNext()}};$i_108.postDefs.push(function(){$i_108.Dynamics.b2ContactManager.s_evalCP=new b2ContactPoint});b2DebugDraw.b2DebugDraw=function(){};b2DebugDraw.prototype.b2DebugDraw=function(){};b2DebugDraw.prototype.SetFlags=function(flags){if(flags===undefined)flags=0};b2DebugDraw.prototype.GetFlags=function(){};b2DebugDraw.prototype.AppendFlags=function(flags){if(flags===undefined)flags=0};b2DebugDraw.prototype.ClearFlags=function(flags){if(flags===undefined)flags=0};b2DebugDraw.prototype.SetSprite=function(sprite){};b2DebugDraw.prototype.GetSprite=function(){};b2DebugDraw.prototype.SetDrawScale=function(drawScale){if(drawScale===undefined)drawScale=0};b2DebugDraw.prototype.GetDrawScale=function(){};b2DebugDraw.prototype.SetLineThickness=function(lineThickness){if(lineThickness===undefined)lineThickness=0};b2DebugDraw.prototype.GetLineThickness=function(){};b2DebugDraw.prototype.SetAlpha=function(alpha){if(alpha===undefined)alpha=0};b2DebugDraw.prototype.GetAlpha=function(){};b2DebugDraw.prototype.SetFillAlpha=function(alpha){if(alpha===undefined)alpha=0};b2DebugDraw.prototype.GetFillAlpha=function(){};b2DebugDraw.prototype.SetXFormScale=function(xformScale){if(xformScale===undefined)xformScale=0};b2DebugDraw.prototype.GetXFormScale=function(){};b2DebugDraw.prototype.DrawPolygon=function(vertices,vertexCount,color){if(vertexCount===undefined)vertexCount=0};b2DebugDraw.prototype.DrawSolidPolygon=function(vertices,vertexCount,color){if(vertexCount===undefined)vertexCount=0};b2DebugDraw.prototype.DrawCircle=function(center,radius,color){if(radius===undefined)radius=0};b2DebugDraw.prototype.DrawSolidCircle=function(center,radius,axis,color){if(radius===undefined)radius=0};b2DebugDraw.prototype.DrawSegment=function(p1,p2,color){};b2DebugDraw.prototype.DrawTransform=function(xf){};$i_108.postDefs.push(function(){$i_108.Dynamics.b2DebugDraw.e_shapeBit=1;$i_108.Dynamics.b2DebugDraw.e_jointBit=2;$i_108.Dynamics.b2DebugDraw.e_aabbBit=4;$i_108.Dynamics.b2DebugDraw.e_pairBit=8;$i_108.Dynamics.b2DebugDraw.e_centerOfMassBit=16;$i_108.Dynamics.b2DebugDraw.e_controllerBit=32});b2DestructionListener.b2DestructionListener=function(){};b2DestructionListener.prototype.SayGoodbyeJoint=function(joint){};b2DestructionListener.prototype.SayGoodbyeFixture=function(fixture){};b2FilterData.b2FilterData=function(){this.categoryBits=1;this.maskBits=65535;this.groupIndex=0};b2FilterData.prototype.Copy=function(){var copy=new b2FilterData;copy.categoryBits=this.categoryBits;copy.maskBits=this.maskBits;copy.groupIndex=this.groupIndex;return copy};b2Fixture.b2Fixture=function(){this.m_filter=new b2FilterData};b2Fixture.prototype.GetType=function(){return this.m_shape.GetType()};b2Fixture.prototype.GetShape=function(){return this.m_shape};b2Fixture.prototype.SetSensor=function(sensor){if(this.m_isSensor==sensor)return;this.m_isSensor=sensor;if(this.m_body==null)return;var edge=this.m_body.GetContactList();var x=0;while(edge){x++;if(x>10000){console.log("5384")}var contact=edge.contact;var fixtureA=contact.GetFixtureA();var fixtureB=contact.GetFixtureB();if(fixtureA==this||fixtureB==this)contact.SetSensor(fixtureA.IsSensor()||fixtureB.IsSensor());edge=edge.next}};b2Fixture.prototype.IsSensor=function(){return this.m_isSensor};b2Fixture.prototype.SetFilterData=function(filter){this.m_filter=filter.Copy();if(this.m_body)return;var edge=this.m_body.GetContactList();var x=0;while(edge){x++;if(x>10000){console.log("5401")}var contact=edge.contact;var fixtureA=contact.GetFixtureA();var fixtureB=contact.GetFixtureB();if(fixtureA==this||fixtureB==this)contact.FlagForFiltering();edge=edge.next}};b2Fixture.prototype.GetFilterData=function(){return this.m_filter.Copy()};b2Fixture.prototype.GetBody=function(){return this.m_body};b2Fixture.prototype.GetNext=function(){return this.m_next};b2Fixture.prototype.GetUserData=function(){return this.m_userData};b2Fixture.prototype.SetUserData=function(data){this.m_userData=data};b2Fixture.prototype.TestPoint=function(p){return this.m_shape.TestPoint(this.m_body.GetTransform(),p)};b2Fixture.prototype.RayCast=function(output,input){return this.m_shape.RayCast(output,input,this.m_body.GetTransform())};b2Fixture.prototype.GetMassData=function(massData){if(massData===undefined)massData=null;if(massData==null){massData=new b2MassData}this.m_shape.ComputeMass(massData,this.m_density);return massData};b2Fixture.prototype.SetDensity=function(density){if(density===undefined)density=0;this.m_density=density};b2Fixture.prototype.GetDensity=function(){return this.m_density};b2Fixture.prototype.GetFriction=function(){return this.m_friction};b2Fixture.prototype.SetFriction=function(friction){if(friction===undefined)friction=0;this.m_friction=friction};b2Fixture.prototype.GetRestitution=function(){return this.m_restitution};b2Fixture.prototype.SetRestitution=function(restitution){if(restitution===undefined)restitution=0;this.m_restitution=restitution};b2Fixture.prototype.GetAABB=function(){return this.m_aabb};b2Fixture.prototype.b2Fixture=function(){this.m_aabb=new b2AABB;this.m_userData=null;this.m_body=null;this.m_next=null;this.m_shape=null;this.m_density=0;this.m_friction=0;this.m_restitution=0};b2Fixture.prototype.Create=function(body,xf,def){this.m_userData=def.userData;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_body=body;this.m_next=null;this.m_filter=def.filter.Copy();this.m_isSensor=def.isSensor;this.m_shape=def.shape.Copy();this.m_density=def.density};b2Fixture.prototype.Destroy=function(){this.m_shape=null};b2Fixture.prototype.CreateProxy=function(broadPhase,xf){this.m_shape.ComputeAABB(this.m_aabb,xf);this.m_proxy=broadPhase.CreateProxy(this.m_aabb,this)};b2Fixture.prototype.DestroyProxy=function(broadPhase){if(this.m_proxy==null){return}broadPhase.DestroyProxy(this.m_proxy);this.m_proxy=null};b2Fixture.prototype.Synchronize=function(broadPhase,transform1,transform2){if(!this.m_proxy)return;var aabb1=new b2AABB;var aabb2=new b2AABB;this.m_shape.ComputeAABB(aabb1,transform1);this.m_shape.ComputeAABB(aabb2,transform2);this.m_aabb.Combine(aabb1,aabb2);var displacement=b2Math.SubtractVV(transform2.position,transform1.position);broadPhase.MoveProxy(this.m_proxy,this.m_aabb,displacement)};b2FixtureDef.b2FixtureDef=function(){this.filter=new b2FilterData};b2FixtureDef.prototype.b2FixtureDef=function(){this.shape=null;this.userData=null;this.friction=0.2;this.restitution=0;this.density=0;this.filter.categoryBits=1;this.filter.maskBits=65535;this.filter.groupIndex=0;this.isSensor=false};b2Island.b2Island=function(){};b2Island.prototype.b2Island=function(){this.m_bodies=new Vector;this.m_contacts=new Vector;this.m_joints=new Vector};b2Island.prototype.Initialize=function(bodyCapacity,contactCapacity,jointCapacity,allocator,listener,contactSolver){if(bodyCapacity===undefined)bodyCapacity=0;if(contactCapacity===undefined)contactCapacity=0;if(jointCapacity===undefined)jointCapacity=0;var i=0;this.m_bodyCapacity=bodyCapacity;this.m_contactCapacity=contactCapacity;this.m_jointCapacity=jointCapacity;this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;this.m_allocator=allocator;this.m_listener=listener;this.m_contactSolver=contactSolver;for(i=this.m_bodies.length;ib2Settings.b2_maxTranslationSquared){b.m_linearVelocity.Normalize();b.m_linearVelocity.x*=b2Settings.b2_maxTranslation*step.inv_dt;b.m_linearVelocity.y*=b2Settings.b2_maxTranslation*step.inv_dt}var rotation=step.dt*b.m_angularVelocity;if(rotation*rotation>b2Settings.b2_maxRotationSquared){if(b.m_angularVelocity<0){b.m_angularVelocity=-b2Settings.b2_maxRotation*step.inv_dt}else{b.m_angularVelocity=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()}for(i=0;iangTolSqr||b2Math.Dot(b.m_linearVelocity,b.m_linearVelocity)>linTolSqr){b.m_sleepTime=0;minSleepTime=0}else{b.m_sleepTime+=step.dt;minSleepTime=b2Math.Min(minSleepTime,b.m_sleepTime)}}if(minSleepTime>=b2Settings.b2_timeToSleep){for(i=0;ib2Settings.b2_maxTranslationSquared){b.m_linearVelocity.Normalize();b.m_linearVelocity.x*=b2Settings.b2_maxTranslation*subStep.inv_dt;b.m_linearVelocity.y*=b2Settings.b2_maxTranslation*subStep.inv_dt}var rotation=subStep.dt*b.m_angularVelocity;if(rotation*rotation>b2Settings.b2_maxRotationSquared){if(b.m_angularVelocity<0){b.m_angularVelocity=-b2Settings.b2_maxRotation*subStep.inv_dt}else{b.m_angularVelocity=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()}var k_toiBaumgarte=0.75;for(i=0;i10000){console.log("5848")}var jn0=jn;jn=jn.next;if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeJoint(jn0.joint)}this.DestroyJoint(jn0.joint)}b.m_jointList=null;var coe=b.m_controllerList;var x=0;while(coe){x++;if(x>10000){console.log("5860")}var coe0=coe;coe=coe.nextController;coe0.controller.RemoveBody(b)}b.m_controllerList=null;var ce=b.m_contactList;var x=0;while(ce){x++;if(x>10000){console.log("5868");process.exit(0)}var ce0=ce;ce=ce.next;this.m_contactManager.Destroy(ce0.contact)}b.m_contactList=null;var f=b.m_fixtureList;var x=0;while(f){x++;if(x>10000){console.log("5877")}var f0=f;f=f.m_next;if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeFixture(f0)}f0.DestroyProxy(this.m_contactManager.m_broadPhase);f0.Destroy()}b.m_fixtureList=null;b.m_fixtureCount=0;if(b.m_prev){b.m_prev.m_next=b.m_next}if(b.m_next){b.m_next.m_prev=b.m_prev}if(b==this.m_bodyList){this.m_bodyList=b.m_next}--this.m_bodyCount;b.Destroy();b=undefined;return true};b2World.prototype.CreateJoint=function(def){var j=b2Joint.Create(def,null);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==false){var edge=bodyB.GetContactList();var x=0;while(edge){x++;if(x>10000){console.log("5929")}if(edge.other==bodyA){edge.contact.FlagForFiltering()}edge=edge.next}}return j};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}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;b2Joint.Destroy(j,null);--this.m_jointCount;if(collideConnected==false){var edge=bodyB.GetContactList();var x=0;while(edge){x++;if(x>10000){console.log("5981");process.exit(0)}if(edge.other==bodyA){edge.contact.FlagForFiltering()}edge=edge.next}edge=null}};b2World.prototype.AddController=function(c){c.m_next=this.m_controllerList;c.m_prev=null;this.m_controllerList=c;c.m_world=this;this.m_controllerCount++;return c};b2World.prototype.RemoveController=function(c){if(c.m_prev)c.m_prev.m_next=c.m_next;if(c.m_next)c.m_next.m_prev=c.m_prev;if(this.m_controllerList==c)this.m_controllerList=c.m_next;this.m_controllerCount--};b2World.prototype.CreateController=function(controller){if(controller.m_world!=this)throw new Error("Controller can only be a member of one world");controller.m_next=this.m_controllerList;controller.m_prev=null;if(this.m_controllerList)this.m_controllerList.m_prev=controller;this.m_controllerList=controller;++this.m_controllerCount;controller.m_world=this;return controller};b2World.prototype.DestroyController=function(controller){controller.Clear();if(controller.m_next)controller.m_next.m_prev=controller.m_prev;if(controller.m_prev)controller.m_prev.m_next=controller.m_next;if(controller==this.m_controllerList)this.m_controllerList=controller.m_next;--this.m_controllerCount};b2World.prototype.SetWarmStarting=function(flag){b2World.m_warmStarting=flag};b2World.prototype.SetContinuousPhysics=function(flag){b2World.m_continuousPhysics=flag};b2World.prototype.GetBodyCount=function(){return this.m_bodyCount};b2World.prototype.GetJointCount=function(){return this.m_jointCount};b2World.prototype.GetContactCount=function(){return this.m_contactCount};b2World.prototype.SetGravity=function(gravity){this.m_gravity=gravity};b2World.prototype.GetGravity=function(){return this.m_gravity};b2World.prototype.GetGroundBody=function(){return this.m_groundBody};b2World.prototype.Step=function(dt,velocityIterations,positionIterations){if(dt===undefined)dt=0;if(velocityIterations===undefined)velocityIterations=0;if(positionIterations===undefined)positionIterations=0;if(this.m_flags&b2World.e_newFixture){this.m_contactManager.FindNewContacts();this.m_flags&=~b2World.e_newFixture}this.m_flags|=b2World.e_locked;var step=b2World.s_timestep2;step.dt=dt;step.velocityIterations=velocityIterations;step.positionIterations=positionIterations;if(dt>0){step.inv_dt=1/dt}else{step.inv_dt=0}step.dtRatio=this.m_inv_dt0*dt;step.warmStarting=b2World.m_warmStarting;this.m_contactManager.Collide();if(step.dt>0){this.Solve(step)}if(b2World.m_continuousPhysics&&step.dt>0){this.SolveTOI(step)}if(step.dt>0){this.m_inv_dt0=step.inv_dt}this.m_flags&=~b2World.e_locked};b2World.prototype.ClearForces=function(){for(var body=this.m_bodyList;body;body=body.m_next){body.m_force.SetZero();body.m_torque=0}};b2World.prototype.DrawDebugData=function(){if(this.m_debugDraw==null){return}this.m_debugDraw.m_sprite.graphics.clear();var flags=this.m_debugDraw.GetFlags();var i=0;var b;var f;var s;var j;var bp;var invQ=new b2Vec2;var x1=new b2Vec2;var x2=new b2Vec2;var xf;var b1=new b2AABB;var b2=new b2AABB;var vs=[new b2Vec2,new b2Vec2,new b2Vec2,new b2Vec2];var color=new b2Color(0,0,0);if(flags&b2DebugDraw.e_shapeBit){for(b=this.m_bodyList;b;b=b.m_next){if(!b._entity||!b._entity._$i_108NoDebug){xf=b.m_xf;for(f=b.GetFixtureList();f;f=f.m_next){s=f.GetShape();if(b.IsActive()==false){color.Set(0.5,0.5,0.3);this.DrawShape(s,xf,color)}else if(b.GetType()==b2Body.b2_staticBody){color.Set(0.5,0.9,0.5);this.DrawShape(s,xf,color)}else if(b.GetType()==b2Body.b2_kinematicBody){color.Set(0.5,0.5,0.9);this.DrawShape(s,xf,color)}else if(b.IsAwake()==false){color.Set(0.6,0.6,0.6);this.DrawShape(s,xf,color)}else{color.Set(0.9,0.7,0.7);this.DrawShape(s,xf,color)}}}}}if(flags&b2DebugDraw.e_jointBit){for(j=this.m_jointList;j;j=j.m_next){this.DrawJoint(j)}}if(flags&b2DebugDraw.e_controllerBit){for(var c=this.m_controllerList;c;c=c.m_next){c.Draw(this.m_debugDraw)}}if(flags&b2DebugDraw.e_pairBit){color.Set(0.3,0.9,0.9);for(var contact=this.m_contactManager.m_contactList;contact;contact=contact.GetNext()){var fixtureA=contact.GetFixtureA();var fixtureB=contact.GetFixtureB();var cA=fixtureA.GetAABB().GetCenter();var cB=fixtureB.GetAABB().GetCenter();this.m_debugDraw.DrawSegment(cA,cB,color)}}if(flags&b2DebugDraw.e_aabbBit){bp=this.m_contactManager.m_broadPhase;vs=[new b2Vec2,new b2Vec2,new b2Vec2,new b2Vec2];for(b=this.m_bodyList;b;b=b.GetNext()){if(b.IsActive()==false){continue}for(f=b.GetFixtureList();f;f=f.GetNext()){var aabb=bp.GetFatAABB(f.m_proxy);vs[0].Set(aabb.lowerBound.x,aabb.lowerBound.y);vs[1].Set(aabb.upperBound.x,aabb.lowerBound.y);vs[2].Set(aabb.upperBound.x,aabb.upperBound.y);vs[3].Set(aabb.lowerBound.x,aabb.upperBound.y);this.m_debugDraw.DrawPolygon(vs,4,color)}}}if(flags&b2DebugDraw.e_centerOfMassBit){for(b=this.m_bodyList;b;b=b.m_next){xf=b2World.s_xf;xf.R=b.m_xf.R;xf.position=b.GetWorldCenter();this.m_debugDraw.DrawTransform(xf)}}};b2World.prototype.QueryAABB=function(callback,aabb){var __this=this;var broadPhase=__this.m_contactManager.m_broadPhase;function WorldQueryWrapper(proxy){return callback(broadPhase.GetUserData(proxy))}broadPhase.Query(WorldQueryWrapper,aabb)};b2World.prototype.QueryShape=function(callback,shape,transform){var __this=this;if(transform===undefined)transform=null;if(transform==null){transform=new b2Transform;transform.SetIdentity()}var broadPhase=__this.m_contactManager.m_broadPhase;function WorldQueryWrapper(proxy){var fixture=broadPhase.GetUserData(proxy)instanceof b2Fixture?broadPhase.GetUserData(proxy):null;if(b2Shape.TestOverlap(shape,transform,fixture.GetShape(),fixture.GetBody().GetTransform()))return callback(fixture);return true}var aabb=new b2AABB;shape.ComputeAABB(aabb,transform);broadPhase.Query(WorldQueryWrapper,aabb)};b2World.prototype.QueryPoint=function(callback,p){var __this=this;var broadPhase=__this.m_contactManager.m_broadPhase;function WorldQueryWrapper(proxy){var fixture=broadPhase.GetUserData(proxy)instanceof b2Fixture?broadPhase.GetUserData(proxy):null;if(fixture.TestPoint(p))return callback(fixture);return true}var aabb=new b2AABB;aabb.lowerBound.Set(p.x-b2Settings.b2_linearSlop,p.y-b2Settings.b2_linearSlop);aabb.upperBound.Set(p.x+b2Settings.b2_linearSlop,p.y+b2Settings.b2_linearSlop);broadPhase.Query(WorldQueryWrapper,aabb)};b2World.prototype.RayCast=function(callback,point1,point2){var __this=this;var broadPhase=__this.m_contactManager.m_broadPhase;var output=new b2RayCastOutput;function RayCastWrapper(input,proxy){var userData=broadPhase.GetUserData(proxy);var fixture=userData instanceof b2Fixture?userData:null;var hit=fixture.RayCast(output,input);if(hit){var fraction=output.fraction;var point=new b2Vec2((1-fraction)*point1.x+fraction*point2.x,(1-fraction)*point1.y+fraction*point2.y);return callback(fixture,point,output.normal,fraction)}return input.maxFraction}var input=new b2RayCastInput(point1,point2);broadPhase.RayCast(RayCastWrapper,input)};b2World.prototype.RayCastOne=function(point1,point2){var __this=this;var result;function RayCastOneWrapper(fixture,point,normal,fraction){if(fraction===undefined)fraction=0;result=fixture;return fraction}__this.RayCast(RayCastOneWrapper,point1,point2);return result};b2World.prototype.RayCastAll=function(point1,point2){var __this=this;var result=new Vector;function RayCastAllWrapper(fixture,point,normal,fraction){if(fraction===undefined)fraction=0;result[result.length]=fixture;return 1}__this.RayCast(RayCastAllWrapper,point1,point2);return result};b2World.prototype.GetBodyList=function(){return this.m_bodyList};b2World.prototype.GetJointList=function(){return this.m_jointList};b2World.prototype.GetContactList=function(){return this.m_contactList};b2World.prototype.IsLocked=function(){return(this.m_flags&b2World.e_locked)>0};b2World.prototype.Solve=function(step){var b;for(var controller=this.m_controllerList;controller;controller=controller.m_next){controller.Step(step)}var island=this.m_island;island.Initialize(this.m_bodyCount,this.m_contactCount,this.m_jointCount,null,this.m_contactManager.m_contactListener,this.m_contactSolver);for(b=this.m_bodyList;b;b=b.m_next){b.m_flags&=~b2Body.e_islandFlag}for(var c=this.m_contactList;c;c=c.m_next){c.m_flags&=~b2Contact.e_islandFlag}for(var j=this.m_jointList;j;j=j.m_next){j.m_islandFlag=false}var stackSize=parseInt(this.m_bodyCount);var stack=this.s_stack;for(var seed=this.m_bodyList;seed;seed=seed.m_next){if(seed.m_flags&b2Body.e_islandFlag){continue}if(seed.IsAwake()==false||seed.IsActive()==false){continue}if(seed.GetType()==b2Body.b2_staticBody){continue}island.Clear();var stackCount=0;stack[stackCount++]=seed;seed.m_flags|=b2Body.e_islandFlag;var x=0;while(stackCount>0){x++;if(x>10000){console.log("6325");process.exit(0)}b=stack[--stackCount];island.AddBody(b);if(b.IsAwake()==false){b.SetAwake(true)}if(b.GetType()==b2Body.b2_staticBody){continue}var other;for(var ce=b.m_contactList;ce;ce=ce.next){if(ce.contact){if(ce.contact.m_flags&b2Contact.e_islandFlag){continue}if(ce.contact.IsSensor()==true||ce.contact.IsEnabled()==false||ce.contact.IsTouching()==false){continue}island.AddContact(ce.contact);ce.contact.m_flags|=b2Contact.e_islandFlag;other=ce.other;if(other.m_flags&b2Body.e_islandFlag){continue}stack[stackCount++]=other;other.m_flags|=b2Body.e_islandFlag}}for(var jn=b.m_jointList;jn;jn=jn.next){if(jn.joint.m_islandFlag==true){continue}other=jn.other;if(other.IsActive()==false){continue}island.AddJoint(jn.joint);jn.joint.m_islandFlag=true;if(other.m_flags&b2Body.e_islandFlag){continue}stack[stackCount++]=other;other.m_flags|=b2Body.e_islandFlag}}island.Solve(step,this.m_gravity,this.m_allowSleep);for(var i=0;i=0&&toi<=1);if(toi>0&&toi<1){toi=(1-toi)*t0+toi;if(toi>1)toi=1}c.m_toi=toi;c.m_flags|=b2Contact.e_toiFlag}if(Number.MIN_VALUE0){x++;if(x>10000){console.log("6492")}b=queue[queueStart++];--queueSize;island.AddBody(b);if(b.IsAwake()==false){b.SetAwake(true)}if(b.GetType()!=b2Body.b2_dynamicBody){continue}for(cEdge=b.m_contactList;cEdge;cEdge=cEdge.next){if(island.m_contactCount==island.m_contactCapacity){break}if(cEdge.contact.m_flags&b2Contact.e_islandFlag){continue}if(cEdge.contact.IsSensor()==true||cEdge.contact.IsEnabled()==false||cEdge.contact.IsTouching()==false){continue}island.AddContact(cEdge.contact);cEdge.contact.m_flags|=b2Contact.e_islandFlag;var other=cEdge.other;if(other.m_flags&b2Body.e_islandFlag){continue}if(other.GetType()!=b2Body.b2_staticBody){other.Advance(minTOI);other.SetAwake(true)}queue[queueStart+queueSize]=other;++queueSize;other.m_flags|=b2Body.e_islandFlag}for(var jEdge=b.m_jointList;jEdge;jEdge=jEdge.next){if(island.m_jointCount==island.m_jointCapacity)continue;if(jEdge.joint.m_islandFlag==true)continue;other=jEdge.other;if(other.IsActive()==false){continue}island.AddJoint(jEdge.joint);jEdge.joint.m_islandFlag=true;if(other.m_flags&b2Body.e_islandFlag)continue;if(other.GetType()!=b2Body.b2_staticBody){other.Advance(minTOI);other.SetAwake(true)}queue[queueStart+queueSize]=other;++queueSize;other.m_flags|=b2Body.e_islandFlag}}var subStep=b2World.s_timestep;subStep.warmStarting=false;subStep.dt=(1-minTOI)*step.dt;subStep.inv_dt=1/subStep.dt;subStep.dtRatio=0;subStep.velocityIterations=step.velocityIterations;subStep.positionIterations=step.positionIterations;island.SolveTOI(subStep);var i=0;for(i=0;i0;for(var i=0;i0){contact.m_fixtureA.m_body.SetAwake(true);contact.m_fixtureB.m_body.SetAwake(true)}var type1=parseInt(contact.m_fixtureA.GetType());var type2=parseInt(contact.m_fixtureB.GetType());var reg=null;if(contact.m_swaped){reg=this.m_registers[type2][type1]}else{reg=this.m_registers[type1][type2]}contact.Reset();if(true){reg.poolCount++;contact.m_next=reg.pool;reg.pool=contact}var destroyFcn=reg.destroyFcn;destroyFcn(contact,this.m_allocator)};b2ContactRegister.b2ContactRegister=function(){};b2ContactResult.b2ContactResult=function(){this.position=new b2Vec2;this.normal=new b2Vec2;this.id=new b2ContactID};b2ContactSolver.b2ContactSolver=function(){this.m_step=new b2TimeStep;this.m_constraints=new Vector};b2ContactSolver.prototype.b2ContactSolver=function(){};b2ContactSolver.prototype.Initialize=function(step,contacts,contactCount,allocator){if(contactCount===undefined)contactCount=0;var contact;this.m_step.Set(step);this.m_allocator=allocator;var i=0;var tVec;var tMat;this.m_constraintCount=contactCount;var x=0;while(this.m_constraints.length10000){console.log("7113");this.m_constraints=[];this.m_constraintCount=0;return}else{this.m_constraints[this.m_constraints.length]=new b2ContactConstraint}}for(i=0;i0);b2ContactSolver.s_worldManifold.Initialize(manifold,bodyA.m_xf,radiusA,bodyB.m_xf,radiusB);var normalX=b2ContactSolver.s_worldManifold.m_normal.x;var normalY=b2ContactSolver.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;k0?newImpulse:0;lambda=newImpulse-ccp.normalImpulse;PX=lambda*normalX;PY=lambda*normalY;vA.x-=invMassA*PX;vA.y-=invMassA*PY;wA-=invIA*(ccp.rA.x*PY-ccp.rA.y*PX);vB.x+=invMassB*PX;vB.y+=invMassB*PY;wB+=invIB*(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=vB.x-wB*cp1.rB.y-vA.x+wA*cp1.rA.y;var dv1Y=vB.y+wB*cp1.rB.x-vA.y-wA*cp1.rA.x;var dv2X=vB.x-wB*cp2.rB.y-vA.x+wA*cp2.rA.y;var dv2Y=vB.y+wB*cp2.rB.x-vA.y-wA*cp2.rA.x;var vn1=dv1X*normalX+dv1Y*normalY;var vn2=dv2X*normalX+dv2Y*normalY;var bX=vn1-cp1.velocityBias;var bY=vn2-cp2.velocityBias;tMat=c.K;bX-=tMat.col1.x*aX+tMat.col2.x*aY;bY-=tMat.col1.y*aX+tMat.col2.y*aY;var k_errorTol=0.001;for(;;){tMat=c.normalMass;var xX=-(tMat.col1.x*bX+tMat.col2.x*bY);var xY=-(tMat.col1.y*bX+tMat.col2.y*bY);if(xX>=0&&xY>=0){dX=xX-aX;dY=xY-aY;P1X=dX*normalX;P1Y=dX*normalY;P2X=dY*normalX;P2Y=dY*normalY;vA.x-=invMassA*(P1X+P2X);vA.y-=invMassA*(P1Y+P2Y);wA-=invIA*(cp1.rA.x*P1Y-cp1.rA.y*P1X+cp2.rA.x*P2Y-cp2.rA.y*P2X);vB.x+=invMassB*(P1X+P2X);vB.y+=invMassB*(P1Y+P2Y);wB+=invIB*(cp1.rB.x*P1Y-cp1.rB.y*P1X+cp2.rB.x*P2Y-cp2.rB.y*P2X);cp1.normalImpulse=xX;cp2.normalImpulse=xY;break}xX=-cp1.normalMass*bX;xY=0;vn1=0;vn2=c.K.col1.y*xX+bY;if(xX>=0&&vn2>=0){dX=xX-aX;dY=xY-aY;P1X=dX*normalX;P1Y=dX*normalY;P2X=dY*normalX;P2Y=dY*normalY;vA.x-=invMassA*(P1X+P2X);vA.y-=invMassA*(P1Y+P2Y);wA-=invIA*(cp1.rA.x*P1Y-cp1.rA.y*P1X+cp2.rA.x*P2Y-cp2.rA.y*P2X);vB.x+=invMassB*(P1X+P2X);vB.y+=invMassB*(P1Y+P2Y);wB+=invIB*(cp1.rB.x*P1Y-cp1.rB.y*P1X+cp2.rB.x*P2Y-cp2.rB.y*P2X);cp1.normalImpulse=xX;cp2.normalImpulse=xY;break}xX=0;xY=-cp2.normalMass*bY;vn1=c.K.col2.x*xY+bX;vn2=0;if(xY>=0&&vn1>=0){dX=xX-aX;dY=xY-aY;P1X=dX*normalX;P1Y=dX*normalY;P2X=dY*normalX;P2Y=dY*normalY;vA.x-=invMassA*(P1X+P2X);vA.y-=invMassA*(P1Y+P2Y);wA-=invIA*(cp1.rA.x*P1Y-cp1.rA.y*P1X+cp2.rA.x*P2Y-cp2.rA.y*P2X);vB.x+=invMassB*(P1X+P2X);vB.y+=invMassB*(P1Y+P2Y);wB+=invIB*(cp1.rB.x*P1Y-cp1.rB.y*P1X+cp2.rB.x*P2Y-cp2.rB.y*P2X);cp1.normalImpulse=xX;cp2.normalImpulse=xY;break}xX=0;xY=0;vn1=bX;vn2=bY;if(vn1>=0&&vn2>=0){dX=xX-aX;dY=xY-aY;P1X=dX*normalX;P1Y=dX*normalY;P2X=dY*normalX;P2Y=dY*normalY;vA.x-=invMassA*(P1X+P2X);vA.y-=invMassA*(P1Y+P2Y);wA-=invIA*(cp1.rA.x*P1Y-cp1.rA.y*P1X+cp2.rA.x*P2Y-cp2.rA.y*P2X);vB.x+=invMassB*(P1X+P2X);vB.y+=invMassB*(P1Y+P2Y);wB+=invIB*(cp1.rB.x*P1Y-cp1.rB.y*P1X+cp2.rB.x*P2Y-cp2.rB.y*P2X);cp1.normalImpulse=xX;cp2.normalImpulse=xY;break}break}}bodyA.m_angularVelocity=wA;bodyB.m_angularVelocity=wB}};b2ContactSolver.prototype.FinalizeVelocityConstraints=function(){for(var i=0;i-1.5*b2Settings.b2_linearSlop};$i_108.postDefs.push(function(){$i_108.Dynamics.Contacts.b2ContactSolver.s_worldManifold=new b2WorldManifold;$i_108.Dynamics.Contacts.b2ContactSolver.s_psm=new b2PositionSolverManifold});$i_108.inherit(b2EdgeAndCircleContact,$i_108.Dynamics.Contacts.b2Contact);b2EdgeAndCircleContact.prototype.__super=$i_108.Dynamics.Contacts.b2Contact.prototype;b2EdgeAndCircleContact.b2EdgeAndCircleContact=function(){$i_108.Dynamics.Contacts.b2Contact.b2Contact.apply(this,arguments)};b2EdgeAndCircleContact.Create=function(allocator){return new b2EdgeAndCircleContact};b2EdgeAndCircleContact.Destroy=function(contact,allocator){};b2EdgeAndCircleContact.prototype.Reset=function(fixtureA,fixtureB){this.__super.Reset.call(this,fixtureA,fixtureB)};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()instanceof b2EdgeShape?this.m_fixtureA.GetShape():null,bA.m_xf,this.m_fixtureB.GetShape()instanceof b2CircleShape?this.m_fixtureB.GetShape():null,bB.m_xf)};b2EdgeAndCircleContact.prototype.b2CollideEdgeAndCircle=function(manifold,edge,xf1,circle,xf2){};$i_108.inherit(b2NullContact,$i_108.Dynamics.Contacts.b2Contact);b2NullContact.prototype.__super=$i_108.Dynamics.Contacts.b2Contact.prototype;b2NullContact.b2NullContact=function(){$i_108.Dynamics.Contacts.b2Contact.b2Contact.apply(this,arguments)};b2NullContact.prototype.b2NullContact=function(){this.__super.b2Contact.call(this)};b2NullContact.prototype.Evaluate=function(){};$i_108.inherit(b2PolyAndCircleContact,$i_108.Dynamics.Contacts.b2Contact);b2PolyAndCircleContact.prototype.__super=$i_108.Dynamics.Contacts.b2Contact.prototype;b2PolyAndCircleContact.b2PolyAndCircleContact=function(){$i_108.Dynamics.Contacts.b2Contact.b2Contact.apply(this,arguments)};b2PolyAndCircleContact.Create=function(allocator){return new b2PolyAndCircleContact};b2PolyAndCircleContact.Destroy=function(contact,allocator){};b2PolyAndCircleContact.prototype.Reset=function(fixtureA,fixtureB){this.__super.Reset.call(this,fixtureA,fixtureB);if(fixtureA){b2Settings.b2Assert(fixtureA.GetType()==b2Shape.e_polygonShape)}if(fixtureB){b2Settings.b2Assert(fixtureB.GetType()==b2Shape.e_circleShape)}};b2PolyAndCircleContact.prototype.Evaluate=function(){var bA=this.m_fixtureA.m_body;var bB=this.m_fixtureB.m_body;b2Collision.CollidePolygonAndCircle(this.m_manifold,this.m_fixtureA.GetShape()instanceof b2PolygonShape?this.m_fixtureA.GetShape():null,bA.m_xf,this.m_fixtureB.GetShape()instanceof b2CircleShape?this.m_fixtureB.GetShape():null,bB.m_xf)};$i_108.inherit(b2PolyAndEdgeContact,$i_108.Dynamics.Contacts.b2Contact);b2PolyAndEdgeContact.prototype.__super=$i_108.Dynamics.Contacts.b2Contact.prototype;b2PolyAndEdgeContact.b2PolyAndEdgeContact=function(){$i_108.Dynamics.Contacts.b2Contact.b2Contact.apply(this,arguments)};b2PolyAndEdgeContact.Create=function(allocator){return new b2PolyAndEdgeContact};b2PolyAndEdgeContact.Destroy=function(contact,allocator){};b2PolyAndEdgeContact.prototype.Reset=function(fixtureA,fixtureB){this.__super.Reset.call(this,fixtureA,fixtureB);if(fixtureA){b2Settings.b2Assert(fixtureA.GetType()==b2Shape.e_polygonShape)}if(fixtureB){b2Settings.b2Assert(fixtureB.GetType()==b2Shape.e_edgeShape)}};b2PolyAndEdgeContact.prototype.Evaluate=function(){var bA=this.m_fixtureA.GetBody();var bB=this.m_fixtureB.GetBody();this.b2CollidePolyAndEdge(this.m_manifold,this.m_fixtureA.GetShape()instanceof b2PolygonShape?this.m_fixtureA.GetShape():null,bA.m_xf,this.m_fixtureB.GetShape()instanceof b2EdgeShape?this.m_fixtureB.GetShape():null,bB.m_xf)};b2PolyAndEdgeContact.prototype.b2CollidePolyAndEdge=function(manifold,polygon,xf1,edge,xf2){};$i_108.inherit(b2PolygonContact,$i_108.Dynamics.Contacts.b2Contact);b2PolygonContact.prototype.__super=$i_108.Dynamics.Contacts.b2Contact.prototype;b2PolygonContact.b2PolygonContact=function(){$i_108.Dynamics.Contacts.b2Contact.b2Contact.apply(this,arguments)};b2PolygonContact.Create=function(allocator){return new b2PolygonContact};b2PolygonContact.Destroy=function(contact,allocator){};b2PolygonContact.prototype.Reset=function(fixtureA,fixtureB){this.__super.Reset.call(this,fixtureA,fixtureB)};b2PolygonContact.prototype.Evaluate=function(){var bA=this.m_fixtureA.GetBody();var bB=this.m_fixtureB.GetBody();b2Collision.CollidePolygons(this.m_manifold,this.m_fixtureA.GetShape()instanceof b2PolygonShape?this.m_fixtureA.GetShape():null,bA.m_xf,this.m_fixtureB.GetShape()instanceof b2PolygonShape?this.m_fixtureB.GetShape():null,bB.m_xf)};b2PositionSolverManifold.b2PositionSolverManifold=function(){};b2PositionSolverManifold.prototype.b2PositionSolverManifold=function(){this.m_normal=new b2Vec2;this.m_separations=new Vector_a2j_Number(b2Settings.b2_maxManifoldPoints);this.m_points=new Vector(b2Settings.b2_maxManifoldPoints);for(var i=0;i0);var i=0;var clipPointX=0;var clipPointY=0;var tMat;var tVec;var planePointX=0;var planePointY=0;switch(cc.type){case b2Manifold.e_circles:{tMat=cc.bodyA.m_xf.R;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>Number.MIN_VALUE*Number.MIN_VALUE){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=0.5*(pointAX+pointBX);this.m_points[0].y=0.5*(pointAY+pointBY);this.m_separations[0]=dX*this.m_normal.x+dY*this.m_normal.y-cc.radius}break;case b2Manifold.e_faceA:{tMat=cc.bodyA.m_xf.R;tVec=cc.localPlaneNormal;this.m_normal.x=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;this.m_normal.y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=cc.bodyA.m_xf.R;tVec=cc.localPoint;planePointX=cc.bodyA.m_xf.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);planePointY=cc.bodyA.m_xf.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tMat=cc.bodyB.m_xf.R;for(i=0;i10000){console.log("7784")}edge=edge.nextController}if(edge.prevBody)edge.prevBody.nextBody=edge.nextBody;if(edge.nextBody)edge.nextBody.prevBody=edge.prevBody;if(edge.nextController)edge.nextController.prevController=edge.prevController;if(edge.prevController)edge.prevController.nextController=edge.nextController;if(this.m_bodyList==edge)this.m_bodyList=edge.nextBody;if(body.m_controllerList==edge)body.m_controllerList=edge.nextController;body.m_controllerCount--;this.m_bodyCount--};b2Controller.prototype.Clear=function(){var x=0;while(this.m_bodyList){x++;if(x>10000){console.log("7800")}this.RemoveBody(this.m_bodyList.body)}};b2Controller.prototype.GetNext=function(){return this.m_next};b2Controller.prototype.GetWorld=function(){return this.m_world};b2Controller.prototype.GetBodyList=function(){return this.m_bodyList};b2ControllerEdge.b2ControllerEdge=function(){};$i_108.inherit(b2GravityController,$i_108.Dynamics.Controllers.b2Controller);b2GravityController.prototype.__super=$i_108.Dynamics.Controllers.b2Controller.prototype;b2GravityController.b2GravityController=function(){$i_108.Dynamics.Controllers.b2Controller.b2Controller.apply(this,arguments);this.G=1;this.invSqr=true};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(i=this.m_bodyList;i;i=i.nextBody){body1=i.body;p1=body1.GetWorldCenter();mass1=body1.GetMass();for(j=this.m_bodyList;j!=i;j=j.nextBody){body2=j.body;p2=body2.GetWorldCenter();dx=p2.x-p1.x;dy=p2.y-p1.y;r2=dx*dx+dy*dy;if(r20||yDamping>0){this.maxTimestep=1/Math.max(xDamping,yDamping)}else{this.maxTimestep=0}};b2TensorDampingController.prototype.Step=function(step){var timestep=step.dt;if(timestep<=Number.MIN_VALUE)return;if(timestep>this.maxTimestep&&this.maxTimestep>0)timestep=this.maxTimestep;for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.IsAwake()){continue}var damping=body.GetWorldVector(b2Math.MulMV(this.T,body.GetLocalVector(body.GetLinearVelocity())));body.SetLinearVelocity(new b2Vec2(body.GetLinearVelocity().x+damping.x*timestep,body.GetLinearVelocity().y+damping.y*timestep))}}})();(function(){var b2Color=$i_108.Common.b2Color;var b2internal=$i_108.Common.b2internal;var b2Settings=$i_108.Common.b2Settings;var b2Mat22=$i_108.Common.Math.b2Mat22;var b2Mat33=$i_108.Common.Math.b2Mat33;var b2Math=$i_108.Common.Math.b2Math;var b2Sweep=$i_108.Common.Math.b2Sweep;var b2Transform=$i_108.Common.Math.b2Transform;var b2Vec2=$i_108.Common.Math.b2Vec2;var b2Vec3=$i_108.Common.Math.b2Vec3;var b2DistanceJoint=$i_108.Dynamics.Joints.b2DistanceJoint;var b2DistanceJointDef=$i_108.Dynamics.Joints.b2DistanceJointDef;var b2FrictionJoint=$i_108.Dynamics.Joints.b2FrictionJoint;var b2FrictionJointDef=$i_108.Dynamics.Joints.b2FrictionJointDef;var b2GearJoint=$i_108.Dynamics.Joints.b2GearJoint;var b2GearJointDef=$i_108.Dynamics.Joints.b2GearJointDef;var b2Jacobian=$i_108.Dynamics.Joints.b2Jacobian;var b2Joint=$i_108.Dynamics.Joints.b2Joint;var b2JointDef=$i_108.Dynamics.Joints.b2JointDef;var b2JointEdge=$i_108.Dynamics.Joints.b2JointEdge;var b2LineJoint=$i_108.Dynamics.Joints.b2LineJoint;var b2LineJointDef=$i_108.Dynamics.Joints.b2LineJointDef;var b2MouseJoint=$i_108.Dynamics.Joints.b2MouseJoint;var b2MouseJointDef=$i_108.Dynamics.Joints.b2MouseJointDef;var b2PrismaticJoint=$i_108.Dynamics.Joints.b2PrismaticJoint;var b2PrismaticJointDef=$i_108.Dynamics.Joints.b2PrismaticJointDef;var b2PulleyJoint=$i_108.Dynamics.Joints.b2PulleyJoint;var b2PulleyJointDef=$i_108.Dynamics.Joints.b2PulleyJointDef;var b2RevoluteJoint=$i_108.Dynamics.Joints.b2RevoluteJoint;var b2RevoluteJointDef=$i_108.Dynamics.Joints.b2RevoluteJointDef;var b2WeldJoint=$i_108.Dynamics.Joints.b2WeldJoint;var b2WeldJointDef=$i_108.Dynamics.Joints.b2WeldJointDef;var b2Body=$i_108.Dynamics.b2Body;var b2BodyDef=$i_108.Dynamics.b2BodyDef;var b2ContactFilter=$i_108.Dynamics.b2ContactFilter;var b2ContactImpulse=$i_108.Dynamics.b2ContactImpulse;var b2ContactListener=$i_108.Dynamics.b2ContactListener;var b2ContactManager=$i_108.Dynamics.b2ContactManager;var b2DebugDraw=$i_108.Dynamics.b2DebugDraw;var b2DestructionListener=$i_108.Dynamics.b2DestructionListener;var b2FilterData=$i_108.Dynamics.b2FilterData;var b2Fixture=$i_108.Dynamics.b2Fixture;var b2FixtureDef=$i_108.Dynamics.b2FixtureDef;var b2Island=$i_108.Dynamics.b2Island;var b2TimeStep=$i_108.Dynamics.b2TimeStep;var b2World=$i_108.Dynamics.b2World;$i_108.inherit(b2DistanceJoint,$i_108.Dynamics.Joints.b2Joint);b2DistanceJoint.prototype.__super=$i_108.Dynamics.Joints.b2Joint.prototype;b2DistanceJoint.b2DistanceJoint=function(){$i_108.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_localAnchor1=new b2Vec2;this.m_localAnchor2=new b2Vec2;this.m_u=new b2Vec2};b2DistanceJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};b2DistanceJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};b2DistanceJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return new b2Vec2(inv_dt*this.m_impulse*this.m_u.x,inv_dt*this.m_impulse*this.m_u.y)};b2DistanceJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return 0};b2DistanceJoint.prototype.GetLength=function(){return this.m_length};b2DistanceJoint.prototype.SetLength=function(length){if(length===undefined)length=0;this.m_length=length};b2DistanceJoint.prototype.GetFrequency=function(){return this.m_frequencyHz};b2DistanceJoint.prototype.SetFrequency=function(hz){if(hz===undefined)hz=0;this.m_frequencyHz=hz};b2DistanceJoint.prototype.GetDampingRatio=function(){return this.m_dampingRatio};b2DistanceJoint.prototype.SetDampingRatio=function(ratio){if(ratio===undefined)ratio=0;this.m_dampingRatio=ratio};b2DistanceJoint.prototype.b2DistanceJoint=function(def){this.__super.b2Joint.call(this,def);var tMat;var tX=0;var tY=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};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>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>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}};b2DistanceJoint.prototype.SolveVelocityConstraints=function(step){var tMat;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;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=bA.m_linearVelocity.x+-bA.m_angularVelocity*r1Y;var v1Y=bA.m_linearVelocity.y+bA.m_angularVelocity*r1X;var v2X=bB.m_linearVelocity.x+-bB.m_angularVelocity*r2Y;var v2Y=bB.m_linearVelocity.y+bB.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;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)};b2DistanceJoint.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;var tMat;if(this.m_frequencyHz>0){return true}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;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 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;var length=Math.sqrt(dX*dX+dY*dY);dX/=length;dY/=length;var C=length-this.m_length;C=b2Math.Clamp(C,-b2Settings.b2_maxLinearCorrection,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;bA.m_sweep.c.x-=bA.m_invMass*PX;bA.m_sweep.c.y-=bA.m_invMass*PY;bA.m_sweep.a-=bA.m_invI*(r1X*PY-r1Y*PX);bB.m_sweep.c.x+=bB.m_invMass*PX;bB.m_sweep.c.y+=bB.m_invMass*PY;bB.m_sweep.a+=bB.m_invI*(r2X*PY-r2Y*PX);bA.SynchronizeTransform();bB.SynchronizeTransform();return b2Math.Abs(C)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}};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=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=b2Math.MulMV(this.m_linearMass,new b2Vec2(-CdotX,-CdotY));var oldImpulseV=this.m_linearImpulse.Copy();this.m_linearImpulse.Add(impulseV);maxImpulse=step.dt*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()>maxImpulse*maxImpulse){this.m_linearImpulse.Normalize();this.m_linearImpulse.Multiply(maxImpulse)}impulseV=b2Math.SubtractVV(this.m_linearImpulse,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)}bA.m_angularVelocity=wA;bB.m_angularVelocity=wB};b2FrictionJoint.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;return true};$i_108.inherit(b2FrictionJointDef,$i_108.Dynamics.Joints.b2JointDef);b2FrictionJointDef.prototype.__super=$i_108.Dynamics.Joints.b2JointDef.prototype;b2FrictionJointDef.b2FrictionJointDef=function(){$i_108.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2};b2FrictionJointDef.prototype.b2FrictionJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_frictionJoint;this.maxForce=0;this.maxTorque=0};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))};$i_108.inherit(b2GearJoint,$i_108.Dynamics.Joints.b2Joint);b2GearJoint.prototype.__super=$i_108.Dynamics.Joints.b2Joint.prototype;b2GearJoint.b2GearJoint=function(){$i_108.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_groundAnchor1=new b2Vec2;this.m_groundAnchor2=new b2Vec2;this.m_localAnchor1=new b2Vec2;this.m_localAnchor2=new b2Vec2;this.m_J=new b2Jacobian};b2GearJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};b2GearJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};b2GearJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return new b2Vec2(inv_dt*this.m_impulse*this.m_J.linearB.x,inv_dt*this.m_impulse*this.m_J.linearB.y)};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)};b2GearJoint.prototype.GetRatio=function(){return this.m_ratio};b2GearJoint.prototype.SetRatio=function(ratio){if(ratio===undefined)ratio=0;this.m_ratio=ratio};b2GearJoint.prototype.b2GearJoint=function(def){this.__super.b2Joint.call(this,def);var type1=parseInt(def.joint1.m_type);var type2=parseInt(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==b2Joint.e_revoluteJoint){this.m_revolute1=def.joint1 instanceof b2RevoluteJoint?def.joint1:null;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 instanceof b2PrismaticJoint?def.joint1:null;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==b2Joint.e_revoluteJoint){this.m_revolute2=def.joint2 instanceof b2RevoluteJoint?def.joint2:null;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 instanceof b2PrismaticJoint?def.joint2:null;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};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>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}};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};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 linearErrorNumber.MIN_VALUE?1/this.m_motorMass:0}{this.m_perp.SetV(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(b2Math.Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2Settings.b2_linearSlop){this.m_limitState=b2Joint.e_equalLimits}else if(jointTransition<=this.m_lowerTranslation){if(this.m_limitState!=b2Joint.e_atLowerLimit){this.m_limitState=b2Joint.e_atLowerLimit;this.m_impulse.y=0}}else if(jointTransition>=this.m_upperTranslation){if(this.m_limitState!=b2Joint.e_atUpperLimit){this.m_limitState=b2Joint.e_atUpperLimit;this.m_impulse.y=0}}else{this.m_limitState=b2Joint.e_inactiveLimit;this.m_impulse.y=0}}else{this.m_limitState=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}};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&&this.m_limitState!=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=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&&this.m_limitState!=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=this.m_K.Solve(new b2Vec2,-Cdot1,-Cdot2);this.m_impulse.Add(df);if(this.m_limitState==b2Joint.e_atLowerLimit){this.m_impulse.y=b2Math.Max(this.m_impulse.y,0)}else if(this.m_limitState==b2Joint.e_atUpperLimit){this.m_impulse.y=b2Math.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;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};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=b2Mat22.FromAngle(a1);var R2=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=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(b2Math.Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2Settings.b2_linearSlop){C2=b2Math.Clamp(translation,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);linearError=b2Math.Abs(translation);active=true}else if(translation<=this.m_lowerTranslation){C2=b2Math.Clamp(translation-this.m_lowerTranslation+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0);linearError=this.m_lowerTranslation-translation;active=true}else if(translation>=this.m_upperTranslation){C2=b2Math.Clamp(translation-this.m_upperTranslation+b2Settings.b2_linearSlop,0,b2Settings.b2_maxLinearCorrection);linearError=translation-this.m_upperTranslation;active=true}}this.m_perp=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=new b2Vec2;var C1=this.m_perp.x*dX+this.m_perp.y*dY;linearError=b2Math.Max(linearError,b2Math.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<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop};$i_108.inherit(b2LineJointDef,$i_108.Dynamics.Joints.b2JointDef);b2LineJointDef.prototype.__super=$i_108.Dynamics.Joints.b2JointDef.prototype;b2LineJointDef.b2LineJointDef=function(){$i_108.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2;this.localAxisA=new b2Vec2};b2LineJointDef.prototype.b2LineJointDef=function(){this.__super.b2JointDef.call(this);this.type=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};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)};$i_108.inherit(b2MouseJoint,$i_108.Dynamics.Joints.b2Joint);b2MouseJoint.prototype.__super=$i_108.Dynamics.Joints.b2Joint.prototype;b2MouseJoint.b2MouseJoint=function(){$i_108.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.K=new b2Mat22;this.K1=new b2Mat22;this.K2=new b2Mat22;this.m_localAnchor=new b2Vec2;this.m_target=new b2Vec2;this.m_impulse=new b2Vec2;this.m_mass=new b2Mat22;this.m_C=new b2Vec2};b2MouseJoint.prototype.GetAnchorA=function(){return this.m_target};b2MouseJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor)};b2MouseJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return new b2Vec2(inv_dt*this.m_impulse.x,inv_dt*this.m_impulse.y)};b2MouseJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return 0};b2MouseJoint.prototype.GetTarget=function(){return this.m_target};b2MouseJoint.prototype.SetTarget=function(target){if(this.m_bodyB.IsAwake()==false){this.m_bodyB.SetAwake(true)}this.m_target=target};b2MouseJoint.prototype.GetMaxForce=function(){return this.m_maxForce};b2MouseJoint.prototype.SetMaxForce=function(maxForce){if(maxForce===undefined)maxForce=0;this.m_maxForce=maxForce};b2MouseJoint.prototype.GetFrequency=function(){return this.m_frequencyHz};b2MouseJoint.prototype.SetFrequency=function(hz){if(hz===undefined)hz=0;this.m_frequencyHz=hz};b2MouseJoint.prototype.GetDampingRatio=function(){return this.m_dampingRatio};b2MouseJoint.prototype.SetDampingRatio=function(ratio){if(ratio===undefined)ratio=0;this.m_dampingRatio=ratio};b2MouseJoint.prototype.b2MouseJoint=function(def){this.__super.b2Joint.call(this,def);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};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*=0.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)};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()>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)};b2MouseJoint.prototype.SolvePositionConstraints=function(baumgarte){if(baumgarte===undefined)baumgarte=0;return true};$i_108.inherit(b2MouseJointDef,$i_108.Dynamics.Joints.b2JointDef);b2MouseJointDef.prototype.__super=$i_108.Dynamics.Joints.b2JointDef.prototype;b2MouseJointDef.b2MouseJointDef=function(){$i_108.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.target=new b2Vec2};b2MouseJointDef.prototype.b2MouseJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_mouseJoint;this.maxForce=0;this.frequencyHz=5;this.dampingRatio=0.7};$i_108.inherit(b2PrismaticJoint,$i_108.Dynamics.Joints.b2Joint);b2PrismaticJoint.prototype.__super=$i_108.Dynamics.Joints.b2Joint.prototype;b2PrismaticJoint.b2PrismaticJoint=function(){$i_108.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_localAnchor1=new b2Vec2;this.m_localAnchor2=new b2Vec2;this.m_localXAxis1=new b2Vec2;this.m_localYAxis1=new b2Vec2;this.m_axis=new b2Vec2;this.m_perp=new b2Vec2;this.m_K=new b2Mat33;this.m_impulse=new b2Vec3};b2PrismaticJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};b2PrismaticJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};b2PrismaticJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return new b2Vec2(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))};b2PrismaticJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return inv_dt*this.m_impulse.y};b2PrismaticJoint.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};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));return speed};b2PrismaticJoint.prototype.IsLimitEnabled=function(){return this.m_enableLimit};b2PrismaticJoint.prototype.EnableLimit=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag};b2PrismaticJoint.prototype.GetLowerLimit=function(){return this.m_lowerTranslation};b2PrismaticJoint.prototype.GetUpperLimit=function(){return this.m_upperTranslation};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};b2PrismaticJoint.prototype.IsMotorEnabled=function(){return this.m_enableMotor};b2PrismaticJoint.prototype.EnableMotor=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag};b2PrismaticJoint.prototype.SetMotorSpeed=function(speed){if(speed===undefined)speed=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed};b2PrismaticJoint.prototype.GetMotorSpeed=function(){return this.m_motorSpeed};b2PrismaticJoint.prototype.SetMaxMotorForce=function(force){if(force===undefined)force=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorForce=force};b2PrismaticJoint.prototype.GetMotorForce=function(){return this.m_motorImpulse};b2PrismaticJoint.prototype.b2PrismaticJoint=function(def){this.__super.b2Joint.call(this,def);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_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=b2Joint.e_inactiveLimit;this.m_axis.SetZero();this.m_perp.SetZero()};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();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(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;if(this.m_motorMass>Number.MIN_VALUE)this.m_motorMass=1/this.m_motorMass}{this.m_perp.SetV(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+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(b2Math.Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2Settings.b2_linearSlop){this.m_limitState=b2Joint.e_equalLimits}else if(jointTransition<=this.m_lowerTranslation){if(this.m_limitState!=b2Joint.e_atLowerLimit){this.m_limitState=b2Joint.e_atLowerLimit;this.m_impulse.z=0}}else if(jointTransition>=this.m_upperTranslation){if(this.m_limitState!=b2Joint.e_atUpperLimit){this.m_limitState=b2Joint.e_atUpperLimit;this.m_impulse.z=0}}else{this.m_limitState=b2Joint.e_inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=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}};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&&this.m_limitState!=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=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&&this.m_limitState!=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=this.m_K.Solve33(new b2Vec3,-Cdot1X,-Cdot1Y,-Cdot2);this.m_impulse.Add(df);if(this.m_limitState==b2Joint.e_atLowerLimit){this.m_impulse.z=b2Math.Max(this.m_impulse.z,0)}else if(this.m_limitState==b2Joint.e_atUpperLimit){this.m_impulse.z=b2Math.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 f2r=this.m_K.Solve22(new b2Vec2,bX,bY);f2r.x+=f1.x;f2r.y+=f1.y;this.m_impulse.x=f2r.x;this.m_impulse.y=f2r.y;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;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=this.m_K.Solve22(new b2Vec2,-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;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};b2PrismaticJoint.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=b2Mat22.FromAngle(a1);var R2=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=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(b2Math.Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2Settings.b2_linearSlop){C2=b2Math.Clamp(translation,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);linearError=b2Math.Abs(translation);active=true}else if(translation<=this.m_lowerTranslation){C2=b2Math.Clamp(translation-this.m_lowerTranslation+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0);linearError=this.m_lowerTranslation-translation;active=true}else if(translation>=this.m_upperTranslation){C2=b2Math.Clamp(translation-this.m_upperTranslation+b2Settings.b2_linearSlop,0,b2Settings.b2_maxLinearCorrection);linearError=translation-this.m_upperTranslation;active=true}}this.m_perp=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=new b2Vec3;var C1X=this.m_perp.x*dX+this.m_perp.y*dY;var C1Y=a2-a1-this.m_refAngle;linearError=b2Math.Max(linearError,b2Math.Abs(C1X));angularError=b2Math.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=this.m_K.Solve22(new b2Vec2,-C1X,-C1Y);impulse.x=impulse1.x;impulse.y=impulse1.y;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;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<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop};$i_108.inherit(b2PrismaticJointDef,$i_108.Dynamics.Joints.b2JointDef);b2PrismaticJointDef.prototype.__super=$i_108.Dynamics.Joints.b2JointDef.prototype;b2PrismaticJointDef.b2PrismaticJointDef=function(){$i_108.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2;this.localAxisA=new b2Vec2};b2PrismaticJointDef.prototype.b2PrismaticJointDef=function(){this.__super.b2JointDef.call(this);this.type=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};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()};$i_108.inherit(b2PulleyJoint,$i_108.Dynamics.Joints.b2Joint);b2PulleyJoint.prototype.__super=$i_108.Dynamics.Joints.b2Joint.prototype;b2PulleyJoint.b2PulleyJoint=function(){$i_108.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_groundAnchor1=new b2Vec2;this.m_groundAnchor2=new b2Vec2;this.m_localAnchor1=new b2Vec2;this.m_localAnchor2=new b2Vec2;this.m_u1=new b2Vec2;this.m_u2=new b2Vec2};b2PulleyJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};b2PulleyJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};b2PulleyJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return new b2Vec2(inv_dt*this.m_impulse*this.m_u2.x,inv_dt*this.m_impulse*this.m_u2.y)};b2PulleyJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return 0};b2PulleyJoint.prototype.GetGroundAnchorA=function(){var a=this.m_ground.m_xf.position.Copy();a.Add(this.m_groundAnchor1);return a};b2PulleyJoint.prototype.GetGroundAnchorB=function(){var a=this.m_ground.m_xf.position.Copy();a.Add(this.m_groundAnchor2);return a};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)};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)};b2PulleyJoint.prototype.GetRatio=function(){return this.m_ratio};b2PulleyJoint.prototype.b2PulleyJoint=function(def){this.__super.b2Joint.call(this,def);var tMat;var tX=0;var tY=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=b2Math.Min(def.maxLengthA,this.m_constant-this.m_ratio*b2PulleyJoint.b2_minPulleyLength);this.m_maxLength2=b2Math.Min(def.maxLengthB,(this.m_constant-b2PulleyJoint.b2_minPulleyLength)/this.m_ratio);this.m_impulse=0;this.m_limitImpulse1=0;this.m_limitImpulse2=0};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>b2Settings.b2_linearSlop){this.m_u1.Multiply(1/length1)}else{this.m_u1.SetZero()}if(length2>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>0){this.m_state=b2Joint.e_inactiveLimit;this.m_impulse=0}else{this.m_state=b2Joint.e_atUpperLimit}if(length1b2Settings.b2_linearSlop){this.m_u1.Multiply(1/length1)}else{this.m_u1.SetZero()}if(length2>b2Settings.b2_linearSlop){this.m_u2.Multiply(1/length2)}else{this.m_u2.SetZero()}C=this.m_constant-length1-this.m_ratio*length2;linearError=b2Math.Max(linearError,-C);C=b2Math.Clamp(C+b2Settings.b2_linearSlop,-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==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>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=b2Math.Max(linearError,-C);C=b2Math.Clamp(C+b2Settings.b2_linearSlop,-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==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>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=b2Math.Max(linearError,-C);C=b2Math.Clamp(C+b2Settings.b2_linearSlop,-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=this.m_upperAngle){if(this.m_limitState!=b2Joint.e_atUpperLimit){this.m_impulse.z=0}this.m_limitState=b2Joint.e_atUpperLimit}else{this.m_limitState=b2Joint.e_inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=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}};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&&this.m_limitState!=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=b2Math.Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;w1-=i1*impulse;w2+=i2*impulse}if(this.m_enableLimit&&this.m_limitState!=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==b2Joint.e_equalLimits){this.m_impulse.Add(this.impulse3)}else if(this.m_limitState==b2Joint.e_atLowerLimit){newImpulse=this.m_impulse.z+this.impulse3.z;if(newImpulse<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==b2Joint.e_atUpperLimit){newImpulse=this.m_impulse.z+this.impulse3.z;if(newImpulse>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};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&&this.m_limitState!=b2Joint.e_inactiveLimit){var angle=bB.m_sweep.a-bA.m_sweep.a-this.m_referenceAngle;var limitImpulse=0;if(this.m_limitState==b2Joint.e_equalLimits){C=b2Math.Clamp(angle-this.m_lowerAngle,-b2Settings.b2_maxAngularCorrection,b2Settings.b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C;angularError=b2Math.Abs(C)}else if(this.m_limitState==b2Joint.e_atLowerLimit){C=angle-this.m_lowerAngle;angularError=-C;C=b2Math.Clamp(C+b2Settings.b2_angularSlop,-b2Settings.b2_maxAngularCorrection,0);limitImpulse=-this.m_motorMass*C}else if(this.m_limitState==b2Joint.e_atUpperLimit){C=angle-this.m_upperAngle;angularError=C;C=b2Math.Clamp(C-b2Settings.b2_angularSlop,0,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*b2Settings.b2_linearSlop;if(CLengthSquared>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=0.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(b2RevoluteJoint.tImpulse,-CX,-CY);impulseX=b2RevoluteJoint.tImpulse.x;impulseY=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<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop};$i_108.postDefs.push(function(){$i_108.Dynamics.Joints.b2RevoluteJoint.tImpulse=new b2Vec2});$i_108.inherit(b2RevoluteJointDef,$i_108.Dynamics.Joints.b2JointDef);b2RevoluteJointDef.prototype.__super=$i_108.Dynamics.Joints.b2JointDef.prototype;b2RevoluteJointDef.b2RevoluteJointDef=function(){$i_108.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2};b2RevoluteJointDef.prototype.b2RevoluteJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_revoluteJoint;this.localAnchorA.Set(0,0);this.localAnchorB.Set(0,0);this.referenceAngle=0;this.lowerAngle=0;this.upperAngle=0;this.maxMotorTorque=0;this.motorSpeed=0;this.enableLimit=false;this.enableMotor=false};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()};$i_108.inherit(b2WeldJoint,$i_108.Dynamics.Joints.b2Joint);b2WeldJoint.prototype.__super=$i_108.Dynamics.Joints.b2Joint.prototype;b2WeldJoint.b2WeldJoint=function(){$i_108.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_localAnchorA=new b2Vec2;this.m_localAnchorB=new b2Vec2;this.m_impulse=new b2Vec3;this.m_mass=new b2Mat33};b2WeldJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA)};b2WeldJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB)};b2WeldJoint.prototype.GetReactionForce=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return new b2Vec2(inv_dt*this.m_impulse.x,inv_dt*this.m_impulse.y)};b2WeldJoint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return inv_dt*this.m_impulse.z};b2WeldJoint.prototype.b2WeldJoint=function(def){this.__super.b2Joint.call(this,def);this.m_localAnchorA.SetV(def.localAnchorA);this.m_localAnchorB.SetV(def.localAnchorB);this.m_referenceAngle=def.referenceAngle;this.m_impulse.SetZero();this.m_mass=new b2Mat33};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()}};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=new b2Vec3;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);bA.m_angularVelocity=wA;bB.m_angularVelocity=wB};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*b2Settings.b2_linearSlop;var positionError=Math.sqrt(C1X*C1X+C1Y*C1Y);var angularError=b2Math.Abs(C2);if(positionError>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=new b2Vec3;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);bA.SynchronizeTransform();bB.SynchronizeTransform();return positionError<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop};$i_108.inherit(b2WeldJointDef,$i_108.Dynamics.Joints.b2JointDef);b2WeldJointDef.prototype.__super=$i_108.Dynamics.Joints.b2JointDef.prototype;b2WeldJointDef.b2WeldJointDef=function(){$i_108.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2};b2WeldJointDef.prototype.b2WeldJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_weldJoint;this.referenceAngle=0};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()}})();(function(){var b2DebugDraw=$i_108.Dynamics.b2DebugDraw;b2DebugDraw.b2DebugDraw=function(){this.m_drawScale=1;this.m_lineThickness=1;this.m_alpha=1;this.m_fillAlpha=1;this.m_xformScale=1;var __this=this;this.m_sprite={graphics:{clear:function(){},setTranslation:function(x,y){__this.m_ctx.translate(x,y)}}}};b2DebugDraw.prototype._color=function(color,alpha){return`rgba(${(color&16711680)>>16},${(color&65280)>>8},${color&255},${alpha})`};b2DebugDraw.prototype.b2DebugDraw=function(){this.m_drawFlags=0};b2DebugDraw.prototype.SetFlags=function(flags){if(flags===undefined)flags=0;this.m_drawFlags=flags};b2DebugDraw.prototype.GetFlags=function(){return this.m_drawFlags};b2DebugDraw.prototype.AppendFlags=function(flags){if(flags===undefined)flags=0;this.m_drawFlags|=flags};b2DebugDraw.prototype.ClearFlags=function(flags){if(flags===undefined)flags=0;this.m_drawFlags&=~flags};b2DebugDraw.prototype.SetSprite=function(sprite){this.m_ctx=sprite};b2DebugDraw.prototype.GetSprite=function(){return this.m_ctx};b2DebugDraw.prototype.SetDrawScale=function(drawScale){if(drawScale===undefined)drawScale=0;this.m_drawScale=drawScale};b2DebugDraw.prototype.GetDrawScale=function(){return this.m_drawScale};b2DebugDraw.prototype.SetLineThickness=function(lineThickness){if(lineThickness===undefined)lineThickness=0;this.m_lineThickness=lineThickness;this.m_ctx.strokeWidth=lineThickness};b2DebugDraw.prototype.GetLineThickness=function(){return this.m_lineThickness};b2DebugDraw.prototype.SetAlpha=function(alpha){if(alpha===undefined)alpha=0;this.m_alpha=alpha};b2DebugDraw.prototype.GetAlpha=function(){return this.m_alpha};b2DebugDraw.prototype.SetFillAlpha=function(alpha){if(alpha===undefined)alpha=0;this.m_fillAlpha=alpha};b2DebugDraw.prototype.GetFillAlpha=function(){return this.m_fillAlpha};b2DebugDraw.prototype.SetXFormScale=function(xformScale){if(xformScale===undefined)xformScale=0;this.m_xformScale=xformScale};b2DebugDraw.prototype.GetXFormScale=function(){return this.m_xformScale};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.color,this.m_alpha);s.moveTo(vertices[0].x*drawScale,vertices[0].y*drawScale);for(var i=1;i=0&&dY>=0;valid=valid&&this.lowerBound.IsValid()&&this.upperBound.IsValid();return valid};b2AABB.prototype.GetCenter=function(){return new b2Vec2((this.lowerBound.x+this.upperBound.x)/2,(this.lowerBound.y+this.upperBound.y)/2)};b2AABB.prototype.GetExtents=function(){return new b2Vec2((this.upperBound.x-this.lowerBound.x)/2,(this.upperBound.y-this.lowerBound.y)/2)};b2AABB.prototype.Contains=function(aabb){var result=true;result=result&&this.lowerBound.x<=aabb.lowerBound.x;result=result&&this.lowerBound.y<=aabb.lowerBound.y;result=result&&aabb.upperBound.x<=this.upperBound.x;result=result&&aabb.upperBound.y<=this.upperBound.y;return result};b2AABB.prototype.RayCast=function(output,input){var tmin=-Number.MAX_VALUE;var tmax=Number.MAX_VALUE;var pX=input.p1.x;var pY=input.p1.y;var dX=input.p2.x-input.p1.x;var dY=input.p2.y-input.p1.y;var absDX=Math.abs(dX);var absDY=Math.abs(dY);var normal=output.normal;var inv_d=0;var t1=0;var t2=0;var t3=0;var s=0;{if(absDXt2){t3=t1;t1=t2;t2=t3;s=1}if(t1>tmin){normal.x=s;normal.y=0;tmin=t1}tmax=Math.min(tmax,t2);if(tmin>tmax)return false}}{if(absDYt2){t3=t1;t1=t2;t2=t3;s=1}if(t1>tmin){normal.y=s;normal.x=0;tmin=t1}tmax=Math.min(tmax,t2);if(tmin>tmax)return false}}output.fraction=tmin;return true};b2AABB.prototype.TestOverlap=function(other){var d1X=other.lowerBound.x-this.upperBound.x;var d1Y=other.lowerBound.y-this.upperBound.y;var d2X=this.lowerBound.x-other.upperBound.x;var d2Y=this.lowerBound.y-other.upperBound.y;if(d1X>0||d1Y>0)return false;if(d2X>0||d2Y>0)return false;return true};b2AABB.Combine=function(aabb1,aabb2){var aabb=new b2AABB;aabb.Combine(aabb1,aabb2);return aabb};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)};b2AABB.prototype.Free=function(){};b2Bound.b2Bound=function(){};b2Bound.prototype.IsLower=function(){return(this.value&1)===0};b2Bound.prototype.IsUpper=function(){return(this.value&1)===1};b2Bound.prototype.Swap=function(b){var tempValue=this.value;var tempProxy=this.proxy;var tempStabbingCount=this.stabbingCount;this.value=b.value;this.proxy=b.proxy;this.stabbingCount=b.stabbingCount;b.value=tempValue;b.proxy=tempProxy;b.stabbingCount=tempStabbingCount};b2BoundValues.b2BoundValues=function(){};b2BoundValues.prototype.b2BoundValues=function(){this.lowerValues=[0,0];this.upperValues=[0,0]};b2Collision.b2Collision=function(){};b2Collision.ClipSegmentToLine=function(vOut,vIn,normal,offset){var numOut=0;var cv=vIn[0];var vIn0=cv.v;cv=vIn[1];var vIn1=cv.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<=0)vOut[numOut++].Set(vIn[0]);if(distance1<=0)vOut[numOut++].Set(vIn[1]);if(distance0*distance1<0){var interp=distance0/(distance0-distance1);cv=vOut[numOut];var tVec=cv.v;tVec.x=vIn0.x+interp*(vIn1.x-vIn0.x);tVec.y=vIn0.y+interp*(vIn1.y-vIn0.y);cv=vOut[numOut];var cv2;if(distance0>0){cv2=vIn[0];cv.id=cv2.id}else{cv2=vIn[1];cv.id=cv2.id}++numOut}return numOut};b2Collision.EdgeSeparation=function(poly1,xf1,edge1,poly2,xf2){var verts=poly2.m_vertices;var tMat=xf1.R;var tVec=poly1.m_normals[edge1];var normal1WorldX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var normal1WorldY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=xf2.R;var normal1X=tMat.col1.x*normal1WorldX+tMat.col1.y*normal1WorldY;var normal1Y=tMat.col2.x*normal1WorldX+tMat.col2.y*normal1WorldY;var index=0;var minDot=Number.MAX_VALUE;var i=poly2.m_vertexCount;while(i>0){tVec=verts[--i];var dot=tVec.x*normal1X+tVec.y*normal1Y;if(dot0){tVec=normals1[--i];var dot=tVec.x*dLocal1X+tVec.y*dLocal1Y;if(dot>maxDot){maxDot=dot;edge=i}}var s=b2Collision.EdgeSeparation(poly1,xf1,edge,poly2,xf2);var prevEdge=edge-1>=0?edge-1:count1-1;var sPrev=b2Collision.EdgeSeparation(poly1,xf1,prevEdge,poly2,xf2);var nextEdge=edge+1s&&sPrev>sNext){increment=-1;bestEdge=prevEdge;bestSeparation=sPrev}else if(sNext>s){increment=1;bestEdge=nextEdge;bestSeparation=sNext}else{edgeIndex[0]=edge;return s}while(true){if(increment===-1)edge=bestEdge-1>=0?bestEdge-1:count1-1;else edge=bestEdge+1bestSeparation){bestEdge=edge;bestSeparation=s}else break}edgeIndex[0]=bestEdge;return bestSeparation};b2Collision.FindIncidentEdge=function(c,poly1,xf1,edge1,poly2,xf2){var normals2=poly2.m_normals;var tMat=xf1.R;var tVec=poly1.m_normals[edge1];var normal1X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var normal1Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=xf2.R;var tX=tMat.col1.x*normal1X+tMat.col1.y*normal1Y;normal1Y=tMat.col2.x*normal1X+tMat.col2.y*normal1Y;normal1X=tX;var index=0;var minDot=Number.MAX_VALUE;var i=poly2.m_vertexCount;while(i>0){tVec=normals2[--i];var dot=normal1X*tVec.x+normal1Y*tVec.y;if(dottotalRadius)return;var edgeB=0;b2Collision.s_edgeBO[0]=edgeB;var separationB=b2Collision.FindMaxSeparation(b2Collision.s_edgeBO,polyB,xfB,polyA,xfA);edgeB=b2Collision.s_edgeBO[0];if(separationB>totalRadius)return;var poly1;var poly2;var xf1;var xf2;var edge1=0;var flip=0;var k_relativeTol=0.98;var k_absoluteTol=0.001;if(separationB>k_relativeTol*separationA+k_absoluteTol){poly1=polyB;poly2=polyA;xf1=xfB;xf2=xfA;edge1=edgeB;manifold.m_type=b2Manifold.e_faceB;flip=1}else{poly1=polyA;poly2=polyB;xf1=xfA;xf2=xfB;edge1=edgeA;manifold.m_type=b2Manifold.e_faceA;flip=0}var incidentEdge=b2Collision.s_incidentEdge;b2Collision.FindIncidentEdge(incidentEdge,poly1,xf1,edge1,poly2,xf2);var count1=poly1.m_vertexCount;var vertices1=poly1.m_vertices;var local_v11=vertices1[edge1];var local_v12;if(edge1+1radius*radius){manifold.m_pointCount=0;return}manifold.m_type=b2Manifold.e_circles;manifold.m_localPoint.SetV(circle1.m_p);manifold.m_localPlaneNormal.SetZero();manifold.m_pointCount=1;manifold.m_points[0].m_localPoint.SetV(circle2.m_p);manifold.m_points[0].m_id.key=0};b2Collision.CollidePolygonAndCircle=function(manifold,polygon,xf1,circle,xf2){manifold.m_pointCount=0;var tMat=xf2.R;var tVec=circle.m_p;var cX=xf2.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var cY=xf2.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);var dX=cX-xf1.position.x;var dY=cY-xf1.position.y;tMat=xf1.R;var cLocalX=dX*tMat.col1.x+dY*tMat.col1.y;var cLocalY=dX*tMat.col2.x+dY*tMat.col2.y;var normalIndex=0;var separation=-Number.MAX_VALUE;var radius=polygon.m_radius+circle.m_radius;var vertexCount=polygon.m_vertexCount;var vertices=polygon.m_vertices;var normals=polygon.m_normals;for(var i=0;iradius){return}if(s>separation){separation=s;normalIndex=i}}var vertIndex1=normalIndex;var vertIndex2=vertIndex1+1radius*radius)return;manifold.m_pointCount=1;manifold.m_type=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.m_p);manifold.m_points[0].m_id.key=0}else if(u2<=0){if((cLocalX-v2.x)*(cLocalX-v2.x)+(cLocalY-v2.y)*(cLocalY-v2.y)>radius*radius)return;manifold.m_pointCount=1;manifold.m_type=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.m_p);manifold.m_points[0].m_id.key=0}else{var faceCenterX=0.5*(v1.x+v2.x);var faceCenterY=0.5*(v1.y+v2.y);separation=(cLocalX-faceCenterX)*normals[vertIndex1].x+(cLocalY-faceCenterY)*normals[vertIndex1].y;if(separation>radius)return;manifold.m_pointCount=1;manifold.m_type=b2Manifold.e_faceA;manifold.m_localPlaneNormal.x=normals[vertIndex1].x;manifold.m_localPlaneNormal.y=normals[vertIndex1].y;manifold.m_localPlaneNormal.Normalize();manifold.m_localPoint.Set(faceCenterX,faceCenterY);manifold.m_points[0].m_localPoint.SetV(circle.m_p);manifold.m_points[0].m_id.key=0}};b2Collision.TestOverlap=function(a,b){var t1=b.lowerBound;var t2=a.upperBound;var d1X=t1.x-t2.x;var d1Y=t1.y-t2.y;t1=a.lowerBound;t2=b.upperBound;var d2X=t1.x-t2.x;var d2Y=t1.y-t2.y;if(d1X>0||d1Y>0)return false;if(d2X>0||d2Y>0)return false;return true};$i_109.postDefs.push(function(){$i_109.Collision.b2Collision.s_incidentEdge=b2Collision.MakeClipPointVector();$i_109.Collision.b2Collision.s_clipPoints1=b2Collision.MakeClipPointVector();$i_109.Collision.b2Collision.s_clipPoints2=b2Collision.MakeClipPointVector();$i_109.Collision.b2Collision.s_edgeAO=[0];$i_109.Collision.b2Collision.s_edgeBO=[0];$i_109.Collision.b2Collision.s_localTangent=new b2Vec2;$i_109.Collision.b2Collision.s_localNormal=new b2Vec2;$i_109.Collision.b2Collision.s_planePoint=new b2Vec2;$i_109.Collision.b2Collision.s_normal=new b2Vec2;$i_109.Collision.b2Collision.s_tangent=new b2Vec2;$i_109.Collision.b2Collision.s_tangent2=new b2Vec2;$i_109.Collision.b2Collision.s_v11=new b2Vec2;$i_109.Collision.b2Collision.s_v12=new b2Vec2;$i_109.Collision.b2Collision.b2CollidePolyTempVec=new b2Vec2;$i_109.Collision.b2Collision.b2_nullFeature=255});b2ContactID.prototype.b2ContactID=function(){this.features._m_id=this};b2ContactID.prototype.Set=function(id){this.key=id._key};b2ContactID.prototype.Copy=function(){var id=new b2ContactID;id.key=this.key;return id};Object.defineProperty(b2ContactID.prototype,"key",{enumerable:false,configurable:true,get:function(){return this._key}});Object.defineProperty(b2ContactID.prototype,"key",{enumerable:false,configurable:true,set:function(value){this._key=value;this.features._referenceEdge=this._key&255;this.features._incidentEdge=(this._key&65280)>>8&255;this.features._incidentVertex=(this._key&16711680)>>16&255;this.features._flip=(this._key&4278190080)>>24&255}});b2ContactPoint.b2ContactPoint=function(){this.position=new b2Vec2;this.velocity=new b2Vec2;this.normal=new b2Vec2;this.id=new b2ContactID};b2Distance.b2Distance=function(){};b2Distance.Distance=function(output,cache,input){var proxyA=input.proxyA;var proxyB=input.proxyB;var transformA=input.transformA;var transformB=input.transformB;var simplex=b2Distance.s_simplex;simplex.ReadCache(cache,proxyA,transformA,proxyB,transformB);var vertices=simplex.m_vertices;var k_maxIters=20;var saveA=b2Distance.s_saveA;var saveB=b2Distance.s_saveB;var saveCount=0;var i=0;var iter=0;while(iterrA+rB&&output.distance>Number.MIN_VALUE){output.distance-=rA+rB;var normal=b2Math.SubtractVV(output.pointB,output.pointA);normal.Normalize();output.pointA.x+=rA*normal.x;output.pointA.y+=rA*normal.y;output.pointB.x-=rB*normal.x;output.pointB.y-=rB*normal.y}else{var p=new b2Vec2(0.5*(output.pointA.x+output.pointB.x),0.5*(output.pointA.y+output.pointB.y));output.pointA.x=output.pointB.x=p.x;output.pointA.y=output.pointB.y=p.y;output.distance=0}}};$i_109.postDefs.push(function(){$i_109.Collision.b2Distance.s_simplex=new b2Simplex;$i_109.Collision.b2Distance.s_saveA=[0,0,0];$i_109.Collision.b2Distance.s_saveB=[0,0,0]});b2DistanceInput.b2DistanceInput=function(){};b2DistanceOutput.b2DistanceOutput=function(){this.pointA=new b2Vec2;this.pointB=new b2Vec2};b2DistanceProxy.prototype.Set=function(shape){switch(shape.GetType()){case b2Shape.e_circleShape:{this.m_vertices=[1,true];this.m_vertices[0]=shape.m_p;this.m_count=1;this.m_radius=shape.m_radius}break;case b2Shape.e_polygonShape:{this.m_vertices=shape.m_vertices;this.m_count=shape.m_vertexCount;this.m_radius=shape.m_radius}break;default:break;}};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;ibestValue){bestIndex=i;bestValue=value}}return bestIndex};b2DistanceProxy.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;ibestValue){bestIndex=i;bestValue=value}}return this.m_vertices[bestIndex]};b2DistanceProxy.prototype.GetVertexCount=function(){return this.m_count};b2DistanceProxy.prototype.GetVertex=function(index){return this.m_vertices[index]};b2DynamicTree.b2DynamicTree=function(){};b2DynamicTree.prototype.b2DynamicTree=function(){this.m_root=null;this.m_freeList=null;this.m_path=0;this.m_insertionCount=0};b2DynamicTree.prototype.CreateProxy=function(aabb,userData){var node=this.AllocateNode();var extendX=b2Settings.b2_aabbExtension;var extendY=b2Settings.b2_aabbExtension;node.aabb.lowerBound.x=aabb.lowerBound.x-extendX;node.aabb.lowerBound.y=aabb.lowerBound.y-extendY;node.aabb.upperBound.x=aabb.upperBound.x+extendX;node.aabb.upperBound.y=aabb.upperBound.y+extendY;node.userData=userData;this.InsertLeaf(node);return node};b2DynamicTree.prototype.DestroyProxy=function(proxy){this.RemoveLeaf(proxy);this.FreeNode(proxy)};b2DynamicTree.prototype.MoveProxy=function(proxy,aabb,displacement){if(proxy.aabb.Contains(aabb))return false;this.RemoveLeaf(proxy);var extendX=b2Settings.b2_aabbExtension+b2Settings.b2_aabbMultiplier*(displacement.x>0?displacement.x:-displacement.x);var extendY=b2Settings.b2_aabbExtension+b2Settings.b2_aabbMultiplier*(displacement.y>0?displacement.y:-displacement.y);proxy.aabb.lowerBound.x=aabb.lowerBound.x-extendX;proxy.aabb.lowerBound.y=aabb.lowerBound.y-extendY;proxy.aabb.upperBound.x=aabb.upperBound.x+extendX;proxy.aabb.upperBound.y=aabb.upperBound.y+extendY;this.InsertLeaf(proxy);return true};b2DynamicTree.prototype.Rebalance=function(iterations){for(var i=0;i>bit&1?node.child2:node.child1;bit=bit+1&31}++this.m_path;this.RemoveLeaf(node);this.InsertLeaf(node)}};b2DynamicTree.prototype.GetFatAABB=function(proxy){return proxy.aabb};b2DynamicTree.prototype.GetUserData=function(proxy){return proxy.userData};b2DynamicTree.prototype.Query=function(callback,aabb,proxy,thisArg){if(this.m_root===null)return;var stack=[this.m_root];var count=1;while(count>0){var node=stack[--count];if(node.aabb.TestOverlap(aabb)){if(node.IsLeaf()){var proceed=callback(node,proxy,thisArg);if(!proceed)return}else{stack[count++]=node.child1;stack[count++]=node.child2}}}};b2DynamicTree.prototype.RayCast=function(callback,input){var p1=input.p1;var p2=input.p2;var r=b2Math.SubtractVV(p1,p2);r.Normalize();var v=b2Math.CrossFV(1,r);var abs_v=b2Math.AbsV(v);var maxFraction=input.maxFraction;var segmentAABB=new b2AABB;var tX=0;var tY=0;{tX=p1.x+maxFraction*(p2.x-p1.x);tY=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=Math.min(p1.x,tX);segmentAABB.lowerBound.y=Math.min(p1.y,tY);segmentAABB.upperBound.x=Math.max(p1.x,tX);segmentAABB.upperBound.y=Math.max(p1.y,tY)}var stack=[this.m_root];var count=1;while(count>0){var node=stack[--count];if(node===null||node.aabb.TestOverlap(segmentAABB)===false){continue}var c=node.aabb.GetCenter();var h=node.aabb.GetExtents();var separation=Math.abs(v.x*(p1.x-c.x)+v.y*(p1.y-c.y))-abs_v.x*h.x-abs_v.y*h.y;if(separation>0)continue;if(node.IsLeaf()){var subInput=new b2RayCastInput;subInput.p1=input.p1;subInput.p2=input.p2;subInput.maxFraction=maxFraction;var value=callback(subInput,node);if(value===0)return;if(value>0){maxFraction=value;tX=p1.x+maxFraction*(p2.x-p1.x);tY=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=Math.min(p1.x,tX);segmentAABB.lowerBound.y=Math.min(p1.y,tY);segmentAABB.upperBound.x=Math.max(p1.x,tX);segmentAABB.upperBound.y=Math.max(p1.y,tY)}}else{stack[count++]=node.child1;stack[count++]=node.child2}}};b2DynamicTree.prototype.AllocateNode=function(){if(this.m_freeList){var node=this.m_freeList;this.m_freeList=node.parent;node.parent=null;node.child1=null;node.child2=null;return node}return new b2DynamicTreeNode};b2DynamicTree.prototype.FreeNode=function(node){node.parent=this.m_freeList;this.m_freeList=node};b2DynamicTree.prototype.InsertLeaf=function(leaf){++this.m_insertionCount;if(this.m_root==null){this.m_root=leaf;this.m_root.parent=null;return}var center=leaf.aabb.GetCenter();var sibling=this.m_root;if(sibling.IsLeaf()===false){do{var child1=sibling.child1;var child2=sibling.child2;var norm1=Math.abs((child1.aabb.lowerBound.x+child1.aabb.upperBound.x)/2-center.x)+Math.abs((child1.aabb.lowerBound.y+child1.aabb.upperBound.y)/2-center.y);var norm2=Math.abs((child2.aabb.lowerBound.x+child2.aabb.upperBound.x)/2-center.x)+Math.abs((child2.aabb.lowerBound.y+child2.aabb.upperBound.y)/2-center.y);if(norm1k_slop){var bX=s.x-this.p1.x;var bY=s.y-this.p1.y;var a=bX*nX+bY*nY;if(a>=0&&a<=maxLambda*denom){var mu2=-rX*bY+rY*bX;if(-k_slop*denom<=mu2&&mu2<=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};b2Segment.prototype.Extend=function(aabb){this.ExtendForward(aabb);this.ExtendBackward(aabb)};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>0?(aabb.upperBound.x-this.p1.x)/dX:dX<0?(aabb.lowerBound.x-this.p1.x)/dX:Number.POSITIVE_INFINITY,dY>0?(aabb.upperBound.y-this.p1.y)/dY:dY<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};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>0?(aabb.upperBound.x-this.p2.x)/dX:dX<0?(aabb.lowerBound.x-this.p2.x)/dX:Number.POSITIVE_INFINITY,dY>0?(aabb.upperBound.y-this.p2.y)/dY:dY<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};b2SeparationFunction.b2SeparationFunction=function(){this.m_localPoint=new b2Vec2;this.m_axis=new b2Vec2};b2SeparationFunction.prototype.Initialize=function(cache,proxyA,transformA,proxyB,transformB){this.m_proxyA=proxyA;this.m_proxyB=proxyB;var count=cache.count;if(count===1){this.m_type=b2SeparationFunction.e_points;var localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);var localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);var tVec=localPointA;var tMat=transformA.R;var pointAX=transformA.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var pointAY=transformA.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tVec=localPointB;tMat=transformB.R;var pointBX=transformB.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var 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=b2SeparationFunction.e_faceA;var localPointA1=this.m_proxyA.GetVertex(cache.indexA[0]);var localPointA2=this.m_proxyA.GetVertex(cache.indexA[1]);var localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);this.m_localPoint.x=0.5*(localPointA1.x+localPointA2.x);this.m_localPoint.y=0.5*(localPointA1.y+localPointA2.y);this.m_axis.x=localPointA2.y-localPointA1.y;this.m_axis.y=-1*(localPointA2.x-localPointA1.x);this.m_axis.Normalize();var tVec=this.m_axis;var tMat=transformA.R;var normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tVec=this.m_localPoint;tMat=transformA.R;var pointAX=transformA.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var pointAY=transformA.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tVec=localPointB;tMat=transformB.R;var pointBX=transformB.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var pointBY=transformB.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);var s=(pointBX-pointAX)*normalX+(pointBY-pointAY)*normalY;if(s<0){this.m_axis.NegativeSelf()}}else if(cache.indexA[0]===cache.indexA[0]){this.m_type=b2SeparationFunction.e_faceB;var localPointB1=this.m_proxyB.GetVertex(cache.indexB[0]);var localPointB2=this.m_proxyB.GetVertex(cache.indexB[1]);var localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);this.m_localPoint.x=0.5*(localPointB1.x+localPointB2.x);this.m_localPoint.y=0.5*(localPointB1.y+localPointB2.y);this.m_axis.x=localPointB2.y-localPointB1.y;this.m_axis.y=-1*(localPointB2.x-localPointB1.x);this.m_axis.Normalize();var tVec=this.m_axis;var tMat=transformB.R;var normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tVec=this.m_localPoint;tMat=transformB.R;var pointBX=transformB.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var pointBY=transformB.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tVec=localPointA;tMat=transformA.R;var pointAX=transformA.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);var pointAY=transformA.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);var s=(pointAX-pointBX)*normalX+(pointAY-pointBY)*normalY;if(s<0){this.m_axis.NegativeSelf()}}else{var localPointA1=this.m_proxyA.GetVertex(cache.indexA[0]);var localPointA2=this.m_proxyA.GetVertex(cache.indexA[1]);var localPointB1=this.m_proxyB.GetVertex(cache.indexB[0]);var localPointB2=this.m_proxyB.GetVertex(cache.indexB[1]);var subA=b2Math.SubtractVV(localPointA2,localPointA1);var subB=b2Math.SubtractVV(localPointB2,localPointB1);var dA=b2Math.MulMV(transformA.R,subA);var dB=b2Math.MulMV(transformB.R,subB);var a=dA.x*dA.x+dA.y*dA.y;var e=dB.x*dB.x+dB.y*dB.y;var r=b2Math.SubtractVV(dB,dA);var c=dA.x*r.x+dA.y*r.y;var f=dB.x*r.x+dB.y*r.y;var b=dA.x*dB.x+dA.y*dB.y;var denom=a*e-b*b;var s=0;if(denom!==0){s=b2Math.Clamp((b*f-c*e)/denom,0,1)}var t=(b*s+f)/e;if(t<0){t=0;s=b2Math.Clamp((b-c)/a,0,1)}var localPointA=new b2Vec2;localPointA.x=localPointA1.x+s*(localPointA2.x-localPointA1.x);localPointA.y=localPointA1.y+s*(localPointA2.y-localPointA1.y);var localPointB=new b2Vec2;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=b2SeparationFunction.e_faceB;this.m_axis.x=localPointB2.y-localPointB1.y;this.m_axis.y=-1*(localPointB2.x-localPointB1.x);this.m_axis.Normalize();this.m_localPoint=localPointB;if(s<0){this.m_axis.NegativeSelf()}}else{this.m_type=b2SeparationFunction.e_faceA;this.m_axis.x=localPointA2.y-localPointA1.y;this.m_axis.y=-1*(localPointA2.x-localPointA1.x);this.m_localPoint=localPointA;if(s<0){this.m_axis.NegativeSelf()}}}};b2SeparationFunction.prototype.Evaluate=function(transformA,transformB){var axisA;var axisB;var localPointA;var localPointB;var pointA;var pointB;var normal;switch(this.m_type){case b2SeparationFunction.e_points:axisA=b2Math.MulTMV(transformA.R,this.m_axis);var neg=this.m_axis.GetNegative();if(axisB!==undefined){axisB.x=b2Math.Dot(neg,transformB.R.col1);axisB.y=b2Math.Dot(neg,transformB.R.col2)}else{axisB=b2Math.MulTMV(transformB.R,neg)}localPointA=this.m_proxyA.GetSupportVertex(axisA);localPointB=this.m_proxyB.GetSupportVertex(axisB);pointA=b2Math.MulX(transformA,localPointA);pointB=b2Math.MulX(transformB,localPointB);var result=(pointB.x-pointA.x)*this.m_axis.x+(pointB.y-pointA.y)*this.m_axis.y;return result;case b2SeparationFunction.e_faceA:normal=b2Math.MulMV(transformA.R,this.m_axis);pointA=b2Math.MulX(transformA,this.m_localPoint);var neg=normal.GetNegative();if(axisB!==undefined){axisB.x=b2Math.Dot(neg,transformB.R.col1);axisB.y=b2Math.Dot(neg,transformB.R.col2)}else{axisB=b2Math.MulTMV(transformB.R,neg)}localPointB=this.m_proxyB.GetSupportVertex(axisB);pointB=b2Math.MulX(transformB,localPointB);var result=(pointB.x-pointA.x)*normal.x+(pointB.y-pointA.y)*normal.y;return result;case b2SeparationFunction.e_faceB:normal=b2Math.MulMV(transformB.R,this.m_axis);pointB=b2Math.MulX(transformB,this.m_localPoint);var neg=normal.GetNegative();if(axisA!==undefined){axisA.x=b2Math.Dot(neg,transformA.R.col1);axisA.y=b2Math.Dot(neg,transformA.R.col2)}else{axisA=b2Math.MulTMV(transformA.R,neg)}localPointA=this.m_proxyA.GetSupportVertex(axisA);pointA=b2Math.MulX(transformA,localPointA);var result=(pointA.x-pointB.x)*normal.x+(pointA.y-pointB.y)*normal.y;return result;default:return 0;}};$i_109.postDefs.push(function(){$i_109.Collision.b2SeparationFunction.e_points=1;$i_109.Collision.b2SeparationFunction.e_faceA=2;$i_109.Collision.b2SeparationFunction.e_faceB=4});b2Simplex.b2Simplex=function(){this.m_v1=new b2SimplexVertex;this.m_v2=new b2SimplexVertex;this.m_v3=new b2SimplexVertex;this.m_vertices=[0,0,0]};b2Simplex.prototype.b2Simplex=function(){this.m_vertices[0]=this.m_v1;this.m_vertices[1]=this.m_v2;this.m_vertices[2]=this.m_v3};b2Simplex.prototype.ReadCache=function(cache,proxyA,transformA,proxyB,transformB){this.m_count=cache.count;var vertices=this.m_vertices;var i=this.m_count;while(i>0){var v=vertices[--i];v.indexA=cache.indexA[i];v.indexB=cache.indexB[i];var vertA=proxyA.GetVertex(v.indexA);var vertB=proxyB.GetVertex(v.indexB);v.wA.x=transformA.R.col1.x*vertA.x+transformA.R.col2.x*vertA.y+transformA.position.x;v.wA.y=transformA.R.col1.y*vertA.x+transformA.R.col2.y*vertA.y+transformA.position.y;v.wB.x=transformB.R.col1.x*vertB.x+transformB.R.col2.x*vertB.y+transformB.position.x;v.wB.y=transformB.R.col1.y*vertB.x+transformB.R.col2.y*vertB.y+transformB.position.y;v.w.x=v.wB.x-v.wA.x;v.w.y=v.wB.y-v.wA.y;v.a=0}if(this.m_count>1){var metric1=cache.metric;var metric2=this.GetMetric();if(metric2<0.5*metric1||2*metric10){var cross=b2Math.CrossFV(1,e12);return cross}else{var cross=b2Math.CrossVF(e12,1);return cross}}default:return new b2Vec2;}};b2Simplex.prototype.GetClosestPoint=function(){switch(this.m_count){case 1:return this.m_v1.w;case 2:return new b2Vec2(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);default:return new b2Vec2;}};b2Simplex.prototype.GetWitnessPoints=function(pA,pB){switch(this.m_count){case 1:pA.SetV(this.m_v1.wA);pB.SetV(this.m_v1.wB);break;case 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;break;case 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;break;default:break;}};b2Simplex.prototype.GetMetric=function(){switch(this.m_count){case 1:return 0;case 2:var sub=b2Math.SubtractVV(this.m_v1.w,this.m_v2.w);var len=sub.Length();return len;case 3:var sub1=b2Math.SubtractVV(this.m_v2.w,this.m_v1.w);var sub2=b2Math.SubtractVV(this.m_v3.w,this.m_v1.w);var cross=b2Math.CrossVV(sub1,sub2);return cross;default:break;}};b2Simplex.prototype.Solve2=function(){var w1=this.m_v1.w;var w2=this.m_v2.w;var e12=b2Math.SubtractVV(w2,w1);var d12_2=-(w1.x*e12.x+w1.y*e12.y);if(d12_2<=0){this.m_v1.a=1;this.m_count=1;return}var d12_1=w2.x*e12.x+w2.y*e12.y;if(d12_1<=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};b2Simplex.prototype.Solve3=function(){var w1=this.m_v1.w;var w2=this.m_v2.w;var w3=this.m_v3.w;var e12=b2Math.SubtractVV(w2,w1);var w1e12=b2Math.Dot(w1,e12);var w2e12=b2Math.Dot(w2,e12);var d12_1=w2e12;var d12_2=-w1e12;var e13=b2Math.SubtractVV(w3,w1);var w1e13=b2Math.Dot(w1,e13);var w3e13=b2Math.Dot(w3,e13);var d13_1=w3e13;var d13_2=-w1e13;var e23=b2Math.SubtractVV(w3,w2);var w2e23=b2Math.Dot(w2,e23);var w3e23=b2Math.Dot(w3,e23);var d23_1=w3e23;var d23_2=-w2e23;var n123=b2Math.CrossVV(e12,e13);var d123_1=n123*b2Math.CrossVV(w2,w3);var d123_2=n123*b2Math.CrossVV(w3,w1);var d123_3=n123*b2Math.CrossVV(w1,w2);if(d12_2<=0&&d13_2<=0){this.m_v1.a=1;this.m_count=1;return}if(d12_1>0&&d12_2>0&&d123_3<=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>0&&d13_2>0&&d123_2<=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<=0&&d23_2<=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Set(this.m_v2);return}if(d13_1<=0&&d23_1<=0){this.m_v3.a=1;this.m_count=1;this.m_v1.Set(this.m_v3);return}if(d23_1>0&&d23_2>0&&d123_1<=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};b2SimplexCache.b2SimplexCache=function(){this.indexA=[0,0,0];this.indexB=[0,0,0]};b2SimplexVertex.b2SimplexVertex=function(){};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};b2TimeOfImpact.b2TimeOfImpact=function(){};b2TimeOfImpact.TimeOfImpact=function(input){++b2TimeOfImpact.b2_toiCalls;var proxyA=input.proxyA;var proxyB=input.proxyB;var sweepA=input.sweepA;var sweepB=input.sweepB;var radius=proxyA.m_radius+proxyB.m_radius;var tolerance=input.tolerance;var alpha=0;var iter=0;var target=0;b2TimeOfImpact.s_cache.count=0;b2TimeOfImpact.s_distanceInput.useRadii=false;for(;;){sweepA.GetTransform(b2TimeOfImpact.s_xfA,alpha);sweepB.GetTransform(b2TimeOfImpact.s_xfB,alpha);b2TimeOfImpact.s_distanceInput.proxyA=proxyA;b2TimeOfImpact.s_distanceInput.proxyB=proxyB;b2TimeOfImpact.s_distanceInput.transformA=b2TimeOfImpact.s_xfA;b2TimeOfImpact.s_distanceInput.transformB=b2TimeOfImpact.s_xfB;b2Distance.Distance(b2TimeOfImpact.s_distanceOutput,b2TimeOfImpact.s_cache,b2TimeOfImpact.s_distanceInput);if(b2TimeOfImpact.s_distanceOutput.distance<=0){alpha=1;break}b2TimeOfImpact.s_fcn.Initialize(b2TimeOfImpact.s_cache,proxyA,b2TimeOfImpact.s_xfA,proxyB,b2TimeOfImpact.s_xfB);var separation=b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA,b2TimeOfImpact.s_xfB);if(separation<=0){alpha=1;break}if(iter===0){if(separation>radius){target=b2Math.Max(radius-tolerance,0.75*radius)}else{target=b2Math.Max(separation-tolerance,0.02*radius)}}if(separation-target<0.5*tolerance){if(iter===0)alpha=1;break}var newAlpha=alpha;var x1=alpha;var x2=1;var f1=separation;sweepA.GetTransform(b2TimeOfImpact.s_xfA,x2);sweepB.GetTransform(b2TimeOfImpact.s_xfB,x2);var f2=b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA,b2TimeOfImpact.s_xfB);if(f2>=target){alpha=1;break}var rootIterCount=0;var x=0;for(;;){if(rootIterCount&1){x=x1+(target-f1)*(x2-x1)/(f2-f1)}else{x=0.5*(x1+x2)}sweepA.GetTransform(b2TimeOfImpact.s_xfA,x);sweepB.GetTransform(b2TimeOfImpact.s_xfB,x);var f=b2TimeOfImpact.s_fcn.Evaluate(b2TimeOfImpact.s_xfA,b2TimeOfImpact.s_xfB);if(b2Math.Abs(f-target)<0.025*tolerance){newAlpha=x;break}if(f>target){x1=x;f1=f}else{x2=x;f2=f}++b2TimeOfImpact.b2_toiRootIters;if(++rootIterCount===50)break}b2TimeOfImpact.b2_toiMaxRootIters=b2Math.Max(b2TimeOfImpact.b2_toiMaxRootIters,rootIterCount);if(newAlpha<(1+100*Number.MIN_VALUE)*alpha)break;alpha=newAlpha;iter++;++b2TimeOfImpact.b2_toiIters;if(iter===1000)break}b2TimeOfImpact.b2_toiMaxIters=b2Math.Max(b2TimeOfImpact.b2_toiMaxIters,iter);return alpha};$i_109.postDefs.push(function(){$i_109.Collision.b2TimeOfImpact.b2_toiCalls=0;$i_109.Collision.b2TimeOfImpact.b2_toiIters=0;$i_109.Collision.b2TimeOfImpact.b2_toiMaxIters=0;$i_109.Collision.b2TimeOfImpact.b2_toiRootIters=0;$i_109.Collision.b2TimeOfImpact.b2_toiMaxRootIters=0;$i_109.Collision.b2TimeOfImpact.s_cache=new b2SimplexCache;$i_109.Collision.b2TimeOfImpact.s_distanceInput=new b2DistanceInput;$i_109.Collision.b2TimeOfImpact.s_xfA=new b2Transform(new b2Vec2());$i_109.Collision.b2TimeOfImpact.s_xfB=new b2Transform(new b2Vec2());$i_109.Collision.b2TimeOfImpact.s_fcn=new b2SeparationFunction;$i_109.Collision.b2TimeOfImpact.s_distanceOutput=new b2DistanceOutput});b2TOIInput.b2TOIInput=function(){this.proxyA=new b2DistanceProxy;this.proxyB=new b2DistanceProxy;this.sweepA=new b2Sweep;this.sweepB=new b2Sweep};b2WorldManifold.b2WorldManifold=function(){this.m_normal=new b2Vec2};b2WorldManifold.Free=function(manifold){var i=manifold.m_points.length};b2WorldManifold.prototype.b2WorldManifold=function(){this.m_points=[new b2Vec2,new b2Vec2]};b2WorldManifold.prototype.Initialize=function(manifold,xfA,radiusA,xfB,radiusB){var points=this.m_points;switch(manifold.m_type){case b2Manifold.e_circles:{var tMat=xfA.R;var 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>Number.MIN_VALUE*Number.MIN_VALUE){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=0.5*(cAX+cBX);this.m_points[0].y=0.5*(cAY+cBY)}break;case b2Manifold.e_faceA:{var tMat=xfA.R;var tVec=manifold.m_localPlaneNormal;var normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=xfA.R;tVec=manifold.m_localPoint;var planePointX=xfA.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var planePointY=xfA.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;this.m_normal.x=normalX;this.m_normal.y=normalY;var i=manifold.m_pointCount;while(i>0){tMat=xfB.R;tVec=manifold.m_points[--i].m_localPoint;var clipPointX=xfB.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var clipPointY=xfB.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;this.m_points[i].x=clipPointX+0.5*(radiusA-(clipPointX-planePointX)*normalX-(clipPointY-planePointY)*normalY-radiusB)*normalX;this.m_points[i].y=clipPointY+0.5*(radiusA-(clipPointX-planePointX)*normalX-(clipPointY-planePointY)*normalY-radiusB)*normalY}}break;case b2Manifold.e_faceB:{var tMat=xfB.R;var tVec=manifold.m_localPlaneNormal;var normalX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var normalY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=xfB.R;tVec=manifold.m_localPoint;var planePointX=xfB.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var planePointY=xfB.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;this.m_normal.x=-normalX;this.m_normal.y=-normalY;var i=manifold.m_pointCount;while(i>0){tMat=xfA.R;tVec=manifold.m_points[--i].m_localPoint;var clipPointX=xfA.position.x+tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var clipPointY=xfA.position.y+tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;this.m_points[i].x=clipPointX+0.5*(radiusB-(clipPointX-planePointX)*normalX-(clipPointY-planePointY)*normalY-radiusA)*normalX;this.m_points[i].y=clipPointY+0.5*(radiusB-(clipPointX-planePointX)*normalX-(clipPointY-planePointY)*normalY-radiusA)*normalY}}break;}};ClipVertex.ClipVertex=function(){this.v=new b2Vec2;this.id=new b2ContactID};ClipVertex.prototype.Set=function(other){this.v.SetV(other.v);this.id.Set(other.id)};Features.Features=function(){};Object.defineProperty(Features.prototype,"referenceEdge",{enumerable:false,configurable:true,get:function(){return this._referenceEdge}});Object.defineProperty(Features.prototype,"referenceEdge",{enumerable:false,configurable:true,set:function(value){this._referenceEdge=value;this._m_id._key=this._m_id._key&4294967040|this._referenceEdge&255}});Object.defineProperty(Features.prototype,"incidentEdge",{enumerable:false,configurable:true,get:function(){return this._incidentEdge}});Object.defineProperty(Features.prototype,"incidentEdge",{enumerable:false,configurable:true,set:function(value){this._incidentEdge=value;this._m_id._key=this._m_id._key&4294902015|this._incidentEdge<<8&65280}});Object.defineProperty(Features.prototype,"incidentVertex",{enumerable:false,configurable:true,get:function(){return this._incidentVertex}});Object.defineProperty(Features.prototype,"incidentVertex",{enumerable:false,configurable:true,set:function(value){this._incidentVertex=value;this._m_id._key=this._m_id._key&4278255615|this._incidentVertex<<16&16711680}});Object.defineProperty(Features.prototype,"flip",{enumerable:false,configurable:true,get:function(){return this._flip}});Object.defineProperty(Features.prototype,"flip",{enumerable:false,configurable:true,set:function(value){this._flip=value;this._m_id._key=this._m_id._key&16777215|this._flip<<24&4278190080}})})();(function(){var b2Color=$i_109.Common.b2Color;var b2internal=$i_109.Common.b2internal;var b2Settings=$i_109.Common.b2Settings;var b2CircleShape=$i_109.Collision.Shapes.b2CircleShape;var b2EdgeChainDef=$i_109.Collision.Shapes.b2EdgeChainDef;var b2EdgeShape=$i_109.Collision.Shapes.b2EdgeShape;var b2MassData=$i_109.Collision.Shapes.b2MassData;var b2PolygonShape=$i_109.Collision.Shapes.b2PolygonShape;var b2Shape=$i_109.Collision.Shapes.b2Shape;var b2Mat22=$i_109.Common.Math.b2Mat22;var b2Mat33=$i_109.Common.Math.b2Mat33;var b2Math=$i_109.Common.Math.b2Math;var b2Sweep=$i_109.Common.Math.b2Sweep;var b2Transform=$i_109.Common.Math.b2Transform;var b2Vec2=$i_109.Common.Math.b2Vec2;var b2Vec3=$i_109.Common.Math.b2Vec3;var b2Body=$i_109.Dynamics.b2Body;var b2BodyDef=$i_109.Dynamics.b2BodyDef;var b2ContactFilter=$i_109.Dynamics.b2ContactFilter;var b2ContactImpulse=$i_109.Dynamics.b2ContactImpulse;var b2ContactListener=$i_109.Dynamics.b2ContactListener;var b2ContactManager=$i_109.Dynamics.b2ContactManager;var b2DebugDraw=$i_109.Dynamics.b2DebugDraw;var b2DestructionListener=$i_109.Dynamics.b2DestructionListener;var b2FilterData=$i_109.Dynamics.b2FilterData;var b2Fixture=$i_109.Dynamics.b2Fixture;var b2FixtureDef=$i_109.Dynamics.b2FixtureDef;var b2Island=$i_109.Dynamics.b2Island;var b2TimeStep=$i_109.Dynamics.b2TimeStep;var b2World=$i_109.Dynamics.b2World;var b2AABB=$i_109.Collision.b2AABB;var b2Bound=$i_109.Collision.b2Bound;var b2BoundValues=$i_109.Collision.b2BoundValues;var b2Collision=$i_109.Collision.b2Collision;var b2ContactID=$i_109.Collision.b2ContactID;var b2ContactPoint=$i_109.Collision.b2ContactPoint;var b2Distance=$i_109.Collision.b2Distance;var b2DistanceInput=$i_109.Collision.b2DistanceInput;var b2DistanceOutput=$i_109.Collision.b2DistanceOutput;var b2DistanceProxy=$i_109.Collision.b2DistanceProxy;var b2DynamicTree=$i_109.Collision.b2DynamicTree;var b2DynamicTreeBroadPhase=$i_109.Collision.b2DynamicTreeBroadPhase;var b2DynamicTreeNode=$i_109.Collision.b2DynamicTreeNode;var b2DynamicTreePair=$i_109.Collision.b2DynamicTreePair;var b2Manifold=$i_109.Collision.b2Manifold;var b2ManifoldPoint=$i_109.Collision.b2ManifoldPoint;var b2Point=$i_109.Collision.b2Point;var b2RayCastInput=$i_109.Collision.b2RayCastInput;var b2RayCastOutput=$i_109.Collision.b2RayCastOutput;var b2Segment=$i_109.Collision.b2Segment;var b2SeparationFunction=$i_109.Collision.b2SeparationFunction;var b2Simplex=$i_109.Collision.b2Simplex;var b2SimplexCache=$i_109.Collision.b2SimplexCache;var b2SimplexVertex=$i_109.Collision.b2SimplexVertex;var b2TimeOfImpact=$i_109.Collision.b2TimeOfImpact;var b2TOIInput=$i_109.Collision.b2TOIInput;var b2WorldManifold=$i_109.Collision.b2WorldManifold;var ClipVertex=$i_109.Collision.ClipVertex;var Features=$i_109.Collision.Features;var IBroadPhase=$i_109.Collision.IBroadPhase;$i_109.inherit(b2CircleShape,$i_109.Collision.Shapes.b2Shape);b2CircleShape.prototype.__super=$i_109.Collision.Shapes.b2Shape.prototype;b2CircleShape.prototype.Copy=function(){var s=new b2CircleShape;s.Set(this);return s};b2CircleShape.prototype.Set=function(other){this.__super.Set.call(this,other);if($i_109.is(other,b2CircleShape)){var other2=other instanceof b2CircleShape?other:null;this.m_p.SetV(other2.m_p)}};b2CircleShape.prototype.TestPoint=function(transform,p){var tMat=transform.R;var dX=transform.position.x+(tMat.col1.x*this.m_p.x+tMat.col2.x*this.m_p.y);var dY=transform.position.y+(tMat.col1.y*this.m_p.x+tMat.col2.y*this.m_p.y);dX=p.x-dX;dY=p.y-dY;return dX*dX+dY*dY<=this.m_radius*this.m_radius};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_radius*this.m_radius;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<0||rr=0&&a<=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};b2CircleShape.prototype.ComputeAABB=function(aabb,transform){var tMat=transform.R;var pX=transform.position.x+(tMat.col1.x*this.m_p.x+tMat.col2.x*this.m_p.y);var pY=transform.position.y+(tMat.col1.y*this.m_p.x+tMat.col2.y*this.m_p.y);aabb.lowerBound.Set(pX-this.m_radius,pY-this.m_radius);aabb.upperBound.Set(pX+this.m_radius,pY+this.m_radius)};b2CircleShape.prototype.ComputeMass=function(massData,density){massData.mass=density*b2Settings.b2_pi*this.m_radius*this.m_radius;massData.center.SetV(this.m_p);massData.I=massData.mass*(0.5*this.m_radius*this.m_radius+(this.m_p.x*this.m_p.x+this.m_p.y*this.m_p.y))};b2CircleShape.prototype.ComputeSubmergedArea=function(normal,offset,xf,c){var p=b2Math.MulX(xf,this.m_p);var l=-(b2Math.Dot(normal,p)-offset);if(l<-this.m_radius+Number.MIN_VALUE){return 0}if(l>this.m_radius){c.SetV(p);return Math.PI*this.m_radius*this.m_radius}var r2=this.m_radius*this.m_radius;var l2=l*l;var area=r2*(Math.asin(l/this.m_radius)+Math.PI/2)+l*Math.sqrt(r2-l2);var com=-2/3*Math.pow(r2-l2,1.5)/area;c.x=p.x+normal.x*com;c.y=p.y+normal.y*com;return area};b2CircleShape.prototype.GetLocalPosition=function(){return this.m_p};b2CircleShape.prototype.SetLocalPosition=function(position){this.m_p.SetV(position)};b2CircleShape.prototype.GetRadius=function(){return this.m_radius};b2CircleShape.prototype.SetRadius=function(radius){this.m_radius=radius};b2CircleShape.prototype.b2CircleShape=function(radius){if(radius===undefined)radius=0;this.__super.b2Shape.call(this);this.m_type=b2Shape.e_circleShape;this.m_radius=radius};b2EdgeChainDef.b2EdgeChainDef=function(){};b2EdgeChainDef.prototype.b2EdgeChainDef=function(){this.vertexCount=0;this.isALoop=true;this.vertices=[]};$i_109.inherit(b2EdgeShape,$i_109.Collision.Shapes.b2Shape);b2EdgeShape.prototype.__super=$i_109.Collision.Shapes.b2Shape.prototype;b2EdgeShape.b2EdgeShape=function(){$i_109.Collision.Shapes.b2Shape.b2Shape.apply(this,arguments);this.s_supportVec=new b2Vec2;this.m_v1=new b2Vec2;this.m_v2=new b2Vec2;this.m_coreV1=new b2Vec2;this.m_coreV2=new b2Vec2;this.m_normal=new b2Vec2;this.m_direction=new b2Vec2;this.m_cornerDir1=new b2Vec2;this.m_cornerDir2=new b2Vec2};b2EdgeShape.prototype.TestPoint=function(transform,p){return false};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>k_slop){var bX=input.p1.x-v1X;var bY=input.p1.y-v1Y;var a=bX*nX+bY*nY;if(a>=0&&a<=input.maxFraction*denom){var mu2=-rX*bY+rY*bX;if(-k_slop*denom<=mu2&&mu2<=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};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(v1X0){if(d2>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>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}else{}}c.x=(v0.x+v1.x+v2.x)/3;c.y=(v0.y+v1.y+v2.y)/3;var area=0.5*((v1.x-v0.x)*(v2.y-v0.y)-(v1.y-v0.y)*(v2.x-v0.x));return area};b2EdgeShape.prototype.GetLength=function(){return this.m_length};b2EdgeShape.prototype.GetVertex1=function(){return this.m_v1};b2EdgeShape.prototype.GetVertex2=function(){return this.m_v2};b2EdgeShape.prototype.GetCoreVertex1=function(){return this.m_coreV1};b2EdgeShape.prototype.GetCoreVertex2=function(){return this.m_coreV2};b2EdgeShape.prototype.GetNormalVector=function(){return this.m_normal};b2EdgeShape.prototype.GetDirectionVector=function(){return this.m_direction};b2EdgeShape.prototype.GetCorner1Vector=function(){return this.m_cornerDir1};b2EdgeShape.prototype.GetCorner2Vector=function(){return this.m_cornerDir2};b2EdgeShape.prototype.Corner1IsConvex=function(){return this.m_cornerConvex1};b2EdgeShape.prototype.Corner2IsConvex=function(){return this.m_cornerConvex2};b2EdgeShape.prototype.GetFirstVertex=function(xf){var tMat=xf.R;return new b2Vec2(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))};b2EdgeShape.prototype.GetNextEdge=function(){return this.m_nextEdge};b2EdgeShape.prototype.GetPrevEdge=function(){return this.m_prevEdge};b2EdgeShape.prototype.Support=function(xf,dX,dY){if(dX===undefined)dX=0;if(dY===undefined)dY=0;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>v2X*dX+v2Y*dY){this.s_supportVec.x=v1X;this.s_supportVec.y=v1Y}else{this.s_supportVec.x=v2X;this.s_supportVec.y=v2Y}return this.s_supportVec};b2EdgeShape.prototype.b2EdgeShape=function(v1,v2){this.__super.b2Shape.call(this);this.m_type=b2Shape.e_edgeShape;this.m_prevEdge=null;this.m_nextEdge=null;this.m_v1=v1;this.m_v2=v2;this.m_direction.Set(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.Set(this.m_direction.y,-this.m_direction.x);this.m_coreV1.Set(-b2Settings.b2_toiSlop*(this.m_normal.x-this.m_direction.x)+this.m_v1.x,-b2Settings.b2_toiSlop*(this.m_normal.y-this.m_direction.y)+this.m_v1.y);this.m_coreV2.Set(-b2Settings.b2_toiSlop*(this.m_normal.x+this.m_direction.x)+this.m_v2.x,-b2Settings.b2_toiSlop*(this.m_normal.y+this.m_direction.y)+this.m_v2.y);this.m_cornerDir1=this.m_normal;this.m_cornerDir2.Set(-this.m_normal.x,-this.m_normal.y)};b2EdgeShape.prototype.SetPrevEdge=function(edge,core,cornerDir,convex){this.m_prevEdge=edge;this.m_coreV1=core;this.m_cornerDir1=cornerDir;this.m_cornerConvex1=convex};b2EdgeShape.prototype.SetNextEdge=function(edge,core,cornerDir,convex){this.m_nextEdge=edge;this.m_coreV2=core;this.m_cornerDir2=cornerDir;this.m_cornerConvex2=convex};$i_109.inherit(b2PolygonShape,$i_109.Collision.Shapes.b2Shape);b2PolygonShape.prototype.__super=$i_109.Collision.Shapes.b2Shape.prototype;b2PolygonShape.prototype.Copy=function(){var s=new b2PolygonShape;s.Set(this);return s};b2PolygonShape.prototype.Set=function(other){this.__super.Set.call(this,other);if($i_109.is(other,b2PolygonShape)){var other2=other instanceof b2PolygonShape?other:null;this.m_centroid.SetV(other2.m_centroid);this.m_vertexCount=other2.m_vertexCount;this.Reserve(this.m_vertexCount);for(var i=0;i0){return false}}return true};b2PolygonShape.prototype.RayCast=function(output,input,transform){var lower=0;var upper=input.maxFraction;var tVec;var tX=input.p1.x-transform.position.x;var tY=input.p1.y-transform.position.y;var 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;i0&&numerator=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};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;ivX?upperX:vX;upperY=upperY>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};b2PolygonShape.prototype.ComputeMass=function(massData,density){if(density===undefined)density=0;if(this.m_vertexCount===2){massData.center.x=0.5*(this.m_vertices[0].x+this.m_vertices[1].x);massData.center.y=0.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;i0){if(isSubmerged){if(!lastSubmerged){intoIndex=i-1;diveCount++}}else{if(lastSubmerged){outoIndex=i-1;diveCount++}}}lastSubmerged=isSubmerged}switch(diveCount){case 0:if(lastSubmerged){var md=new b2MassData;this.ComputeMass(md,1);c.SetV(b2Math.MulX(xf,md.center));return md.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=new b2Vec2(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=new b2Vec2(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=new b2Vec2;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=0.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}center.Multiply(1/area);c.SetV(b2Math.MulX(xf,center));return area};b2PolygonShape.prototype.GetVertexCount=function(){return this.m_vertexCount};b2PolygonShape.prototype.GetVertices=function(){return this.m_vertices};b2PolygonShape.prototype.GetNormals=function(){return this.m_normals};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;ibestValue){bestIndex=i;bestValue=value}}return bestIndex};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;ibestValue){bestIndex=i;bestValue=value}}return this.m_vertices[bestIndex]};b2PolygonShape.prototype.Validate=function(){return false};b2PolygonShape.prototype.b2PolygonShape=function(){this.__super.b2Shape.call(this);this.m_type=b2Shape.e_polygonShape;this.m_centroid=new b2Vec2;this.m_vertices=[];this.m_normals=[]};b2PolygonShape.prototype.Reserve=function(count){for(var i=this.m_vertices.length;iupperX)upperX=rX;if(rY>upperY)upperY=rY}var area=(upperX-lowerX)*(upperY-lowerY);if(area<0.95*minArea){minArea=area;obb.R.col1.x=uxX;obb.R.col1.y=uxY;obb.R.col2.x=uyX;obb.R.col2.y=uyY;var centerX=0.5*(lowerX+upperX);var centerY=0.5*(lowerY+upperY);var tMat=obb.R;obb.center.x=root.x+(tMat.col1.x*centerX+tMat.col2.x*centerY);obb.center.y=root.y+(tMat.col1.y*centerX+tMat.col2.y*centerY);obb.extents.x=0.5*(upperX-lowerX);obb.extents.y=0.5*(upperY-lowerY)}}};$i_109.postDefs.push(function(){$i_109.Collision.Shapes.b2PolygonShape.s_mat=new b2Mat22});b2Shape.b2Shape=function(){};b2Shape.prototype.Copy=function(){return null};b2Shape.prototype.Set=function(other){this.m_radius=other.m_radius};b2Shape.prototype.GetType=function(){return this.m_type};b2Shape.prototype.TestPoint=function(xf,p){return false};b2Shape.prototype.RayCast=function(output,input,transform){return false};b2Shape.prototype.ComputeAABB=function(aabb,xf){};b2Shape.prototype.ComputeMass=function(massData,density){};b2Shape.prototype.ComputeSubmergedArea=function(normal,offset,xf,c){return 0};b2Shape.TestOverlap=function(shape1,transform1,shape2,transform2){var input=new b2DistanceInput;input.proxyA=new b2DistanceProxy;input.proxyA.Set(shape1);input.proxyB=new b2DistanceProxy;input.proxyB.Set(shape2);input.transformA=transform1;input.transformB=transform2;input.useRadii=true;var simplexCache=new b2SimplexCache;simplexCache.count=0;var output=new b2DistanceOutput;b2Distance.Distance(output,simplexCache,input);return output.distance<10*Number.MIN_VALUE};b2Shape.prototype.b2Shape=function(){this.m_type=b2Shape.e_unknownShape;this.m_radius=b2Settings.b2_linearSlop};$i_109.postDefs.push(function(){$i_109.Collision.Shapes.b2Shape.e_unknownShape=-1;$i_109.Collision.Shapes.b2Shape.e_circleShape=0;$i_109.Collision.Shapes.b2Shape.e_polygonShape=1;$i_109.Collision.Shapes.b2Shape.e_edgeShape=2;$i_109.Collision.Shapes.b2Shape.e_shapeTypeCount=3;$i_109.Collision.Shapes.b2Shape.e_hitCollide=1;$i_109.Collision.Shapes.b2Shape.e_missCollide=0;$i_109.Collision.Shapes.b2Shape.e_startsInsideCollide=-1})})();(function(){var b2Color=$i_109.Common.b2Color;var b2Settings=$i_109.Common.b2Settings;var b2Math=$i_109.Common.Math.b2Math;b2Color.b2Color=function(){this._r=0;this._g=0;this._b=0};b2Color.prototype.b2Color=function(rr,gg,bb){this._r=$i_109.parseUInt(255*b2Math.Clamp(rr,0,1));this._g=$i_109.parseUInt(255*b2Math.Clamp(gg,0,1));this._b=$i_109.parseUInt(255*b2Math.Clamp(bb,0,1))};b2Color.prototype.Set=function(rr,gg,bb){this._r=$i_109.parseUInt(255*b2Math.Clamp(rr,0,1));this._g=$i_109.parseUInt(255*b2Math.Clamp(gg,0,1));this._b=$i_109.parseUInt(255*b2Math.Clamp(bb,0,1))};Object.defineProperty(b2Color.prototype,"r",{enumerable:false,configurable:true,set:function(rr){if(rr===undefined)rr=0;this._r=$i_109.parseUInt(255*b2Math.Clamp(rr,0,1))}});Object.defineProperty(b2Color.prototype,"g",{enumerable:false,configurable:true,set:function(gg){if(gg===undefined)gg=0;this._g=$i_109.parseUInt(255*b2Math.Clamp(gg,0,1))}});Object.defineProperty(b2Color.prototype,"b",{enumerable:false,configurable:true,set:function(bb){if(bb===undefined)bb=0;this._b=$i_109.parseUInt(255*b2Math.Clamp(bb,0,1))}});Object.defineProperty(b2Color.prototype,"color",{enumerable:false,configurable:true,get:function(){return this._r<<16|this._g<<8|this._b}});b2Settings.b2Settings=function(){};b2Settings.b2MixFriction=function(friction1,friction2){return Math.sqrt(friction1*friction2)};b2Settings.b2MixRestitution=function(restitution1,restitution2){return restitution1>restitution2?restitution1:restitution2};b2Settings.b2MixRestitutionMin=function(restitution1,restitution2){if(restitution1.minRestitution){return restitution2>1?restitution2:restitution1}return restitution1>1?restitution1:restitution2};$i_109.postDefs.push(function(){$i_109.Common.b2Settings.VERSION="2.1alpha custom";$i_109.Common.b2Settings.USHRT_MAX=65535;$i_109.Common.b2Settings.b2_pi=Math.PI;$i_109.Common.b2Settings.b2_maxManifoldPoints=2;$i_109.Common.b2Settings.b2_aabbExtension=0.1;$i_109.Common.b2Settings.b2_aabbMultiplier=2;$i_109.Common.b2Settings.b2_linearSlop=0.005;$i_109.Common.b2Settings.b2_polygonRadius=2*b2Settings.b2_linearSlop;$i_109.Common.b2Settings.b2_angularSlop=2/180*b2Settings.b2_pi;$i_109.Common.b2Settings.b2_toiSlop=8*b2Settings.b2_linearSlop;$i_109.Common.b2Settings.b2_maxTOIContactsPerIsland=32;$i_109.Common.b2Settings.b2_maxTOIJointsPerIsland=32;$i_109.Common.b2Settings.b2_velocityThreshold=1;$i_109.Common.b2Settings.b2_maxLinearCorrection=0.2;$i_109.Common.b2Settings.b2_maxAngularCorrection=8/180*b2Settings.b2_pi;$i_109.Common.b2Settings.b2_maxTranslation=6;$i_109.Common.b2Settings.b2_maxTranslationSquared=b2Settings.b2_maxTranslation*b2Settings.b2_maxTranslation;$i_109.Common.b2Settings.b2_maxRotation=0.5*b2Settings.b2_pi;$i_109.Common.b2Settings.b2_maxRotationSquared=b2Settings.b2_maxRotation*b2Settings.b2_maxRotation;$i_109.Common.b2Settings.b2_contactBaumgarte=0.2;$i_109.Common.b2Settings.b2_timeToSleep=0.5;$i_109.Common.b2Settings.b2_linearSleepTolerance=0.01;$i_109.Common.b2Settings.b2_angularSleepTolerance=2/180*b2Settings.b2_pi})})();(function(){var b2Mat22=$i_109.Common.Math.b2Mat22;var b2Mat33=$i_109.Common.Math.b2Mat33;var b2Math=$i_109.Common.Math.b2Math;var b2Sweep=$i_109.Common.Math.b2Sweep;var b2Transform=$i_109.Common.Math.b2Transform;var b2Vec2=$i_109.Common.Math.b2Vec2;var b2Vec3=$i_109.Common.Math.b2Vec3;b2Mat22.prototype.b2Mat22=function(){this.SetIdentity()};b2Mat22.FromAngle=function(angle){var mat=new b2Mat22;mat.Set(angle);return mat};b2Mat22.FromVV=function(c1,c2){var mat=new b2Mat22;mat.SetVV(c1,c2);return mat};b2Mat22.prototype.Set=function(angle){var c=Math.cos(angle);var s=Math.sin(angle);this.col1.x=c;this.col2.x=-s;this.col1.y=s;this.col2.y=c};b2Mat22.prototype.SetVV=function(c1,c2){this.col1.SetV(c1);this.col2.SetV(c2)};b2Mat22.prototype.Copy=function(){var mat=new b2Mat22;mat.SetM(this);return mat};b2Mat22.prototype.SetM=function(m){this.col1.SetV(m.col1);this.col2.SetV(m.col2)};b2Mat22.prototype.AddM=function(m){this.col1.x+=m.col1.x;this.col1.y+=m.col1.y;this.col2.x+=m.col2.x;this.col2.y+=m.col2.y};b2Mat22.prototype.SetIdentity=function(){this.col1.x=1;this.col2.x=0;this.col1.y=0;this.col2.y=1};b2Mat22.prototype.SetZero=function(){this.col1.x=0;this.col2.x=0;this.col1.y=0;this.col2.y=0};b2Mat22.prototype.GetAngle=function(){return Math.atan2(this.col1.y,this.col1.x)};b2Mat22.prototype.GetInverse=function(out){var a=this.col1.x;var b=this.col2.x;var c=this.col1.y;var d=this.col2.y;var det=a*d-b*c;if(det!==0){det=1/det}out.col1.x=det*d;out.col2.x=-det*b;out.col1.y=-det*c;out.col2.y=det*a;return out};b2Mat22.prototype.Solve=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};b2Mat22.prototype.Abs=function(){this.col1.Abs();this.col2.Abs()};b2Mat33.b2Mat33=function(){this.col1=new b2Vec3(0,0,0);this.col2=new b2Vec3(0,0,0);this.col3=new b2Vec3(0,0,0)};b2Mat33.prototype.b2Mat33=function(c1,c2,c3){if(!c1&&!c2&&!c3){this.col1.SetZero();this.col2.SetZero();this.col3.SetZero()}else{this.col1.SetV(c1);this.col2.SetV(c2);this.col3.SetV(c3)}};b2Mat33.prototype.SetVVV=function(c1,c2,c3){this.col1.SetV(c1);this.col2.SetV(c2);this.col3.SetV(c3)};b2Mat33.prototype.Copy=function(){return new b2Mat33(this.col1,this.col2,this.col3)};b2Mat33.prototype.SetM=function(m){this.col1.SetV(m.col1);this.col2.SetV(m.col2);this.col3.SetV(m.col3)};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};b2Mat33.prototype.SetIdentity=function(){this.col1.x=1;this.col2.x=0;this.col3.x=0;this.col1.y=0;this.col2.y=1;this.col3.y=0;this.col1.z=0;this.col2.z=0;this.col3.z=1};b2Mat33.prototype.SetZero=function(){this.col1.x=0;this.col2.x=0;this.col3.x=0;this.col1.y=0;this.col2.y=0;this.col3.y=0;this.col1.z=0;this.col2.z=0;this.col3.z=0};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};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};b2Math.b2Math=function(){};b2Math.IsValid=function(x){return isFinite(x)};b2Math.Dot=function(a,b){return a.x*b.x+a.y*b.y};b2Math.CrossVV=function(a,b){return a.x*b.y-a.y*b.x};b2Math.CrossVF=function(a,s){return new b2Vec2(s*a.y,-s*a.x)};b2Math.CrossFV=function(s,a){return new b2Vec2(-s*a.y,s*a.x)};b2Math.MulMV=function(A,v){return new b2Vec2(A.col1.x*v.x+A.col2.x*v.y,A.col1.y*v.x+A.col2.y*v.y)};b2Math.MulTMV=function(A,v){return new b2Vec2(b2Math.Dot(v,A.col1),b2Math.Dot(v,A.col2))};b2Math.MulX=function(T,v){return new b2Vec2(T.R.col1.x*v.x+T.R.col2.x*v.y+T.position.x,T.R.col1.y*v.x+T.R.col2.y*v.y+T.position.y)};b2Math.MulXT=function(T,v){var a=b2Math.SubtractVV(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};b2Math.AddVV=function(a,b){return new b2Vec2(a.x+b.x,a.y+b.y)};b2Math.SubtractVV=function(a,b){return new b2Vec2(a.x-b.x,a.y-b.y)};b2Math.Distance=function(a,b){var cX=a.x-b.x;var cY=a.y-b.y;return Math.sqrt(cX*cX+cY*cY)};b2Math.DistanceSquared=function(a,b){var cX=a.x-b.x;var cY=a.y-b.y;return cX*cX+cY*cY};b2Math.MulFV=function(s,a){var v=new b2Vec2(s*a.x,s*a.y);return v};b2Math.AddMM=function(A,B){var C=b2Mat22.FromVV(b2Math.AddVV(A.col1,B.col1),b2Math.AddVV(A.col2,B.col2));return C};b2Math.MulMM=function(A,B){var C=b2Mat22.FromVV(b2Math.MulMV(A,B.col1),b2Math.MulMV(A,B.col2));return C};b2Math.MulTMM=function(A,B){var c1=new b2Vec2(b2Math.Dot(A.col1,B.col1),b2Math.Dot(A.col2,B.col1));var c2=new b2Vec2(b2Math.Dot(A.col1,B.col2),b2Math.Dot(A.col2,B.col2));var C=b2Mat22.FromVV(c1,c2);return C};b2Math.Abs=function(a){return a>0?a:-a};b2Math.AbsV=function(a){return new b2Vec2(b2Math.Abs(a.x),b2Math.Abs(a.y))};b2Math.AbsM=function(A){return b2Mat22.FromVV(b2Math.AbsV(A.col1),b2Math.AbsV(A.col2))};b2Math.Min=function(a,b){return ab?a:b};b2Math.MaxV=function(a,b){return new b2Vec2(b2Math.Max(a.x,b.x),b2Math.Max(a.y,b.y))};b2Math.Clamp=function(a,low,high){return ahigh?high:a};b2Math.ClampV=function(a,low,high){return b2Math.MaxV(low,b2Math.MinV(a,high))};b2Math.Swap=function(a,b){var tmp=a[0];a[0]=b[0];b[0]=tmp};b2Math.Random=function(){return Math.random()*2-1};b2Math.RandomRange=function(lo,hi){return(hi-lo)*Math.random()+lo};b2Math.NextPowerOfTwo=function(x){x|=x>>1&2147483647;x|=x>>2&1073741823;x|=x>>4&268435455;x|=x>>8&16777215;x|=x>>16&65535;return x+1};b2Math.IsPowerOfTwo=function(x){return x>0&&(x&x-1)===0};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};b2Sweep.prototype.Copy=function(){var copy=new 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};b2Sweep.prototype.GetTransform=function(xf,alpha){xf.position.x=(1-alpha)*this.c0.x+alpha*this.c.x;xf.position.y=(1-alpha)*this.c0.y+alpha*this.c.y;xf.R.Set((1-alpha)*this.a0+alpha*this.a);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};b2Sweep.prototype.Advance=function(t){if(this.t0Number.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}};b2Transform.prototype.Initialize=function(pos,r){this.position.SetV(pos);this.R.SetM(r)};b2Transform.prototype.SetIdentity=function(){this.position.SetZero();this.R.SetIdentity()};b2Transform.prototype.Set=function(x){this.position.SetV(x.position);this.R.SetM(x.R)};b2Transform.prototype.GetAngle=function(){return Math.atan2(this.R.col1.y,this.R.col1.x)};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 new b2Vec2(-this.x,-this.y)};b2Vec2.prototype.NegativeSelf=function(){this.x=-this.x;this.y=-this.y};b2Vec2.Make=function(x_,y_){return new b2Vec2(x_,y_)};b2Vec2.prototype.Copy=function(){return new b2Vec2(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=b2Math.Dot(this,A.col1);this.y=b2Math.Dot(this,A.col2);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=this.xb.x?this.x:b.x;this.y=this.y>b.y?this.y:b.y};b2Vec2.prototype.Abs=function(){if(this.x<0)this.x=-this.x;if(this.y<0)this.y=-this.y};b2Vec2.prototype.Length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)};b2Vec2.prototype.LengthSquared=function(){return this.x*this.x+this.y*this.y};b2Vec2.prototype.Normalize=function(){var length=Math.sqrt(this.x*this.x+this.y*this.y);if(length0;s1.SetNextEdge(s2,core,cornerDir,convex);s2.SetPrevEdge(s1,core,cornerDir,convex);return angle2};b2Body.prototype.CreateFixture=function(def){if(this.m_world.IsLocked()){return null}var fixture=new b2Fixture;fixture.Create(this,this.m_xf,def);if(this.m_flags&b2Body.e_activeFlag){var broadPhase=this.m_world.m_contactManager.m_broadPhase;fixture.CreateProxy(broadPhase,this.m_xf)}fixture.m_next=this.m_fixtureList;this.m_fixtureList=fixture;++this.m_fixtureCount;fixture.m_body=this;if(fixture.m_density>0){this.ResetMassData()}this.m_world.m_flags|=b2World.e_newFixture;return fixture};b2Body.prototype.CreateFixture2=function(shape,density){if(density===undefined)density=0;var def=new b2FixtureDef;def.shape=shape;def.density=density;return this.CreateFixture(def)};b2Body.prototype.DestroyFixture=function(fixture){if(this.m_world.IsLocked()===true){return}var node=this.m_fixtureList;var ppF=null;while(node!==null){if(node===fixture){if(ppF)ppF.m_next=fixture.m_next;else this.m_fixtureList=fixture.m_next;break}ppF=node;node=node.m_next}var edge=this.m_contactList;while(edge){var c=edge.contact;edge=edge.next;var fixtureA=c.m_fixtureA;var fixtureB=c.m_fixtureB;if(fixture===fixtureA||fixture===fixtureB){this.m_world.m_contactManager.Destroy(c)}}if(this.m_flags&b2Body.e_activeFlag){var broadPhase=this.m_world.m_contactManager.m_broadPhase;fixture.DestroyProxy(broadPhase)}else{}fixture.Destroy();fixture.m_body=null;fixture.m_next=null;--this.m_fixtureCount;this.ResetMassData()};b2Body.prototype.SetPositionAndAngle=function(position,angle){var f;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(f=this.m_fixtureList;f;f=f.m_next){f.Synchronize(broadPhase,this.m_xf,this.m_xf)}this.m_world.m_contactManager.FindNewContacts()};b2Body.prototype.SetTransform=function(xf){this.SetPositionAndAngle(xf.position,xf.GetAngle())};b2Body.prototype.GetTransform=function(){return this.m_xf};b2Body.prototype.GetPosition=function(){return this.m_xf.position};b2Body.prototype.SetPosition=function(position){this.SetPositionAndAngle(position,this.GetAngle())};b2Body.prototype.GetAngle=function(){return this.m_sweep.a};b2Body.prototype.SetAngle=function(angle){this.SetPositionAndAngle(this.GetPosition(),angle)};b2Body.prototype.SetGravityScale=function(scale){this.m_gravityScale=scale};b2Body.prototype.GetGravityScale=function(){return this.m_gravityScale};b2Body.prototype.GetWorldCenter=function(){return this.m_sweep.c};b2Body.prototype.GetLocalCenter=function(){return this.m_sweep.localCenter};b2Body.prototype.SetLinearVelocity=function(v){if(this.m_type===b2Body.b2_staticBody){return}this.m_linearVelocity.SetV(v)};b2Body.prototype.GetLinearVelocity=function(){return this.m_linearVelocity};b2Body.prototype.SetAngularVelocity=function(omega){if(this.m_type===b2Body.b2_staticBody){return}if(omega===undefined)omega=0;this.m_angularVelocity=omega};b2Body.prototype.GetAngularVelocity=function(){return this.m_angularVelocity};b2Body.prototype.GetDefinition=function(){var bd=new b2BodyDef;bd.type=this.GetType();bd.allowSleep=(this.m_flags&b2Body.e_allowSleepFlag)===b2Body.e_allowSleepFlag;bd.angle=this.GetAngle();bd.angularDamping=this.m_angularDamping;bd.angularVelocity=this.m_angularVelocity;bd.fixedRotation=(this.m_flags&b2Body.e_fixedRotationFlag)===b2Body.e_fixedRotationFlag;bd.bullet=(this.m_flags&b2Body.e_bulletFlag)===b2Body.e_bulletFlag;bd.awake=(this.m_flags&b2Body.e_awakeFlag)===b2Body.e_awakeFlag;bd.linearDamping=this.m_linearDamping;bd.linearVelocity.SetV(this.GetLinearVelocity());bd.position=this.GetPosition();bd.userData=this.GetUserData();return bd};b2Body.prototype.ApplyForce=function(force,point){if(this.m_type!==b2Body.b2_dynamicBody){return}if(!this.m_isAwake){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};b2Body.prototype.ApplyTorque=function(torque){if(this.m_type!==b2Body.b2_dynamicBody){return}if(torque===undefined)torque=0;if(!this.m_isAwake){this.SetAwake(true)}this.m_torque+=torque};b2Body.prototype.ApplyImpulse=function(impulse,point){if(this.m_type!==b2Body.b2_dynamicBody){return}if(!this.m_isAwake){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)};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());var prev;for(var f=body1.m_fixtureList;f;){if(callback(f)){var next=f.m_next;if(prev){prev.m_next=next}else{body1.m_fixtureList=next}body1.m_fixtureCount--;f.m_next=body2.m_fixtureList;body2.m_fixtureList=f;body2.m_fixtureCount++;f.m_body=body2;f=next}else{prev=f;f=f.m_next}}body1.ResetMassData();body2.ResetMassData();var center1=body1.GetWorldCenter();var center2=body2.GetWorldCenter();var cross1=b2Math.CrossFV(angularVelocity,b2Math.SubtractVV(center1,center));var cross2=b2Math.CrossFV(angularVelocity,b2Math.SubtractVV(center2,center));var velocity1=b2Math.AddVV(linearVelocity,cross1);var velocity2=b2Math.AddVV(linearVelocity,cross2);body1.SetLinearVelocity(velocity1);body2.SetLinearVelocity(velocity2);body1.SetAngularVelocity(angularVelocity);body2.SetAngularVelocity(angularVelocity);body1.SynchronizeFixtures();body2.SynchronizeFixtures();return body2};b2Body.prototype.Merge=function(other){var f;for(f=other.m_fixtureList;f;){var next=f.m_next;other.m_fixtureCount--;f.m_next=this.m_fixtureList;this.m_fixtureList=f;this.m_fixtureCount++;f.m_body=body2;f=next}var body1=this;body1.m_fixtureCount=0;var body2=other;body1.ResetMassData();this.SynchronizeFixtures()};b2Body.prototype.GetMass=function(){return this.m_mass};b2Body.prototype.GetInertia=function(){return this.m_I};b2Body.prototype.GetMassData=function(data){data.mass=this.m_mass;data.I=this.m_I;data.center.SetV(this.m_sweep.localCenter)};b2Body.prototype.SetMassData=function(massData){if(this.m_world.IsLocked()===true){return}if(this.m_type!==b2Body.b2_dynamicBody){return}this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_mass=massData.mass;if(this.m_mass<=0){this.m_mass=1}this.m_invMass=1/this.m_mass;if(massData.I>0&&(this.m_flags&b2Body.e_fixedRotationFlag)===0){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(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)};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===b2Body.b2_staticBody||this.m_type===b2Body.b2_kinematicBody){return}var center=b2Vec2.Make(0,0);for(var f=this.m_fixtureList;f;f=f.m_next){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}if(this.m_mass>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>0&&(this.m_flags&b2Body.e_fixedRotationFlag)===0){this.m_I-=this.m_mass*(center.x*center.x+center.y*center.y);this.m_I*=this.m_inertiaScale;this.m_invI=1/this.m_I}else{this.m_I=0;this.m_invI=0}var oldCenter=this.m_sweep.c.Copy();this.m_sweep.localCenter.SetV(center);var mult=b2Math.MulX(this.m_xf,this.m_sweep.localCenter);this.m_sweep.c0.SetV(mult);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)};b2Body.prototype.GetWorldPoint=function(localPoint){var A=this.m_xf.R;var u=new b2Vec2(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};b2Body.prototype.GetWorldVector=function(localVector){return b2Math.MulMV(this.m_xf.R,localVector)};b2Body.prototype.GetLocalPoint=function(worldPoint){return b2Math.MulXT(this.m_xf,worldPoint)};b2Body.prototype.GetLocalVector=function(worldVector){return b2Math.MulTMV(this.m_xf.R,worldVector)};b2Body.prototype.GetLinearVelocityFromWorldPoint=function(worldPoint){return new b2Vec2(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))};b2Body.prototype.GetLinearVelocityFromLocalPoint=function(localPoint){var A=this.m_xf.R;var worldPoint=new b2Vec2(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=new b2Vec2(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));return velocity};b2Body.prototype.GetLinearDamping=function(){return this.m_linearDamping};b2Body.prototype.SetLinearDamping=function(linearDamping){if(linearDamping===undefined)linearDamping=0;this.m_linearDamping=linearDamping};b2Body.prototype.GetAngularDamping=function(){return this.m_angularDamping};b2Body.prototype.SetAngularDamping=function(angularDamping){if(angularDamping===undefined)angularDamping=0;this.m_angularDamping=angularDamping};b2Body.prototype.SetType=function(type){if(type===undefined)type=0;if(this.m_type===type){return}this.m_type=type;this.ResetMassData();if(this.m_type===b2Body.b2_staticBody){this.m_linearVelocity.SetZero();this.m_angularVelocity=0}this.SetAwake(true);this.m_force.SetZero();this.m_torque=0;for(var ce=this.m_contactList;ce;ce=ce.next){ce.contact.FlagForFiltering()}};b2Body.prototype.GetType=function(){return this.m_type};b2Body.prototype.SetBullet=function(flag){if(flag){this.m_flags|=b2Body.e_bulletFlag}else{this.m_flags&=~b2Body.e_bulletFlag}};b2Body.prototype.IsBullet=function(){return(this.m_flags&b2Body.e_bulletFlag)===b2Body.e_bulletFlag};b2Body.prototype.SetSleepingAllowed=function(flag){if(flag){this.m_flags|=b2Body.e_allowSleepFlag}else{this.m_flags&=~b2Body.e_allowSleepFlag;this.SetAwake(true)}};b2Body.prototype.SetAwake=function(flag){this.m_isAwake=flag;if(flag){this.m_sleepTime=0}else{this.m_sleepTime=0;this.m_linearVelocity.SetZero();this.m_angularVelocity=0;this.m_force.SetZero();this.m_torque=0}};b2Body.prototype.IsAwake=function(){return this.m_isAwake};b2Body.prototype.SetFixedRotation=function(fixed){if(fixed){this.m_flags|=b2Body.e_fixedRotationFlag}else{this.m_flags&=~b2Body.e_fixedRotationFlag}this.ResetMassData()};b2Body.prototype.IsFixedRotation=function(){return(this.m_flags&b2Body.e_fixedRotationFlag)===b2Body.e_fixedRotationFlag};b2Body.prototype.SetActive=function(flag){if(flag===this.IsActive()){return}var broadPhase;var f;if(flag){this.m_flags|=b2Body.e_activeFlag;broadPhase=this.m_world.m_contactManager.m_broadPhase;for(f=this.m_fixtureList;f;f=f.m_next){f.CreateProxy(broadPhase,this.m_xf)}}else{this.m_flags&=~b2Body.e_activeFlag;broadPhase=this.m_world.m_contactManager.m_broadPhase;for(f=this.m_fixtureList;f;f=f.m_next){f.DestroyProxy(broadPhase)}var ce=this.m_contactList;while(ce){var ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact)}this.m_contactList=null}};b2Body.prototype.IsActive=function(){return(this.m_flags&b2Body.e_activeFlag)===b2Body.e_activeFlag};b2Body.prototype.IsSleepingAllowed=function(){return(this.m_flags&b2Body.e_allowSleepFlag)===b2Body.e_allowSleepFlag};b2Body.prototype.GetFixtureList=function(){return this.m_fixtureList};b2Body.prototype.GetJointList=function(){return this.m_jointList};b2Body.prototype.GetControllerList=function(){return this.m_controllerList};b2Body.prototype.GetContactList=function(){return this.m_contactList};b2Body.prototype.GetNext=function(){return this.m_next};b2Body.prototype.GetUserData=function(){return this.m_userData};b2Body.prototype.SetUserData=function(data){this.m_userData=data};b2Body.prototype.GetWorld=function(){return this.m_world};b2Body.prototype.b2Body=function(bd,world){this.m_flags=0;if(bd.bullet){this.m_flags|=b2Body.e_bulletFlag}if(bd.fixedRotation){this.m_flags|=b2Body.e_fixedRotationFlag}if(bd.allowSleep){this.m_flags|=b2Body.e_allowSleepFlag}if(bd.awake){this.m_flags|=b2Body.e_awakeFlag}if(bd.active){this.m_flags|=b2Body.e_activeFlag}this.m_isAwake=true;this.m_world=world;this.m_xf.position.SetV(bd.position);this.m_xf.R.Set(bd.angle);this.m_sweep.localCenter.SetZero();this.m_sweep.t0=1;this.m_sweep.a0=this.m_sweep.a=bd.angle;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_jointList=null;this.m_controllerList=null;this.m_contactList=null;this.m_controllerCount=0;this.m_prev=null;this.m_next=null;this.m_linearVelocity.SetV(bd.linearVelocity);this.m_angularVelocity=bd.angularVelocity;this.m_linearDamping=bd.linearDamping;this.m_angularDamping=bd.angularDamping;this.m_force.Set(0,0);this.m_torque=0;this.m_sleepTime=0;this.m_type=bd.type;if(this.m_type===b2Body.b2_dynamicBody){this.m_mass=1;this.m_invMass=1}else{this.m_mass=0;this.m_invMass=0}this.m_I=0;this.m_invI=0;this.m_inertiaScale=bd.inertiaScale;this.m_userData=bd.userData;this.m_fixtureList=null;this.m_fixtureCount=0};b2Body.prototype.SynchronizeFixtures=function(){var xf1=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 f;var broadPhase=this.m_world.m_contactManager.m_broadPhase;for(f=this.m_fixtureList;f;f=f.m_next){f.Synchronize(broadPhase,xf1,this.m_xf)}};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)};b2Body.prototype.ShouldCollide=function(other){if(this.m_type!==b2Body.b2_dynamicBody&&other.m_type!==b2Body.b2_dynamicBody){return false}for(var jn=this.m_jointList;jn;jn=jn.next){if(jn.other===other)if(!jn.joint.m_collideConnected){return false}}return true};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()};$i_109.postDefs.push(function(){$i_109.Dynamics.b2Body.s_xf1=new b2Transform(new b2Vec2());$i_109.Dynamics.b2Body.e_islandFlag=1;$i_109.Dynamics.b2Body.e_awakeFlag=2;$i_109.Dynamics.b2Body.e_allowSleepFlag=4;$i_109.Dynamics.b2Body.e_bulletFlag=8;$i_109.Dynamics.b2Body.e_fixedRotationFlag=16;$i_109.Dynamics.b2Body.e_activeFlag=32;$i_109.Dynamics.b2Body.b2_staticBody=0;$i_109.Dynamics.b2Body.b2_kinematicBody=1;$i_109.Dynamics.b2Body.b2_dynamicBody=2});b2BodyDef.prototype.b2BodyDef=function(){this.userData=null;this.position.Set(0,0);this.angle=0;this.linearVelocity.Set(0,0);this.angularVelocity=0;this.linearDamping=0;this.angularDamping=0;this.allowSleep=true;this.awake=true;this.fixedRotation=false;this.bullet=false;this.type=b2Body.b2_staticBody;this.active=true;this.inertiaScale=1};b2ContactFilter.b2ContactFilter=function(){};b2ContactFilter.prototype.ShouldCollide=function(fixtureA,fixtureB){var filter1=fixtureA.GetFilterData();var filter2=fixtureB.GetFilterData();if(filter1.groupIndex===filter2.groupIndex&&filter1.groupIndex!==0){return filter1.groupIndex>0}var collide=(filter1.maskBits&filter2.categoryBits)!==0&&(filter1.categoryBits&filter2.maskBits)!==0;return collide};b2ContactFilter.prototype.RayCollide=function(userData,fixture){if(!userData)return true;return this.ShouldCollide(userData instanceof b2Fixture?userData:null,fixture)};$i_109.postDefs.push(function(){$i_109.Dynamics.b2ContactFilter.b2_defaultFilter=new b2ContactFilter});b2ContactImpulse.b2ContactImpulse=function(){this.normalImpulses=[0,0];this.tangentImpulses=[0,0]};b2ContactListener.b2ContactListener=function(){};b2ContactListener.prototype.BeginContact=function(contact){};b2ContactListener.prototype.EndContact=function(contact){};b2ContactListener.prototype.PreSolve=function(contact,oldManifold){};b2ContactListener.prototype.PostSolve=function(contact,impulse){};$i_109.postDefs.push(function(){$i_109.Dynamics.b2ContactListener.b2_defaultListener=new b2ContactListener});b2ContactManager.b2ContactManager=function(){};b2ContactManager.prototype.b2ContactManager=function(){this.m_world=null;this.m_contactCount=0;this.m_contactFilter=b2ContactFilter.b2_defaultFilter;this.m_contactListener=b2ContactListener.b2_defaultListener;this.m_contactFactory=new b2ContactFactory(this.m_allocator);this.m_broadPhase=new b2DynamicTreeBroadPhase};b2ContactManager.prototype.AddPair=function(proxyUserDataA,proxyUserDataB){var fixtureA=proxyUserDataA instanceof b2Fixture?proxyUserDataA:null;var fixtureB=proxyUserDataB instanceof b2Fixture?proxyUserDataB:null;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(bodyA===bodyB)return;var edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){var fA=edge.contact.m_fixtureA;var fB=edge.contact.m_fixtureB;if(fA===fixtureA&&fB===fixtureB)return;if(fA===fixtureB&&fB===fixtureA)return}edge=edge.next}if(bodyB.ShouldCollide(bodyA)===false){return}if(this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)===false){return}var c=this.m_contactFactory.Create(fixtureA,fixtureB);fixtureA=c.m_fixtureA;fixtureB=c.m_fixtureB;bodyA=fixtureA.m_body;bodyB=fixtureB.m_body;c.m_prev=null;c.m_next=this.m_world.m_contactList;if(this.m_world.m_contactList!==null){this.m_world.m_contactList.m_prev=c}this.m_world.m_contactList=c;c.m_nodeA.contact=c;c.m_nodeA.other=bodyB;c.m_nodeA.prev=null;c.m_nodeA.next=bodyA.m_contactList;if(bodyA.m_contactList!==null){bodyA.m_contactList.prev=c.m_nodeA}bodyA.m_contactList=c.m_nodeA;c.m_nodeB.contact=c;c.m_nodeB.other=bodyA;c.m_nodeB.prev=null;c.m_nodeB.next=bodyB.m_contactList;if(bodyB.m_contactList!==null){bodyB.m_contactList.prev=c.m_nodeB}bodyB.m_contactList=c.m_nodeB;++this.m_world.m_contactCount};b2ContactManager.prototype.FindNewContacts=function(){this.m_broadPhase.UpdatePairs(this)};b2ContactManager.prototype.Destroy=function(c){var fixtureA=c.m_fixtureA;var fixtureB=c.m_fixtureB;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(c.m_isTouching){this.m_contactListener.EndContact(c)}if(c.m_prev){c.m_prev.m_next=c.m_next}if(c.m_next){c.m_next.m_prev=c.m_prev}if(c===this.m_world.m_contactList){this.m_world.m_contactList=c.m_next}if(c.m_nodeA.prev){c.m_nodeA.prev.next=c.m_nodeA.next}if(c.m_nodeA.next){c.m_nodeA.next.prev=c.m_nodeA.prev}if(c.m_nodeA===bodyA.m_contactList){bodyA.m_contactList=c.m_nodeA.next}if(c.m_nodeB.prev){c.m_nodeB.prev.next=c.m_nodeB.next}if(c.m_nodeB.next){c.m_nodeB.next.prev=c.m_nodeB.prev}if(c.m_nodeB===bodyB.m_contactList){bodyB.m_contactList=c.m_nodeB.next}this.m_contactFactory.Destroy(c);--this.m_contactCount};b2ContactManager.prototype.Collide=function(){var c=this.m_world.m_contactList;while(c!==null){var fixtureA=c.m_fixtureA;var fixtureB=c.m_fixtureB;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(!bodyA.m_isAwake&&!bodyB.m_isAwake){c=c.GetNext();continue}if(c.m_isFiltered){if(!bodyB.ShouldCollide(bodyA)){var cNuke=c;c=cNuke.GetNext();this.Destroy(cNuke);continue}if(!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){cNuke=c;c=cNuke.GetNext();this.Destroy(cNuke);continue}c.m_isFiltered=false}if(!this.m_broadPhase.TestOverlap(fixtureA.m_proxy,fixtureB.m_proxy)){cNuke=c;c=cNuke.GetNext();this.Destroy(cNuke);continue}c.Update(this.m_contactListener);c=c.GetNext()}};b2DebugDraw.b2DebugDraw=function(){};b2DebugDraw.prototype.b2DebugDraw=function(){};b2DebugDraw.prototype.SetFlags=function(flags){if(flags===undefined)flags=0};b2DebugDraw.prototype.GetFlags=function(){};b2DebugDraw.prototype.AppendFlags=function(flags){if(flags===undefined)flags=0};b2DebugDraw.prototype.ClearFlags=function(flags){if(flags===undefined)flags=0};b2DebugDraw.prototype.SetSprite=function(sprite){};b2DebugDraw.prototype.GetSprite=function(){};b2DebugDraw.prototype.SetDrawScale=function(drawScale){if(drawScale===undefined)drawScale=0};b2DebugDraw.prototype.GetDrawScale=function(){};b2DebugDraw.prototype.SetLineThickness=function(lineThickness){if(lineThickness===undefined)lineThickness=0};b2DebugDraw.prototype.GetLineThickness=function(){};b2DebugDraw.prototype.SetAlpha=function(alpha){if(alpha===undefined)alpha=0};b2DebugDraw.prototype.GetAlpha=function(){};b2DebugDraw.prototype.SetFillAlpha=function(alpha){if(alpha===undefined)alpha=0};b2DebugDraw.prototype.GetFillAlpha=function(){};b2DebugDraw.prototype.SetXFormScale=function(xformScale){if(xformScale===undefined)xformScale=0};b2DebugDraw.prototype.GetXFormScale=function(){};b2DebugDraw.prototype.DrawPolygon=function(vertices,vertexCount,color){if(vertexCount===undefined)vertexCount=0};b2DebugDraw.prototype.DrawSolidPolygon=function(vertices,vertexCount,color){if(vertexCount===undefined)vertexCount=0};b2DebugDraw.prototype.DrawCircle=function(center,radius,color){if(radius===undefined)radius=0};b2DebugDraw.prototype.DrawSolidCircle=function(center,radius,axis,color){if(radius===undefined)radius=0};b2DebugDraw.prototype.DrawSegment=function(p1,p2,color){};b2DebugDraw.prototype.DrawTransform=function(xf){};$i_109.postDefs.push(function(){$i_109.Dynamics.b2DebugDraw.e_shapeBit=1;$i_109.Dynamics.b2DebugDraw.e_jointBit=2;$i_109.Dynamics.b2DebugDraw.e_aabbBit=4;$i_109.Dynamics.b2DebugDraw.e_pairBit=8;$i_109.Dynamics.b2DebugDraw.e_centerOfMassBit=16;$i_109.Dynamics.b2DebugDraw.e_controllerBit=32});$i_109.postDefs.push(function(){$i_109.Dynamics.b2ContactManager.s_evalCP=new b2ContactPoint});b2DestructionListener.b2DestructionListener=function(){};b2DestructionListener.prototype.SayGoodbyeJoint=function(joint){};b2DestructionListener.prototype.SayGoodbyeFixture=function(fixture){};b2FilterData.prototype.Copy=function(){var copy=new b2FilterData;copy.categoryBits=this.categoryBits;copy.maskBits=this.maskBits;copy.groupIndex=this.groupIndex;return copy};b2Fixture.b2Fixture=function(){this.m_filter=new b2FilterData};b2Fixture.prototype.GetType=function(){return this.m_shape.GetType()};b2Fixture.prototype.GetShape=function(){return this.m_shape};b2Fixture.prototype.SetSensor=function(sensor){if(this.m_isSensor===sensor)return;this.m_isSensor=sensor;if(this.m_body===null)return;var edge=this.m_body.GetContactList();while(edge){var contact=edge.contact;var fixtureA=contact.m_fixtureA;var fixtureB=contact.m_fixtureB;if(fixtureA===this||fixtureB===this)contact.SetSensor(fixtureA.IsSensor()||fixtureB.IsSensor());edge=edge.next}};b2Fixture.prototype.IsSensor=function(){return this.m_isSensor};b2Fixture.prototype.SetFilterData=function(filter){this.m_filter=filter.Copy();if(this.m_body)return;var edge=this.m_body.GetContactList();while(edge){var contact=edge.contact;var fixtureA=contact.m_fixtureA;var fixtureB=contact.m_fixtureB;if(fixtureA===this||fixtureB===this)contact.FlagForFiltering();edge=edge.next}};b2Fixture.prototype.GetFilterData=function(){return this.m_filter.Copy()};b2Fixture.prototype.GetBody=function(){return this.m_body};b2Fixture.prototype.GetNext=function(){return this.m_next};b2Fixture.prototype.GetUserData=function(){return this.m_userData};b2Fixture.prototype.SetUserData=function(data){this.m_userData=data};b2Fixture.prototype.TestPoint=function(p){return this.m_shape.TestPoint(this.m_body.GetTransform(),p)};b2Fixture.prototype.RayCast=function(output,input){return this.m_shape.RayCast(output,input,this.m_body.GetTransform())};b2Fixture.prototype.GetMassData=function(massData){if(massData===undefined){massData=new b2MassData}this.m_shape.ComputeMass(massData,this.m_density);return massData};b2Fixture.prototype.SetDensity=function(density){this.m_density=density};b2Fixture.prototype.GetDensity=function(){return this.m_density};b2Fixture.prototype.GetFriction=function(){return this.m_friction};b2Fixture.prototype.SetFriction=function(friction){this.m_friction=friction};b2Fixture.prototype.GetRestitution=function(){return this.m_restitution};b2Fixture.prototype.SetRestitution=function(restitution){this.m_restitution=restitution};b2Fixture.prototype.GetAABB=function(){return this.m_aabb};b2Fixture.prototype.b2Fixture=function(){this.m_aabb=new b2AABB;this.m_userData=null;this.m_body=null;this.m_next=null;this.m_shape=null;this.m_density=0;this.m_friction=0;this.m_restitution=0};b2Fixture.prototype.Create=function(body,xf,def){this.m_userData=def.userData;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_body=body;this.m_next=null;this.m_filter=def.filter.Copy();this.m_isSensor=def.isSensor;this.m_shape=def.shape.Copy();this.m_density=def.density};b2Fixture.prototype.Destroy=function(){this.m_shape=null;this.m_aabb.Free()};b2Fixture.prototype.CreateProxy=function(broadPhase,xf){this.m_shape.ComputeAABB(this.m_aabb,xf);this.m_proxy=broadPhase.CreateProxy(this.m_aabb,this)};b2Fixture.prototype.DestroyProxy=function(broadPhase){if(this.m_proxy==null){return}broadPhase.DestroyProxy(this.m_proxy);this.m_proxy=null};b2Fixture.prototype.Synchronize=function(broadPhase,transform1,transform2){if(!this.m_proxy)return;var aabb1=new b2AABB;var aabb2=new b2AABB;this.m_shape.ComputeAABB(aabb1,transform1);this.m_shape.ComputeAABB(aabb2,transform2);this.m_aabb.Combine(aabb1,aabb2);aabb1.Free();aabb2.Free();var displacement=b2Math.SubtractVV(transform2.position,transform1.position);broadPhase.MoveProxy(this.m_proxy,this.m_aabb,displacement)};b2FixtureDef.prototype.b2FixtureDef=function(){this.shape=null;this.userData=null;this.friction=0.2;this.restitution=0;this.density=0;this.filter.categoryBits=1;this.filter.maskBits=65535;this.filter.groupIndex=0;this.isSensor=false};b2Island.b2Island=function(){};b2Island.prototype.b2Island=function(){this.m_bodies=[];this.m_contacts=[];this.m_joints=[]};b2Island.prototype.Initialize=function(bodyCapacity,contactCapacity,jointCapacity,allocator,listener,contactSolver){this.m_bodyCapacity=bodyCapacity;this.m_contactCapacity=contactCapacity;this.m_jointCapacity=jointCapacity;this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;this.m_allocator=allocator;this.m_listener=listener;this.m_contactSolver=contactSolver;var i=0;for(i=this.m_bodies.length;ib2Settings.b2_maxTranslationSquared){b.m_linearVelocity.Normalize();b.m_linearVelocity.x*=b2Settings.b2_maxTranslation*step.inv_dt;b.m_linearVelocity.y*=b2Settings.b2_maxTranslation*step.inv_dt}var rotation=step.dt*b.m_angularVelocity;if(rotation*rotation>b2Settings.b2_maxRotationSquared){b.m_angularVelocity=(b.m_angularVelocity<0?-b2Settings.b2_maxRotation:b2Settings.b2_maxRotation)*step.inv_dt}if(b.m_sweep===null){b.m_sweep=new $i_109.Common.Math.b2Sweep}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()}for(i=0;iangTolSqr||b2Math.Dot(b.m_linearVelocity,b.m_linearVelocity)>linTolSqr){b.m_sleepTime=0;minSleepTime=0}else{b.m_sleepTime+=step.dt;minSleepTime=b2Math.Min(minSleepTime,b.m_sleepTime)}}if(minSleepTime>=b2Settings.b2_timeToSleep){for(i=0;ib2Settings.b2_maxTranslationSquared){b.m_linearVelocity.Normalize();b.m_linearVelocity.x*=b2Settings.b2_maxTranslation*subStep.inv_dt;b.m_linearVelocity.y*=b2Settings.b2_maxTranslation*subStep.inv_dt}var rotation=subStep.dt*b.m_angularVelocity;if(rotation*rotation>b2Settings.b2_maxRotationSquared){if(b.m_angularVelocity<0){b.m_angularVelocity=-b2Settings.b2_maxRotation*subStep.inv_dt}else{b.m_angularVelocity=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()}var k_toiBaumgarte=0.75;for(i=0;icc.pointCount){b2Island.s_impulse.normalImpulses.length=cc.pointCount;b2Island.s_impulse.tangentImpulses.length=cc.pointCount}for(var j=0;j0};b2World.prototype.Solve=function(step){var b;for(var controller=this.m_controllerList;controller;controller=controller.m_next){controller.Step(step)}var island=this.m_island;island.Initialize(this.m_bodyCount,this.m_contactCount,this.m_jointCount,null,this.m_contactManager.m_contactListener,this.m_contactSolver);for(b=this.m_bodyList;b;b=b.m_next){b.m_flags&=~b2Body.e_islandFlag}for(var c=this.m_contactList;c;c=c.m_next){c.m_flags&=~b2Contact.e_islandFlag}for(var j=this.m_jointList;j;j=j.m_next){j.m_islandFlag=false}var i;var stack=this.s_stack;for(var seed=this.m_bodyList;seed;seed=seed.m_next){if(seed.m_flags&b2Body.e_islandFlag){continue}if(!seed.m_isAwake||seed.IsActive()===false){continue}if(seed.GetType()===b2Body.b2_staticBody){continue}island.Clear();var stackCount=0;stack[stackCount++]=seed;seed.m_flags|=b2Body.e_islandFlag;while(stackCount!==0){b=stack[--stackCount];island.AddBody(b);if(!b.m_isAwake){b.SetAwake(true)}if(b.GetType()===b2Body.b2_staticBody){continue}var other;for(var ce=b.m_contactList;ce;ce=ce.next){if(ce.contact.m_flags&b2Contact.e_islandFlag){continue}if(!ce.contact.m_isTouching||ce.contact.m_isSensor||!ce.contact.m_isEnabled){continue}island.AddContact(ce.contact);ce.contact.m_flags|=b2Contact.e_islandFlag;other=ce.other;if(other.m_flags&b2Body.e_islandFlag){continue}stack[stackCount++]=other;other.m_flags|=b2Body.e_islandFlag}for(var jn=b.m_jointList;jn;jn=jn.next){if(jn.joint.m_islandFlag==true){continue}other=jn.other;if(other.IsActive()===false){continue}island.AddJoint(jn.joint);jn.joint.m_islandFlag=true;if(other.m_flags&b2Body.e_islandFlag){continue}stack[stackCount++]=other;other.m_flags|=b2Body.e_islandFlag}}island.Solve(step,this.m_gravity,this.m_allowSleep);for(i=0;i0){var minContact=null;var minTOI=1;for(c=this.m_contactList;c;c=c.m_next){if(!c.m_isContinuous||c.m_isSensor||!c.m_isEnabled)continue;var toi=1;if(c.m_flags&b2Contact.e_toiFlag){toi=c.m_toi}else{fA=c.m_fixtureA;fB=c.m_fixtureB;bA=fA.m_body;bB=fB.m_body;if((bA.m_type!==b2Body.b2_dynamicBody||!bA.m_isAwake)&&(bB.m_type!==b2Body.b2_dynamicBody||!bB.m_isAwake)){continue}var t0=bA.m_sweep.t0;if(bA.m_sweep.t00&&toi<1){toi=(1-toi)*t0+toi;if(toi>1)toi=1}c.m_toi=toi;c.m_flags|=b2Contact.e_toiFlag}if(Number.MIN_VALUE0){b=island.m_bodies[--i];b.m_flags&=~b2Body.e_islandFlag;if(!b.m_isAwake)continue;if(b.m_type!==b2Body.b2_dynamicBody)continue;b.SynchronizeFixtures();for(cEdge=b.m_contactList;cEdge;cEdge=cEdge.next){cEdge.contact.m_flags&=~b2Contact.e_toiFlag}}i=island.m_contactCount|0;while(i>0)island.m_contacts[--i].m_flags&=~(b2Contact.e_toiFlag|b2Contact.e_islandFlag);i=island.m_jointCount|0;while(i>0)island.m_joints[--i].m_islandFlag=false;this.m_contactManager.FindNewContacts()}};$i_109.postDefs.push(function(){$i_109.Dynamics.b2World.s_timestep2=new b2TimeStep;$i_109.Dynamics.b2World.s_xf=new b2Transform(new b2Vec2());$i_109.Dynamics.b2World.s_backupA=new b2Sweep;$i_109.Dynamics.b2World.s_backupB=new b2Sweep;$i_109.Dynamics.b2World.s_timestep=new b2TimeStep;$i_109.Dynamics.b2World.s_queue=[];$i_109.Dynamics.b2World.s_jointColor=new b2Color(0.5,0.8,0.8);$i_109.Dynamics.b2World.e_newFixture=1;$i_109.Dynamics.b2World.e_locked=2})})();(function(){var b2CircleShape=$i_109.Collision.Shapes.b2CircleShape;var b2EdgeChainDef=$i_109.Collision.Shapes.b2EdgeChainDef;var b2EdgeShape=$i_109.Collision.Shapes.b2EdgeShape;var b2MassData=$i_109.Collision.Shapes.b2MassData;var b2PolygonShape=$i_109.Collision.Shapes.b2PolygonShape;var b2Shape=$i_109.Collision.Shapes.b2Shape;var b2CircleContact=$i_109.Dynamics.Contacts.b2CircleContact;var b2Contact=$i_109.Dynamics.Contacts.b2Contact;var b2ContactConstraint=$i_109.Dynamics.Contacts.b2ContactConstraint;var b2ContactConstraintPoint=$i_109.Dynamics.Contacts.b2ContactConstraintPoint;var b2ContactEdge=$i_109.Dynamics.Contacts.b2ContactEdge;var b2ContactFactory=$i_109.Dynamics.Contacts.b2ContactFactory;var b2ContactRegister=$i_109.Dynamics.Contacts.b2ContactRegister;var b2ContactResult=$i_109.Dynamics.Contacts.b2ContactResult;var b2ContactSolver=$i_109.Dynamics.Contacts.b2ContactSolver;var b2EdgeAndCircleContact=$i_109.Dynamics.Contacts.b2EdgeAndCircleContact;var b2NullContact=$i_109.Dynamics.Contacts.b2NullContact;var b2PolyAndCircleContact=$i_109.Dynamics.Contacts.b2PolyAndCircleContact;var b2PolyAndEdgeContact=$i_109.Dynamics.Contacts.b2PolyAndEdgeContact;var b2PolygonContact=$i_109.Dynamics.Contacts.b2PolygonContact;var b2PositionSolverManifold=$i_109.Dynamics.Contacts.b2PositionSolverManifold;var b2Body=$i_109.Dynamics.b2Body;var b2BodyDef=$i_109.Dynamics.b2BodyDef;var b2ContactFilter=$i_109.Dynamics.b2ContactFilter;var b2ContactImpulse=$i_109.Dynamics.b2ContactImpulse;var b2ContactListener=$i_109.Dynamics.b2ContactListener;var b2ContactManager=$i_109.Dynamics.b2ContactManager;var b2DebugDraw=$i_109.Dynamics.b2DebugDraw;var b2DestructionListener=$i_109.Dynamics.b2DestructionListener;var b2FilterData=$i_109.Dynamics.b2FilterData;var b2Fixture=$i_109.Dynamics.b2Fixture;var b2FixtureDef=$i_109.Dynamics.b2FixtureDef;var b2Island=$i_109.Dynamics.b2Island;var b2TimeStep=$i_109.Dynamics.b2TimeStep;var b2World=$i_109.Dynamics.b2World;var b2Color=$i_109.Common.b2Color;var b2internal=$i_109.Common.b2internal;var b2Settings=$i_109.Common.b2Settings;var b2Mat22=$i_109.Common.Math.b2Mat22;var b2Mat33=$i_109.Common.Math.b2Mat33;var b2Math=$i_109.Common.Math.b2Math;var b2Sweep=$i_109.Common.Math.b2Sweep;var b2Transform=$i_109.Common.Math.b2Transform;var b2Vec2=$i_109.Common.Math.b2Vec2;var b2Vec3=$i_109.Common.Math.b2Vec3;var b2AABB=$i_109.Collision.b2AABB;var b2Bound=$i_109.Collision.b2Bound;var b2BoundValues=$i_109.Collision.b2BoundValues;var b2Collision=$i_109.Collision.b2Collision;var b2ContactID=$i_109.Collision.b2ContactID;var b2ContactPoint=$i_109.Collision.b2ContactPoint;var b2Distance=$i_109.Collision.b2Distance;var b2DistanceInput=$i_109.Collision.b2DistanceInput;var b2DistanceOutput=$i_109.Collision.b2DistanceOutput;var b2DistanceProxy=$i_109.Collision.b2DistanceProxy;var b2DynamicTree=$i_109.Collision.b2DynamicTree;var b2DynamicTreeBroadPhase=$i_109.Collision.b2DynamicTreeBroadPhase;var b2DynamicTreeNode=$i_109.Collision.b2DynamicTreeNode;var b2DynamicTreePair=$i_109.Collision.b2DynamicTreePair;var b2Manifold=$i_109.Collision.b2Manifold;var b2ManifoldPoint=$i_109.Collision.b2ManifoldPoint;var b2Point=$i_109.Collision.b2Point;var b2RayCastInput=$i_109.Collision.b2RayCastInput;var b2RayCastOutput=$i_109.Collision.b2RayCastOutput;var b2Segment=$i_109.Collision.b2Segment;var b2SeparationFunction=$i_109.Collision.b2SeparationFunction;var b2Simplex=$i_109.Collision.b2Simplex;var b2SimplexCache=$i_109.Collision.b2SimplexCache;var b2SimplexVertex=$i_109.Collision.b2SimplexVertex;var b2TimeOfImpact=$i_109.Collision.b2TimeOfImpact;var b2TOIInput=$i_109.Collision.b2TOIInput;var b2WorldManifold=$i_109.Collision.b2WorldManifold;var ClipVertex=$i_109.Collision.ClipVertex;var Features=$i_109.Collision.Features;var IBroadPhase=$i_109.Collision.IBroadPhase;$i_109.inherit(b2CircleContact,$i_109.Dynamics.Contacts.b2Contact);b2CircleContact.prototype.__super=$i_109.Dynamics.Contacts.b2Contact.prototype;b2CircleContact.b2CircleContact=function(){$i_109.Dynamics.Contacts.b2Contact.b2Contact.apply(this,arguments)};b2CircleContact.Create=function(allocator){return new b2CircleContact};b2CircleContact.Destroy=function(contact,allocator){};b2CircleContact.prototype.Reset=function(fixtureA,fixtureB){this.__super.Reset.call(this,fixtureA,fixtureB)};b2CircleContact.prototype.Evaluate=function(){var bA=this.m_fixtureA.GetBody();var bB=this.m_fixtureB.GetBody();b2Collision.CollideCircles(this.m_manifold,this.m_fixtureA.GetShape()instanceof b2CircleShape?this.m_fixtureA.GetShape():null,bA.m_xf,this.m_fixtureB.GetShape()instanceof b2CircleShape?this.m_fixtureB.GetShape():null,bB.m_xf)};b2Contact.b2Contact=function(){this.m_nodeA=new b2ContactEdge;this.m_nodeB=new b2ContactEdge;this.m_manifold=new b2Manifold;this.m_oldManifold=new b2Manifold;this.m_swapped=false};b2Contact.prototype.GetManifold=function(){return this.m_manifold};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)};b2Contact.prototype.IsTouching=function(){return this.m_isTouching};b2Contact.prototype.IsContinuous=function(){return this.m_isContinuous};b2Contact.prototype.SetSensor=function(sensor){this.m_isSensor=sensor};b2Contact.prototype.IsSensor=function(){return this.m_isSensor};b2Contact.prototype.SetEnabled=function(flag){this.m_isEnabled=flag};b2Contact.prototype.IsEnabled=function(){return this.m_isEnabled};b2Contact.prototype.GetNext=function(){return this.m_next};b2Contact.prototype.GetFixtureA=function(){return this.m_fixtureA};b2Contact.prototype.GetFixtureB=function(){return this.m_fixtureB};b2Contact.prototype.FlagForFiltering=function(){this.m_isFiltered=true};b2Contact.prototype.b2Contact=function(){};b2Contact.prototype.Reset=function(fixtureA,fixtureB){this.m_flags=b2Contact.e_enabledFlag;if(!fixtureA||!fixtureB){this.m_fixtureA=null;this.m_fixtureB=null;return}this.m_isSensor=fixtureA.IsSensor()||fixtureB.IsSensor();this.m_isEnabled=true;this.m_isFiltered=false;this.m_isTouching=false;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();this.m_isContinuous=bodyA.GetType()!==b2Body.b2_dynamicBody||bodyA.IsBullet()||bodyB.GetType()!==b2Body.b2_dynamicBody||bodyB.IsBullet();this.m_fixtureA=fixtureA;this.m_fixtureB=fixtureB;this.m_manifold.m_pointCount=0;this.m_prev=null;this.m_next=null;this.m_nodeA.contact=null;this.m_nodeA.prev=null;this.m_nodeA.next=null;this.m_nodeA.other=null;this.m_nodeB.contact=null;this.m_nodeB.prev=null;this.m_nodeB.next=null;this.m_nodeB.other=null};b2Contact.prototype.Update=function(listener){var tManifold=this.m_oldManifold;this.m_oldManifold=this.m_manifold;this.m_manifold=tManifold;this.m_isEnabled=true;var touching=false;var wasTouching=this.m_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.m_isSensor){if(aabbOverlap){var shapeA=this.m_fixtureA.m_shape;var shapeB=this.m_fixtureB.m_shape;var xfA=bodyA.m_xf;var xfB=bodyB.m_xf;touching=b2Shape.TestOverlap(shapeA,xfA,shapeB,xfB)}this.m_manifold.m_pointCount=0}else{this.m_isContinuous=bodyA.m_type!==b2Body.b2_dynamicBody||bodyA.IsBullet()||bodyB.m_type!==b2Body.b2_dynamicBody||bodyB.IsBullet();if(aabbOverlap){this.Evaluate();touching=this.m_manifold.m_pointCount>0;for(var i=0;i0){contact.m_fixtureA.m_body.SetAwake(true);contact.m_fixtureB.m_body.SetAwake(true)}var type1=contact.m_fixtureA.GetType();var type2=contact.m_fixtureB.GetType();var reg=null;if(contact.m_swapped)reg=this.m_registers[type2][type1];else reg=this.m_registers[type1][type2];contact.Reset(null,null);contact.m_next=reg.pool;reg.pool=contact;var destroyFcn=reg.destroyFcn;destroyFcn(contact,this.m_allocator)};b2ContactRegister.b2ContactRegister=function(){};b2ContactResult.b2ContactResult=function(){this.position=new b2Vec2;this.normal=new b2Vec2;this.id=new b2ContactID};b2ContactSolver.b2ContactSolver=function(){this.m_step=new b2TimeStep;this.m_constraints=[]};b2ContactSolver.prototype.b2ContactSolver=function(){};b2ContactSolver.prototype.Initialize=function(step,contacts,contactCount,allocator){this.m_step.Set(step);this.m_allocator=allocator;this.m_constraintCount=contactCount;while(this.m_constraints.length0){var c=this.m_constraints[--i];var bodyA=c.bodyA;var bodyB=c.bodyB;var wA=bodyA.m_angularVelocity;var wB=bodyB.m_angularVelocity;var vA=bodyA.m_linearVelocity;var vB=bodyB.m_linearVelocity;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 friction=c.friction;j=c.pointCount;while(j>0){ccp=c.points[--j];dvX=vB.x-wB*ccp.rB.y-vA.x+wA*ccp.rA.y;dvY=vB.y+wB*ccp.rB.x-vA.y-wA*ccp.rA.x;vt=dvX*tangentX+dvY*tangentY;lambda=ccp.tangentMass*-vt;maxFriction=friction*ccp.normalImpulse;newImpulse=b2Math.Clamp(ccp.tangentImpulse+lambda,-maxFriction,maxFriction);lambda=newImpulse-ccp.tangentImpulse;PX=lambda*tangentX;PY=lambda*tangentY;vA.x-=invMassA*PX;vA.y-=invMassA*PY;wA-=invIA*(ccp.rA.x*PY-ccp.rA.y*PX);vB.x+=invMassB*PX;vB.y+=invMassB*PY;wB+=invIB*(ccp.rB.x*PY-ccp.rB.y*PX);ccp.tangentImpulse=newImpulse}if(c.pointCount===1){ccp=c.points[0];dvX=vB.x+-wB*ccp.rB.y-vA.x- -wA*ccp.rA.y;dvY=vB.y+wB*ccp.rB.x-vA.y-wA*ccp.rA.x;vn=dvX*normalX+dvY*normalY;lambda=-ccp.normalMass*(vn-ccp.velocityBias);newImpulse=ccp.normalImpulse+lambda;newImpulse=newImpulse>0?newImpulse:0;lambda=newImpulse-ccp.normalImpulse;PX=lambda*normalX;PY=lambda*normalY;vA.x-=invMassA*PX;vA.y-=invMassA*PY;wA-=invIA*(ccp.rA.x*PY-ccp.rA.y*PX);vB.x+=invMassB*PX;vB.y+=invMassB*PY;wB+=invIB*(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=vB.x-wB*cp1.rB.y-vA.x+wA*cp1.rA.y;var dv1Y=vB.y+wB*cp1.rB.x-vA.y-wA*cp1.rA.x;var dv2X=vB.x-wB*cp2.rB.y-vA.x+wA*cp2.rA.y;var dv2Y=vB.y+wB*cp2.rB.x-vA.y-wA*cp2.rA.x;var vn1=dv1X*normalX+dv1Y*normalY;var vn2=dv2X*normalX+dv2Y*normalY;var bX=vn1-cp1.velocityBias;var bY=vn2-cp2.velocityBias;var tMat=c.K;bX-=tMat.col1.x*aX+tMat.col2.x*aY;bY-=tMat.col1.y*aX+tMat.col2.y*aY;for(;;){tMat=c.normalMass;var xX=-(tMat.col1.x*bX+tMat.col2.x*bY);var xY=-(tMat.col1.y*bX+tMat.col2.y*bY);if(xX>=0&&xY>=0){dX=xX-aX;dY=xY-aY;P1X=dX*normalX;P1Y=dX*normalY;P2X=dY*normalX;P2Y=dY*normalY;vA.x-=invMassA*(P1X+P2X);vA.y-=invMassA*(P1Y+P2Y);wA-=invIA*(cp1.rA.x*P1Y-cp1.rA.y*P1X+cp2.rA.x*P2Y-cp2.rA.y*P2X);vB.x+=invMassB*(P1X+P2X);vB.y+=invMassB*(P1Y+P2Y);wB+=invIB*(cp1.rB.x*P1Y-cp1.rB.y*P1X+cp2.rB.x*P2Y-cp2.rB.y*P2X);cp1.normalImpulse=xX;cp2.normalImpulse=xY;break}xX=-cp1.normalMass*bX;xY=0;vn1=0;vn2=c.K.col1.y*xX+bY;if(xX>=0&&vn2>=0){dX=xX-aX;dY=xY-aY;P1X=dX*normalX;P1Y=dX*normalY;P2X=dY*normalX;P2Y=dY*normalY;vA.x-=invMassA*(P1X+P2X);vA.y-=invMassA*(P1Y+P2Y);wA-=invIA*(cp1.rA.x*P1Y-cp1.rA.y*P1X+cp2.rA.x*P2Y-cp2.rA.y*P2X);vB.x+=invMassB*(P1X+P2X);vB.y+=invMassB*(P1Y+P2Y);wB+=invIB*(cp1.rB.x*P1Y-cp1.rB.y*P1X+cp2.rB.x*P2Y-cp2.rB.y*P2X);cp1.normalImpulse=xX;cp2.normalImpulse=xY;break}xX=0;xY=-cp2.normalMass*bY;vn1=c.K.col2.x*xY+bX;vn2=0;if(xY>=0&&vn1>=0){dX=xX-aX;dY=xY-aY;P1X=dX*normalX;P1Y=dX*normalY;P2X=dY*normalX;P2Y=dY*normalY;vA.x-=invMassA*(P1X+P2X);vA.y-=invMassA*(P1Y+P2Y);wA-=invIA*(cp1.rA.x*P1Y-cp1.rA.y*P1X+cp2.rA.x*P2Y-cp2.rA.y*P2X);vB.x+=invMassB*(P1X+P2X);vB.y+=invMassB*(P1Y+P2Y);wB+=invIB*(cp1.rB.x*P1Y-cp1.rB.y*P1X+cp2.rB.x*P2Y-cp2.rB.y*P2X);cp1.normalImpulse=xX;cp2.normalImpulse=xY;break}xX=0;xY=0;vn1=bX;vn2=bY;if(vn1>=0&&vn2>=0){dX=xX-aX;dY=xY-aY;P1X=dX*normalX;P1Y=dX*normalY;P2X=dY*normalX;P2Y=dY*normalY;vA.x-=invMassA*(P1X+P2X);vA.y-=invMassA*(P1Y+P2Y);wA-=invIA*(cp1.rA.x*P1Y-cp1.rA.y*P1X+cp2.rA.x*P2Y-cp2.rA.y*P2X);vB.x+=invMassB*(P1X+P2X);vB.y+=invMassB*(P1Y+P2Y);wB+=invIB*(cp1.rB.x*P1Y-cp1.rB.y*P1X+cp2.rB.x*P2Y-cp2.rB.y*P2X);cp1.normalImpulse=xX;cp2.normalImpulse=xY;break}break}}bodyA.m_angularVelocity=wA;bodyB.m_angularVelocity=wB}};b2ContactSolver.prototype.FinalizeVelocityConstraints=function(){for(var i=0;i-1.5*b2Settings.b2_linearSlop};$i_109.postDefs.push(function(){$i_109.Dynamics.Contacts.b2ContactSolver.s_worldManifold=new b2WorldManifold;$i_109.Dynamics.Contacts.b2ContactSolver.s_psm=new b2PositionSolverManifold});$i_109.inherit(b2EdgeAndCircleContact,$i_109.Dynamics.Contacts.b2Contact);b2EdgeAndCircleContact.prototype.__super=$i_109.Dynamics.Contacts.b2Contact.prototype;b2EdgeAndCircleContact.b2EdgeAndCircleContact=function(){$i_109.Dynamics.Contacts.b2Contact.b2Contact.apply(this,arguments)};b2EdgeAndCircleContact.Create=function(allocator){return new b2EdgeAndCircleContact};b2EdgeAndCircleContact.Destroy=function(contact,allocator){};b2EdgeAndCircleContact.prototype.Reset=function(fixtureA,fixtureB){this.__super.Reset.call(this,fixtureA,fixtureB)};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()instanceof b2EdgeShape?this.m_fixtureA.GetShape():null,bA.m_xf,this.m_fixtureB.GetShape()instanceof b2CircleShape?this.m_fixtureB.GetShape():null,bB.m_xf)};b2EdgeAndCircleContact.prototype.b2CollideEdgeAndCircle=function(manifold,edge,xf1,circle,xf2){};$i_109.inherit(b2NullContact,$i_109.Dynamics.Contacts.b2Contact);b2NullContact.prototype.__super=$i_109.Dynamics.Contacts.b2Contact.prototype;b2NullContact.b2NullContact=function(){$i_109.Dynamics.Contacts.b2Contact.b2Contact.apply(this,arguments)};b2NullContact.prototype.b2NullContact=function(){this.__super.b2Contact.call(this)};b2NullContact.prototype.Evaluate=function(){};$i_109.inherit(b2PolyAndCircleContact,$i_109.Dynamics.Contacts.b2Contact);b2PolyAndCircleContact.prototype.__super=$i_109.Dynamics.Contacts.b2Contact.prototype;b2PolyAndCircleContact.Create=function(allocator){return new b2PolyAndCircleContact};b2PolyAndCircleContact.Destroy=function(contact,allocator){};b2PolyAndCircleContact.prototype.Reset=function(fixtureA,fixtureB){this.__super.Reset.call(this,fixtureA,fixtureB)};b2PolyAndCircleContact.prototype.Evaluate=function(){var bA=this.m_fixtureA.m_body;var bB=this.m_fixtureB.m_body;b2Collision.CollidePolygonAndCircle(this.m_manifold,this.m_fixtureA.GetShape()instanceof b2PolygonShape?this.m_fixtureA.GetShape():null,bA.m_xf,this.m_fixtureB.GetShape()instanceof b2CircleShape?this.m_fixtureB.GetShape():null,bB.m_xf)};$i_109.inherit(b2PolyAndEdgeContact,$i_109.Dynamics.Contacts.b2Contact);b2PolyAndEdgeContact.prototype.__super=$i_109.Dynamics.Contacts.b2Contact.prototype;b2PolyAndEdgeContact.b2PolyAndEdgeContact=function(){b2Contact.b2Contact.apply(this,arguments)};b2PolyAndEdgeContact.Create=function(allocator){return new b2PolyAndEdgeContact};b2PolyAndEdgeContact.Destroy=function(contact,allocator){};b2PolyAndEdgeContact.prototype.Reset=function(fixtureA,fixtureB){this.__super.Reset.call(this,fixtureA,fixtureB)};b2PolyAndEdgeContact.prototype.Evaluate=function(){var bA=this.m_fixtureA.GetBody();var bB=this.m_fixtureB.GetBody();this.b2CollidePolyAndEdge(this.m_manifold,this.m_fixtureA.GetShape()instanceof b2PolygonShape?this.m_fixtureA.GetShape():null,bA.m_xf,this.m_fixtureB.GetShape()instanceof b2EdgeShape?this.m_fixtureB.GetShape():null,bB.m_xf)};b2PolyAndEdgeContact.prototype.b2CollidePolyAndEdge=function(manifold,polygon,xf1,edge,xf2){};$i_109.inherit(b2PolygonContact,$i_109.Dynamics.Contacts.b2Contact);b2PolygonContact.prototype.__super=$i_109.Dynamics.Contacts.b2Contact.prototype;b2PolygonContact.b2PolygonContact=function(){b2Contact.b2Contact.apply(this,arguments)};b2PolygonContact.Create=function(allocator){return new b2PolygonContact};b2PolygonContact.Destroy=function(contact,allocator){};b2PolygonContact.prototype.Reset=function(fixtureA,fixtureB){this.__super.Reset.call(this,fixtureA,fixtureB)};b2PolygonContact.prototype.Evaluate=function(){var bA=this.m_fixtureA.GetBody();var bB=this.m_fixtureB.GetBody();b2Collision.CollidePolygons(this.m_manifold,this.m_fixtureA.m_shape instanceof b2PolygonShape?this.m_fixtureA.m_shape:null,bA.m_xf,this.m_fixtureB.m_shape instanceof b2PolygonShape?this.m_fixtureB.m_shape:null,bB.m_xf)};b2PositionSolverManifold.b2PositionSolverManifold=function(){};b2PositionSolverManifold.prototype.b2PositionSolverManifold=function(){this.m_normal=new b2Vec2;this.m_separations=[0,0];this.m_points=[new b2Vec2,new b2Vec2]};b2PositionSolverManifold.prototype.Initialize=function(cc){var i=0;var clipPointX=0;var clipPointY=0;var tMat;var tVec;var planePointX=0;var planePointY=0;switch(cc.type){case b2Manifold.e_circles:{tMat=cc.bodyA.m_xf.R;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>Number.MIN_VALUE*Number.MIN_VALUE){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=0.5*(pointAX+pointBX);this.m_points[0].y=0.5*(pointAY+pointBY);this.m_separations[0]=dX*this.m_normal.x+dY*this.m_normal.y-cc.radius}break;case b2Manifold.e_faceA:{tMat=cc.bodyA.m_xf.R;tVec=cc.localPlaneNormal;this.m_normal.x=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;this.m_normal.y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=cc.bodyA.m_xf.R;tVec=cc.localPoint;planePointX=cc.bodyA.m_xf.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);planePointY=cc.bodyA.m_xf.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tMat=cc.bodyB.m_xf.R;i=cc.pointCount;while(i>0){tVec=cc.points[--i].localPoint;clipPointX=cc.bodyB.m_xf.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);clipPointY=cc.bodyB.m_xf.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.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}}break;case b2Manifold.e_faceB:{tMat=cc.bodyB.m_xf.R;tVec=cc.localPlaneNormal;this.m_normal.x=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;this.m_normal.y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=cc.bodyB.m_xf.R;tVec=cc.localPoint;planePointX=cc.bodyB.m_xf.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);planePointY=cc.bodyB.m_xf.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.y);tMat=cc.bodyA.m_xf.R;i=cc.pointCount;while(i>0){tVec=cc.points[--i].localPoint;clipPointX=cc.bodyA.m_xf.position.x+(tMat.col1.x*tVec.x+tMat.col2.x*tVec.y);clipPointY=cc.bodyA.m_xf.position.y+(tMat.col1.y*tVec.x+tMat.col2.y*tVec.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}break;}};$i_109.postDefs.push(function(){$i_109.Dynamics.Contacts.b2PositionSolverManifold.circlePointA=new b2Vec2;$i_109.Dynamics.Contacts.b2PositionSolverManifold.circlePointB=new b2Vec2})})();(function(){var b2Mat22=$i_109.Common.Math.b2Mat22;var b2Math=$i_109.Common.Math.b2Math;var b2Vec2=$i_109.Common.Math.b2Vec2;var b2BuoyancyController=$i_109.Dynamics.Controllers.b2BuoyancyController;var b2ConstantAccelController=$i_109.Dynamics.Controllers.b2ConstantAccelController;var b2ConstantForceController=$i_109.Dynamics.Controllers.b2ConstantForceController;var b2Controller=$i_109.Dynamics.Controllers.b2Controller;var b2ControllerEdge=$i_109.Dynamics.Controllers.b2ControllerEdge;var b2GravityController=$i_109.Dynamics.Controllers.b2GravityController;var b2TensorDampingController=$i_109.Dynamics.Controllers.b2TensorDampingController;$i_109.inherit(b2BuoyancyController,$i_109.Dynamics.Controllers.b2Controller);b2BuoyancyController.prototype.__super=$i_109.Dynamics.Controllers.b2Controller.prototype;b2BuoyancyController.b2BuoyancyController=function(){$i_109.Dynamics.Controllers.b2Controller.b2Controller.apply(this,arguments);this.normal=new b2Vec2(0,-1);this.offset=0;this.density=0;this.velocity=new b2Vec2;this.linearDrag=2;this.angularDrag=1;this.useDensity=false;this.useWorldGravity=true;this.gravity=null};b2BuoyancyController.prototype.Draw=function(debugDraw){var r=1000;var p1=new b2Vec2;var p2=new b2Vec2;p1.x=this.normal.x*this.offset+this.normal.y*r;p1.y=this.normal.y*this.offset-this.normal.x*r;p2.x=this.normal.x*this.offset-this.normal.y*r;p2.y=this.normal.y*this.offset+this.normal.x*r;var color=new b2Color(0,0,1);debugDraw.DrawSegment(p1,p2,color)};b2BuoyancyController.prototype.Step=function(step){if(!this.m_bodyList)return;if(this.useWorldGravity){this.gravity=this.GetWorld().GetGravity().Copy()}for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.m_isAwake)continue;var areac=new b2Vec2;var massc=new b2Vec2;var area=0;var mass=0;for(var fixture=body.GetFixtureList();fixture;fixture=fixture.GetNext()){var sc=new b2Vec2;var sarea=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}areac.x/=area;areac.y/=area;massc.x/=mass;massc.y/=mass;if(area0||yDamping>0){this.maxTimestep=1/Math.max(xDamping,yDamping)}else{this.maxTimestep=0}};b2TensorDampingController.prototype.Step=function(step){var timestep=step.dt;if(timestep<=Number.MIN_VALUE)return;if(timestep>this.maxTimestep&&this.maxTimestep>0)timestep=this.maxTimestep;for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.m_isAwake)continue;var multV=b2Math.MulMV(this.T,body.GetLocalVector(body.GetLinearVelocity()));var damping=body.GetWorldVector(multV);var vec=new b2Vec2(body.GetLinearVelocity().x+damping.x*timestep,body.GetLinearVelocity().y+damping.y*timestep);body.SetLinearVelocity(vec)}}})();(function(){var b2Color=$i_109.Common.b2Color;var b2internal=$i_109.Common.b2internal;var b2Settings=$i_109.Common.b2Settings;var b2Mat22=$i_109.Common.Math.b2Mat22;var b2Mat33=$i_109.Common.Math.b2Mat33;var b2Math=$i_109.Common.Math.b2Math;var b2Sweep=$i_109.Common.Math.b2Sweep;var b2Transform=$i_109.Common.Math.b2Transform;var b2Vec2=$i_109.Common.Math.b2Vec2;var b2Vec3=$i_109.Common.Math.b2Vec3;var b2DistanceJoint=$i_109.Dynamics.Joints.b2DistanceJoint;var b2DistanceJointDef=$i_109.Dynamics.Joints.b2DistanceJointDef;var b2FrictionJoint=$i_109.Dynamics.Joints.b2FrictionJoint;var b2FrictionJointDef=$i_109.Dynamics.Joints.b2FrictionJointDef;var b2GearJoint=$i_109.Dynamics.Joints.b2GearJoint;var b2GearJointDef=$i_109.Dynamics.Joints.b2GearJointDef;var b2Jacobian=$i_109.Dynamics.Joints.b2Jacobian;var b2Joint=$i_109.Dynamics.Joints.b2Joint;var b2JointDef=$i_109.Dynamics.Joints.b2JointDef;var b2JointEdge=$i_109.Dynamics.Joints.b2JointEdge;var b2LineJoint=$i_109.Dynamics.Joints.b2LineJoint;var b2LineJointDef=$i_109.Dynamics.Joints.b2LineJointDef;var b2MouseJoint=$i_109.Dynamics.Joints.b2MouseJoint;var b2MouseJointDef=$i_109.Dynamics.Joints.b2MouseJointDef;var b2PrismaticJoint=$i_109.Dynamics.Joints.b2PrismaticJoint;var b2PrismaticJointDef=$i_109.Dynamics.Joints.b2PrismaticJointDef;var b2PulleyJoint=$i_109.Dynamics.Joints.b2PulleyJoint;var b2PulleyJointDef=$i_109.Dynamics.Joints.b2PulleyJointDef;var b2RevoluteJoint=$i_109.Dynamics.Joints.b2RevoluteJoint;var b2RevoluteJointDef=$i_109.Dynamics.Joints.b2RevoluteJointDef;var b2WeldJoint=$i_109.Dynamics.Joints.b2WeldJoint;var b2WeldJointDef=$i_109.Dynamics.Joints.b2WeldJointDef;var b2Body=$i_109.Dynamics.b2Body;var b2BodyDef=$i_109.Dynamics.b2BodyDef;var b2ContactFilter=$i_109.Dynamics.b2ContactFilter;var b2ContactImpulse=$i_109.Dynamics.b2ContactImpulse;var b2ContactListener=$i_109.Dynamics.b2ContactListener;var b2ContactManager=$i_109.Dynamics.b2ContactManager;var b2DebugDraw=$i_109.Dynamics.b2DebugDraw;var b2DestructionListener=$i_109.Dynamics.b2DestructionListener;var b2FilterData=$i_109.Dynamics.b2FilterData;var b2Fixture=$i_109.Dynamics.b2Fixture;var b2FixtureDef=$i_109.Dynamics.b2FixtureDef;var b2Island=$i_109.Dynamics.b2Island;var b2TimeStep=$i_109.Dynamics.b2TimeStep;var b2World=$i_109.Dynamics.b2World;$i_109.inherit(b2DistanceJoint,$i_109.Dynamics.Joints.b2Joint);b2DistanceJoint.prototype.__super=$i_109.Dynamics.Joints.b2Joint.prototype;b2DistanceJoint.b2DistanceJoint=function(){$i_109.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_localAnchor1=new b2Vec2;this.m_localAnchor2=new b2Vec2;this.m_u=new b2Vec2};b2DistanceJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};b2DistanceJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};b2DistanceJoint.prototype.GetReactionForce=function(inv_dt){return new b2Vec2(inv_dt*this.m_impulse*this.m_u.x,inv_dt*this.m_impulse*this.m_u.y)};b2DistanceJoint.prototype.GetReactionTorque=function(inv_dt){return 0};b2DistanceJoint.prototype.GetLength=function(){return this.m_length};b2DistanceJoint.prototype.SetLength=function(length){if(length===undefined)length=0;this.m_length=length};b2DistanceJoint.prototype.GetFrequency=function(){return this.m_frequencyHz};b2DistanceJoint.prototype.SetFrequency=function(hz){if(hz===undefined)hz=0;this.m_frequencyHz=hz};b2DistanceJoint.prototype.GetDampingRatio=function(){return this.m_dampingRatio};b2DistanceJoint.prototype.SetDampingRatio=function(ratio){this.m_dampingRatio=ratio};b2DistanceJoint.prototype.b2DistanceJoint=function(def){this.__super.b2Joint.call(this,def);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};b2DistanceJoint.prototype.InitVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var 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;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>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>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}};b2DistanceJoint.prototype.SolveVelocityConstraints=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var 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=bA.m_linearVelocity.x+-bA.m_angularVelocity*r1Y;var v1Y=bA.m_linearVelocity.y+bA.m_angularVelocity*r1X;var v2X=bB.m_linearVelocity.x+-bB.m_angularVelocity*r2Y;var v2Y=bB.m_linearVelocity.y+bB.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;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)};b2DistanceJoint.prototype.SolvePositionConstraints=function(){if(this.m_frequencyHz>0){return true}var bA=this.m_bodyA;var bB=this.m_bodyB;var 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 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;var length=Math.sqrt(dX*dX+dY*dY);dX/=length;dY/=length;var C=length-this.m_length;C=b2Math.Clamp(C,-b2Settings.b2_maxLinearCorrection,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;bA.m_sweep.c.x-=bA.m_invMass*PX;bA.m_sweep.c.y-=bA.m_invMass*PY;bA.m_sweep.a-=bA.m_invI*(r1X*PY-r1Y*PX);bB.m_sweep.c.x+=bB.m_invMass*PX;bB.m_sweep.c.y+=bB.m_invMass*PY;bB.m_sweep.a+=bB.m_invI*(r2X*PY-r2Y*PX);bA.SynchronizeTransform();bB.SynchronizeTransform();return b2Math.Abs(C)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}};b2FrictionJoint.prototype.SolveVelocityConstraints=function(step){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;var 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;var 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 impulse=-this.m_angularMass*(wB-wA);var oldImpulse=this.m_angularImpulse;maxImpulse=step.dt*this.m_maxTorque;this.m_angularImpulse=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 vec=new b2Vec2(-CdotX,-CdotY);var impulseV=b2Math.MulMV(this.m_linearMass,vec);var oldImpulseV=this.m_linearImpulse.Copy();this.m_linearImpulse.Add(impulseV);maxImpulse=step.dt*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()>maxImpulse*maxImpulse){this.m_linearImpulse.Normalize();this.m_linearImpulse.Multiply(maxImpulse)}impulseV=new b2Vec2(this.m_linearImpulse.x-oldImpulseV.x,this.m_linearImpulse.y-oldImpulseV.y);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)}bA.m_angularVelocity=wA;bB.m_angularVelocity=wB};b2FrictionJoint.prototype.SolvePositionConstraints=function(){return true};$i_109.inherit(b2FrictionJointDef,$i_109.Dynamics.Joints.b2JointDef);b2FrictionJointDef.prototype.__super=$i_109.Dynamics.Joints.b2JointDef.prototype;b2FrictionJointDef.b2FrictionJointDef=function(){$i_109.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2};b2FrictionJointDef.prototype.b2FrictionJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_frictionJoint;this.maxForce=0;this.maxTorque=0};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))};$i_109.inherit(b2GearJoint,$i_109.Dynamics.Joints.b2Joint);b2GearJoint.prototype.__super=$i_109.Dynamics.Joints.b2Joint.prototype;b2GearJoint.b2GearJoint=function(){$i_109.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_groundAnchor1=new b2Vec2;this.m_groundAnchor2=new b2Vec2;this.m_localAnchor1=new b2Vec2;this.m_localAnchor2=new b2Vec2;this.m_J=new b2Jacobian};b2GearJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};b2GearJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};b2GearJoint.prototype.GetReactionForce=function(inv_dt){return new b2Vec2(inv_dt*this.m_impulse*this.m_J.linearB.x,inv_dt*this.m_impulse*this.m_J.linearB.y)};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)};b2GearJoint.prototype.GetRatio=function(){return this.m_ratio};b2GearJoint.prototype.SetRatio=function(ratio){if(ratio===undefined)ratio=0;this.m_ratio=ratio};b2GearJoint.prototype.b2GearJoint=function(def){this.__super.b2Joint.call(this,def);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===b2Joint.e_revoluteJoint){this.m_revolute1=def.joint1 instanceof b2RevoluteJoint?def.joint1:null;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 instanceof b2PrismaticJoint?def.joint1:null;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===b2Joint.e_revoluteJoint){this.m_revolute2=def.joint2 instanceof b2RevoluteJoint?def.joint2:null;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 instanceof b2PrismaticJoint?def.joint2:null;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};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>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}};b2GearJoint.prototype.SolveVelocityConstraints=function(){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};b2GearJoint.prototype.SolvePositionConstraints=function(){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 impulse=-this.m_mass*(this.m_constant-(coordinate1+this.m_ratio*coordinate2));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 b2Settings.b2_linearSlop>0};$i_109.inherit(b2GearJointDef,$i_109.Dynamics.Joints.b2JointDef);b2GearJointDef.prototype.__super=$i_109.Dynamics.Joints.b2JointDef.prototype;b2GearJointDef.b2GearJointDef=function(){$i_109.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments)};b2GearJointDef.prototype.b2GearJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_gearJoint;this.joint1=null;this.joint2=null;this.ratio=1};b2Jacobian.b2Jacobian=function(){this.linearA=new b2Vec2;this.linearB=new b2Vec2};b2Jacobian.prototype.SetZero=function(){this.linearA.SetZero();this.angularA=0;this.linearB.SetZero();this.angularB=0};b2Jacobian.prototype.Set=function(x1,a1,x2,a2){if(a1===undefined)a1=a2=0;this.linearA.SetV(x1);this.angularA=a1;this.linearB.SetV(x2);this.angularB=a2};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};b2Joint.b2Joint=function(){this.m_edgeA=new b2JointEdge;this.m_edgeB=new b2JointEdge;this.m_localCenterA=new b2Vec2;this.m_localCenterB=new b2Vec2};b2Joint.prototype.GetType=function(){return this.m_type};b2Joint.prototype.GetAnchorA=function(){return null};b2Joint.prototype.GetAnchorB=function(){return null};b2Joint.prototype.GetReactionForce=function(inv_dt){return null};b2Joint.prototype.GetReactionTorque=function(inv_dt){if(inv_dt===undefined)inv_dt=0;return 0};b2Joint.prototype.GetBodyA=function(){return this.m_bodyA};b2Joint.prototype.GetBodyB=function(){return this.m_bodyB};b2Joint.prototype.GetNext=function(){return this.m_next};b2Joint.prototype.GetUserData=function(){return this.m_userData};b2Joint.prototype.SetUserData=function(data){this.m_userData=data};b2Joint.prototype.IsActive=function(){return this.m_bodyA.IsActive()&&this.m_bodyB.IsActive()};b2Joint.Create=function(def){var joint=null;switch(def.type){case b2Joint.e_distanceJoint:{joint=new b2DistanceJoint(def instanceof b2DistanceJointDef?def:null)}break;case b2Joint.e_mouseJoint:{joint=new b2MouseJoint(def instanceof b2MouseJointDef?def:null)}break;case b2Joint.e_prismaticJoint:{joint=new b2PrismaticJoint(def instanceof b2PrismaticJointDef?def:null)}break;case b2Joint.e_revoluteJoint:{joint=new b2RevoluteJoint(def instanceof b2RevoluteJointDef?def:null)}break;case b2Joint.e_pulleyJoint:{joint=new b2PulleyJoint(def instanceof b2PulleyJointDef?def:null)}break;case b2Joint.e_gearJoint:{joint=new b2GearJoint(def instanceof b2GearJointDef?def:null)}break;case b2Joint.e_lineJoint:{joint=new b2LineJoint(def instanceof b2LineJointDef?def:null)}break;case b2Joint.e_weldJoint:{joint=new b2WeldJoint(def instanceof b2WeldJointDef?def:null)}break;case b2Joint.e_frictionJoint:{joint=new b2FrictionJoint(def instanceof b2FrictionJointDef?def:null)}break;default:break;}return joint};b2Joint.Destroy=function(){};b2Joint.prototype.b2Joint=function(def){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;this.m_islandFlag=false;this.m_userData=def.userData};b2Joint.prototype.InitVelocityConstraints=function(step){};b2Joint.prototype.SolveVelocityConstraints=function(step){};b2Joint.prototype.FinalizeVelocityConstraints=function(){};b2Joint.prototype.SolvePositionConstraints=function(baumgarte){return false};$i_109.postDefs.push(function(){$i_109.Dynamics.Joints.b2Joint.e_unknownJoint=0;$i_109.Dynamics.Joints.b2Joint.e_revoluteJoint=1;$i_109.Dynamics.Joints.b2Joint.e_prismaticJoint=2;$i_109.Dynamics.Joints.b2Joint.e_distanceJoint=3;$i_109.Dynamics.Joints.b2Joint.e_pulleyJoint=4;$i_109.Dynamics.Joints.b2Joint.e_mouseJoint=5;$i_109.Dynamics.Joints.b2Joint.e_gearJoint=6;$i_109.Dynamics.Joints.b2Joint.e_lineJoint=7;$i_109.Dynamics.Joints.b2Joint.e_weldJoint=8;$i_109.Dynamics.Joints.b2Joint.e_frictionJoint=9;$i_109.Dynamics.Joints.b2Joint.e_inactiveLimit=0;$i_109.Dynamics.Joints.b2Joint.e_atLowerLimit=1;$i_109.Dynamics.Joints.b2Joint.e_atUpperLimit=2;$i_109.Dynamics.Joints.b2Joint.e_equalLimits=3});b2JointDef.b2JointDef=function(){};b2JointDef.prototype.b2JointDef=function(){this.type=b2Joint.e_unknownJoint;this.userData=null;this.bodyA=null;this.bodyB=null;this.collideConnected=false};$i_109.inherit(b2LineJoint,$i_109.Dynamics.Joints.b2Joint);b2LineJoint.prototype.__super=$i_109.Dynamics.Joints.b2Joint.prototype;b2LineJoint.b2LineJoint=function(){$i_109.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_localAnchor1=new b2Vec2;this.m_localAnchor2=new b2Vec2;this.m_localXAxis1=new b2Vec2;this.m_localYAxis1=new b2Vec2;this.m_axis=new b2Vec2;this.m_perp=new b2Vec2;this.m_K=new b2Mat22;this.m_impulse=new b2Vec2};b2LineJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};b2LineJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};b2LineJoint.prototype.GetReactionForce=function(inv_dt){return new b2Vec2(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))};b2LineJoint.prototype.GetReactionTorque=function(inv_dt){return inv_dt*this.m_impulse.y};b2LineJoint.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;var axis=bA.GetWorldVector(this.m_localXAxis1);var translation=axis.x*dX+axis.y*dY;return translation};b2LineJoint.prototype.GetJointSpeed=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var 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};b2LineJoint.prototype.IsLimitEnabled=function(){return this.m_enableLimit};b2LineJoint.prototype.EnableLimit=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag};b2LineJoint.prototype.GetLowerLimit=function(){return this.m_lowerTranslation};b2LineJoint.prototype.GetUpperLimit=function(){return this.m_upperTranslation};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};b2LineJoint.prototype.IsMotorEnabled=function(){return this.m_enableMotor};b2LineJoint.prototype.EnableMotor=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag};b2LineJoint.prototype.SetMotorSpeed=function(speed){if(speed===undefined)speed=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed};b2LineJoint.prototype.GetMotorSpeed=function(){return this.m_motorSpeed};b2LineJoint.prototype.SetMaxMotorForce=function(force){if(force===undefined)force=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorForce=force};b2LineJoint.prototype.GetMaxMotorForce=function(){return this.m_maxMotorForce};b2LineJoint.prototype.GetMotorForce=function(){return this.m_motorImpulse};b2LineJoint.prototype.b2LineJoint=function(def){this.__super.b2Joint.call(this,def);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=b2Joint.e_inactiveLimit;this.m_axis.SetZero();this.m_perp.SetZero()};b2LineJoint.prototype.InitVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;this.m_localCenterA.SetV(bA.GetLocalCenter());this.m_localCenterB.SetV(bB.GetLocalCenter());var xf1=bA.GetTransform();var 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;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-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 mult=b2Math.MulMV(xf1.R,this.m_localXAxis1);this.m_axis.SetV(mult);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>Number.MIN_VALUE?1/this.m_motorMass:0}{var mult=b2Math.MulMV(xf1.R,this.m_localYAxis1);this.m_perp.SetV(mult);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(b2Math.Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2Settings.b2_linearSlop){this.m_limitState=b2Joint.e_equalLimits}else if(jointTransition<=this.m_lowerTranslation){if(this.m_limitState!==b2Joint.e_atLowerLimit){this.m_limitState=b2Joint.e_atLowerLimit;this.m_impulse.y=0}}else if(jointTransition>=this.m_upperTranslation){if(this.m_limitState!==b2Joint.e_atUpperLimit){this.m_limitState=b2Joint.e_atUpperLimit;this.m_impulse.y=0}}else{this.m_limitState=b2Joint.e_inactiveLimit;this.m_impulse.y=0}}else{this.m_limitState=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}};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&&this.m_limitState!==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=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&&this.m_limitState!==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 vec=new b2Vec2;var df=this.m_K.Solve(vec,-Cdot1,-Cdot2);this.m_impulse.Add(df);if(this.m_limitState===b2Joint.e_atLowerLimit){this.m_impulse.y=b2Math.Max(this.m_impulse.y,0)}else if(this.m_limitState===b2Joint.e_atUpperLimit){this.m_impulse.y=b2Math.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;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};b2LineJoint.prototype.SolvePositionConstraints=function(){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 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=b2Mat22.FromAngle(a1);var R2=b2Mat22.FromAngle(a2);var tMat=R1;var r1X=this.m_localAnchor1.x-this.m_localCenterA.x;var r1Y=this.m_localAnchor1.y-this.m_localCenterA.y;var 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=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(b2Math.Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2Settings.b2_linearSlop){C2=b2Math.Clamp(translation,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);linearError=b2Math.Abs(translation);active=true}else if(translation<=this.m_lowerTranslation){C2=b2Math.Clamp(translation-this.m_lowerTranslation+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0);linearError=this.m_lowerTranslation-translation;active=true}else if(translation>=this.m_upperTranslation){C2=b2Math.Clamp(translation-this.m_upperTranslation+b2Settings.b2_linearSlop,0,b2Settings.b2_maxLinearCorrection);linearError=translation-this.m_upperTranslation;active=true}}this.m_perp=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=new b2Vec2;var C1=this.m_perp.x*dX+this.m_perp.y*dY;linearError=b2Math.Max(linearError,b2Math.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<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop};$i_109.inherit(b2LineJointDef,$i_109.Dynamics.Joints.b2JointDef);b2LineJointDef.prototype.__super=$i_109.Dynamics.Joints.b2JointDef.prototype;b2LineJointDef.b2LineJointDef=function(){$i_109.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2;this.localAxisA=new b2Vec2};b2LineJointDef.prototype.b2LineJointDef=function(){this.__super.b2JointDef.call(this);this.type=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};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)};$i_109.inherit(b2MouseJoint,$i_109.Dynamics.Joints.b2Joint);b2MouseJoint.prototype.__super=$i_109.Dynamics.Joints.b2Joint.prototype;b2MouseJoint.b2MouseJoint=function(){$i_109.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.K=new b2Mat22;this.K1=new b2Mat22;this.K2=new b2Mat22;this.m_localAnchor=new b2Vec2;this.m_target=new b2Vec2;this.m_impulse=new b2Vec2;this.m_mass=new b2Mat22;this.m_C=new b2Vec2};b2MouseJoint.prototype.GetAnchorA=function(){return this.m_target};b2MouseJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor)};b2MouseJoint.prototype.GetReactionForce=function(inv_dt){return new b2Vec2(inv_dt*this.m_impulse.x,inv_dt*this.m_impulse.y)};b2MouseJoint.prototype.GetReactionTorque=function(inv_dt){return 0};b2MouseJoint.prototype.GetTarget=function(){return this.m_target};b2MouseJoint.prototype.SetTarget=function(target){if(!this.m_bodyB.m_isAwake){this.m_bodyB.SetAwake(true)}this.m_target=target};b2MouseJoint.prototype.GetMaxForce=function(){return this.m_maxForce};b2MouseJoint.prototype.SetMaxForce=function(maxForce){if(maxForce===undefined)maxForce=0;this.m_maxForce=maxForce};b2MouseJoint.prototype.GetFrequency=function(){return this.m_frequencyHz};b2MouseJoint.prototype.SetFrequency=function(hz){if(hz===undefined)hz=0;this.m_frequencyHz=hz};b2MouseJoint.prototype.GetDampingRatio=function(){return this.m_dampingRatio};b2MouseJoint.prototype.SetDampingRatio=function(ratio){if(ratio===undefined)ratio=0;this.m_dampingRatio=ratio};b2MouseJoint.prototype.b2MouseJoint=function(def){this.__super.b2Joint.call(this,def);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};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*=0.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)};b2MouseJoint.prototype.SolveVelocityConstraints=function(step){var b=this.m_bodyB;var 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 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;var 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()>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)};b2MouseJoint.prototype.SolvePositionConstraints=function(baumgarte){return true};$i_109.inherit(b2MouseJointDef,$i_109.Dynamics.Joints.b2JointDef);b2MouseJointDef.prototype.__super=$i_109.Dynamics.Joints.b2JointDef.prototype;b2MouseJointDef.b2MouseJointDef=function(){$i_109.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.target=new b2Vec2};b2MouseJointDef.prototype.b2MouseJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_mouseJoint;this.maxForce=0;this.frequencyHz=5;this.dampingRatio=0.7};$i_109.inherit(b2PrismaticJoint,$i_109.Dynamics.Joints.b2Joint);b2PrismaticJoint.prototype.__super=$i_109.Dynamics.Joints.b2Joint.prototype;b2PrismaticJoint.b2PrismaticJoint=function(){$i_109.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_localAnchor1=new b2Vec2;this.m_localAnchor2=new b2Vec2;this.m_localXAxis1=new b2Vec2;this.m_localYAxis1=new b2Vec2;this.m_axis=new b2Vec2;this.m_perp=new b2Vec2;this.m_K=new b2Mat33;this.m_impulse=new b2Vec3(0,0,0)};b2PrismaticJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};b2PrismaticJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};b2PrismaticJoint.prototype.GetReactionForce=function(inv_dt){return new b2Vec2(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))};b2PrismaticJoint.prototype.GetReactionTorque=function(inv_dt){return inv_dt*this.m_impulse.y};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;var axis=bA.GetWorldVector(this.m_localXAxis1);var translation=axis.x*dX+axis.y*dY;return translation};b2PrismaticJoint.prototype.GetJointSpeed=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var 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};b2PrismaticJoint.prototype.IsLimitEnabled=function(){return this.m_enableLimit};b2PrismaticJoint.prototype.EnableLimit=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag};b2PrismaticJoint.prototype.GetLowerLimit=function(){return this.m_lowerTranslation};b2PrismaticJoint.prototype.GetUpperLimit=function(){return this.m_upperTranslation};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};b2PrismaticJoint.prototype.IsMotorEnabled=function(){return this.m_enableMotor};b2PrismaticJoint.prototype.EnableMotor=function(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag};b2PrismaticJoint.prototype.SetMotorSpeed=function(speed){if(speed===undefined)speed=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed};b2PrismaticJoint.prototype.GetMotorSpeed=function(){return this.m_motorSpeed};b2PrismaticJoint.prototype.SetMaxMotorForce=function(force){if(force===undefined)force=0;this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorForce=force};b2PrismaticJoint.prototype.GetMotorForce=function(){return this.m_motorImpulse};b2PrismaticJoint.prototype.b2PrismaticJoint=function(def){this.__super.b2Joint.call(this,def);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=b2Joint.e_inactiveLimit;this.m_axis.SetZero();this.m_perp.SetZero()};b2PrismaticJoint.prototype.InitVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;this.m_localCenterA.SetV(bA.GetLocalCenter());this.m_localCenterB.SetV(bB.GetLocalCenter());var xf1=bA.GetTransform();var 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;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-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 mult=b2Math.MulMV(xf1.R,this.m_localXAxis1);this.m_axis.SetV(mult);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>Number.MIN_VALUE)this.m_motorMass=1/this.m_motorMass}{var mult=b2Math.MulMV(xf1.R,this.m_localYAxis1);this.m_perp.SetV(mult);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(b2Math.Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2Settings.b2_linearSlop){this.m_limitState=b2Joint.e_equalLimits}else if(jointTransition<=this.m_lowerTranslation){if(this.m_limitState!==b2Joint.e_atLowerLimit){this.m_limitState=b2Joint.e_atLowerLimit;this.m_impulse.z=0}}else if(jointTransition>=this.m_upperTranslation){if(this.m_limitState!==b2Joint.e_atUpperLimit){this.m_limitState=b2Joint.e_atUpperLimit;this.m_impulse.z=0}}else{this.m_limitState=b2Joint.e_inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=b2Joint.e_inactiveLimit}if(!this.m_enableMotor){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}};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&&this.m_limitState!==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=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&&this.m_limitState!==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=this.m_K.Solve33(new b2Vec3(0,0,0),-Cdot1X,-Cdot1Y,-Cdot2);this.m_impulse.Add(df);if(this.m_limitState===b2Joint.e_atLowerLimit){this.m_impulse.z=b2Math.Max(this.m_impulse.z,0)}else if(this.m_limitState===b2Joint.e_atUpperLimit){this.m_impulse.z=b2Math.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 vec=new b2Vec2;var f2r=this.m_K.Solve22(vec,bX,bY);f2r.x+=f1.x;f2r.y+=f1.y;this.m_impulse.x=f2r.x;this.m_impulse.y=f2r.y;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;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 vec=new b2Vec2;var df2=this.m_K.Solve22(vec,-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;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};b2PrismaticJoint.prototype.SolvePositionConstraints=function(){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 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=b2Mat22.FromAngle(a1);var R2=b2Mat22.FromAngle(a2);var tMat=R1;var r1X=this.m_localAnchor1.x-this.m_localCenterA.x;var r1Y=this.m_localAnchor1.y-this.m_localCenterA.y;var 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=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(b2Math.Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2Settings.b2_linearSlop){C2=b2Math.Clamp(translation,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);linearError=b2Math.Abs(translation);active=true}else if(translation<=this.m_lowerTranslation){C2=b2Math.Clamp(translation-this.m_lowerTranslation+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0);linearError=this.m_lowerTranslation-translation;active=true}else if(translation>=this.m_upperTranslation){C2=b2Math.Clamp(translation-this.m_upperTranslation+b2Settings.b2_linearSlop,0,b2Settings.b2_maxLinearCorrection);linearError=translation-this.m_upperTranslation;active=true}}this.m_perp=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=new b2Vec3(0,0,0);var C1X=this.m_perp.x*dX+this.m_perp.y*dY;var C1Y=a2-a1-this.m_refAngle;linearError=b2Math.Max(linearError,b2Math.Abs(C1X));angularError=b2Math.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 vec=new b2Vec2;var impulse1=this.m_K.Solve22(vec,-C1X,-C1Y);impulse.x=impulse1.x;impulse.y=impulse1.y;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;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<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop};$i_109.inherit(b2PrismaticJointDef,$i_109.Dynamics.Joints.b2JointDef);b2PrismaticJointDef.prototype.__super=$i_109.Dynamics.Joints.b2JointDef.prototype;b2PrismaticJointDef.b2PrismaticJointDef=function(){$i_109.Dynamics.Joints.b2JointDef.b2JointDef.apply(this,arguments);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2;this.localAxisA=new b2Vec2};b2PrismaticJointDef.prototype.b2PrismaticJointDef=function(){this.__super.b2JointDef.call(this);this.type=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};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()};$i_109.inherit(b2PulleyJoint,$i_109.Dynamics.Joints.b2Joint);b2PulleyJoint.prototype.__super=$i_109.Dynamics.Joints.b2Joint.prototype;b2PulleyJoint.b2PulleyJoint=function(){$i_109.Dynamics.Joints.b2Joint.b2Joint.apply(this,arguments);this.m_groundAnchor1=new b2Vec2;this.m_groundAnchor2=new b2Vec2;this.m_localAnchor1=new b2Vec2;this.m_localAnchor2=new b2Vec2;this.m_u1=new b2Vec2;this.m_u2=new b2Vec2};b2PulleyJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchor1)};b2PulleyJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchor2)};b2PulleyJoint.prototype.GetReactionForce=function(inv_dt){return new b2Vec2(inv_dt*this.m_impulse*this.m_u2.x,inv_dt*this.m_impulse*this.m_u2.y)};b2PulleyJoint.prototype.GetReactionTorque=function(inv_dt){return 0};b2PulleyJoint.prototype.GetGroundAnchorA=function(){var a=this.m_ground.m_xf.position.Copy();a.Add(this.m_groundAnchor1);return a};b2PulleyJoint.prototype.GetGroundAnchorB=function(){var a=this.m_ground.m_xf.position.Copy();a.Add(this.m_groundAnchor2);return a};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)};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)};b2PulleyJoint.prototype.GetRatio=function(){return this.m_ratio};b2PulleyJoint.prototype.b2PulleyJoint=function(def){this.__super.b2Joint.call(this,def);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=b2Math.Min(def.maxLengthA,this.m_constant-this.m_ratio*b2PulleyJoint.b2_minPulleyLength);this.m_maxLength2=b2Math.Min(def.maxLengthB,(this.m_constant-b2PulleyJoint.b2_minPulleyLength)/this.m_ratio);this.m_impulse=0;this.m_limitImpulse1=0;this.m_limitImpulse2=0};b2PulleyJoint.prototype.InitVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var 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>b2Settings.b2_linearSlop){this.m_u1.Multiply(1/length1)}else{this.m_u1.SetZero()}if(length2>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>0){this.m_state=b2Joint.e_inactiveLimit;this.m_impulse=0}else{this.m_state=b2Joint.e_atUpperLimit}if(length1b2Settings.b2_linearSlop){this.m_u1.Multiply(1/length1)}else{this.m_u1.SetZero()}if(length2>b2Settings.b2_linearSlop){this.m_u2.Multiply(1/length2)}else{this.m_u2.SetZero()}C=this.m_constant-length1-this.m_ratio*length2;linearError=b2Math.Max(linearError,-C);C=b2Math.Clamp(C+b2Settings.b2_linearSlop,-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===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>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=b2Math.Max(linearError,-C);C=b2Math.Clamp(C+b2Settings.b2_linearSlop,-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===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>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=b2Math.Max(linearError,-C);C=b2Math.Clamp(C+b2Settings.b2_linearSlop,-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=this.m_upperAngle){if(this.m_limitState!==b2Joint.e_atUpperLimit){this.m_impulse.z=0}this.m_limitState=b2Joint.e_atUpperLimit}else{this.m_limitState=b2Joint.e_inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=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}};b2RevoluteJoint.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 m1=bA.m_invMass;var m2=bB.m_invMass;var i1=bA.m_invI;var i2=bB.m_invI;if(this.m_enableMotor&&this.m_limitState!==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=b2Math.Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;w1-=i1*impulse;w2+=i2*impulse}if(this.m_enableLimit&&this.m_limitState!==b2Joint.e_inactiveLimit){var 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 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===b2Joint.e_equalLimits){this.m_impulse.Add(this.impulse3)}else if(this.m_limitState===b2Joint.e_atLowerLimit){var newImpulse=this.m_impulse.z+this.impulse3.z;if(newImpulse<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===b2Joint.e_atUpperLimit){var newImpulse=this.m_impulse.z+this.impulse3.z;if(newImpulse>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{var 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 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};b2RevoluteJoint.prototype.SolvePositionConstraints=function(){var C=0;var bA=this.m_bodyA;var bB=this.m_bodyB;var angularError=0;if(this.m_enableLimit&&this.m_limitState!==b2Joint.e_inactiveLimit){var angle=bB.m_sweep.a-bA.m_sweep.a-this.m_referenceAngle;var limitImpulse=0;if(this.m_limitState===b2Joint.e_equalLimits){C=b2Math.Clamp(angle-this.m_lowerAngle,-b2Settings.b2_maxAngularCorrection,b2Settings.b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C;angularError=b2Math.Abs(C)}else if(this.m_limitState===b2Joint.e_atLowerLimit){C=angle-this.m_lowerAngle;angularError=-C;C=b2Math.Clamp(C+b2Settings.b2_angularSlop,-b2Settings.b2_maxAngularCorrection,0);limitImpulse=-this.m_motorMass*C}else if(this.m_limitState===b2Joint.e_atUpperLimit){C=angle-this.m_upperAngle;angularError=C;C=b2Math.Clamp(C-b2Settings.b2_angularSlop,0,b2Settings.b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C}bA.m_sweep.a-=bA.m_invI*limitImpulse;bB.m_sweep.a+=bB.m_invI*limitImpulse}{var 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 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 invMass1=bA.m_invMass;var invMass2=bB.m_invMass;var invI1=bA.m_invI;var invI2=bB.m_invI;var k_allowedStretch=10*b2Settings.b2_linearSlop;var impulseX,impulseY;if(CLengthSquared>k_allowedStretch*k_allowedStretch){var m=1/(invMass1+invMass2);impulseX=m*-CX;impulseY=m*-CY;bA.m_sweep.c.x-=0.5*invMass1*impulseX;bA.m_sweep.c.y-=0.5*invMass1*impulseY;bB.m_sweep.c.x+=0.5*invMass2*impulseX;bB.m_sweep.c.y+=0.5*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}var k=this.K;k.col1.x=invMass1+invMass2+invI1*r1Y*r1Y+invI2*r2Y*r2Y;k.col1.y=-invI1*r1X*r1Y+-invI2*r2X*r2Y;k.col2.x=k.col1.y;k.col2.y=invMass1+invMass2+invI1*r1X*r1X+invI2*r2X*r2X;k.Solve(b2RevoluteJoint.tImpulse,-CX,-CY);impulseX=b2RevoluteJoint.tImpulse.x;impulseY=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 CLengthSquared<=b2Settings.b2_linearSlop*b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop};$i_109.postDefs.push(function(){$i_109.Dynamics.Joints.b2RevoluteJoint.tImpulse=new b2Vec2});$i_109.inherit(b2RevoluteJointDef,$i_109.Dynamics.Joints.b2JointDef);b2RevoluteJointDef.prototype.__super=$i_109.Dynamics.Joints.b2JointDef.prototype;b2RevoluteJointDef.prototype.b2RevoluteJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_revoluteJoint;this.localAnchorA.Set(0,0);this.localAnchorB.Set(0,0);this.referenceAngle=0;this.lowerAngle=0;this.upperAngle=0;this.maxMotorTorque=0;this.motorSpeed=0;this.enableLimit=false;this.enableMotor=false};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()};$i_109.inherit(b2WeldJoint,$i_109.Dynamics.Joints.b2Joint);b2RevoluteJointDef.prototype.__super=$i_109.Dynamics.Joints.b2JointDef.prototype;b2RevoluteJointDef.prototype.b2RevoluteJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_revoluteJoint;this.localAnchorA.Set(0,0);this.localAnchorB.Set(0,0);this.referenceAngle=0;this.lowerAngle=0;this.upperAngle=0;this.maxMotorTorque=0;this.motorSpeed=0;this.enableLimit=false;this.enableMotor=false};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()};$i_109.inherit(b2WeldJoint,$i_109.Dynamics.Joints.b2Joint);b2WeldJoint.prototype.__super=$i_109.Dynamics.Joints.b2Joint.prototype;b2WeldJoint.prototype.GetAnchorA=function(){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA)};b2WeldJoint.prototype.GetAnchorB=function(){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB)};b2WeldJoint.prototype.GetReactionForce=function(inv_dt){return new b2Vec2(inv_dt*this.m_impulse.x,inv_dt*this.m_impulse.y)};b2WeldJoint.prototype.GetReactionTorque=function(inv_dt){return inv_dt*this.m_impulse.z};b2WeldJoint.prototype.b2WeldJoint=function(def){this.__super.b2Joint.call(this,def);this.m_localAnchorA.SetV(def.localAnchorA);this.m_localAnchorB.SetV(def.localAnchorB);this.m_referenceAngle=def.referenceAngle;this.m_impulse.SetZero();this.m_mass=new b2Mat33};b2WeldJoint.prototype.InitVelocityConstraints=function(step){var bA=this.m_bodyA;var bB=this.m_bodyB;var 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;var 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()}};b2WeldJoint.prototype.SolveVelocityConstraints=function(){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;var 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;var 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=new b2Vec3(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);bA.m_angularVelocity=wA;bB.m_angularVelocity=wB};b2WeldJoint.prototype.SolvePositionConstraints=function(){var bA=this.m_bodyA;var bB=this.m_bodyB;var 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;var 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*b2Settings.b2_linearSlop;var positionError=C1X*C1X+C1Y*C1Y;var angularError=b2Math.Abs(C2);if(positionError>k_allowedStretch*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=new b2Vec3(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);bA.SynchronizeTransform();bB.SynchronizeTransform();return positionError<=b2Settings.b2_linearSlop*b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop};$i_109.inherit(b2WeldJointDef,$i_109.Dynamics.Joints.b2JointDef);b2WeldJointDef.prototype.__super=$i_109.Dynamics.Joints.b2JointDef.prototype;b2WeldJointDef.prototype.b2WeldJointDef=function(){this.__super.b2JointDef.call(this);this.type=b2Joint.e_weldJoint;this.referenceAngle=0};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()}})();(function(){var b2DebugDraw=$i_109.Dynamics.b2DebugDraw;b2DebugDraw.b2DebugDraw=function(){this.m_drawScale=1;this.m_lineThickness=1;this.m_alpha=1;this.m_fillAlpha=1;this.m_xformScale=1;var __this=this;this.m_sprite={graphics:{clear:function(){__this.m_ctx.clearRect(0,0,__this.m_ctx.canvas.width,__this.m_ctx.canvas.height)}}}};b2DebugDraw.prototype._color=function(color,alpha){return`rgba(${(color&16711680)>>16},${(color&65280)>>8},${color&255},${alpha})`};b2DebugDraw.prototype.b2DebugDraw=function(){this.m_drawFlags=0};b2DebugDraw.prototype.SetFlags=function(flags){if(flags===undefined)flags=0;this.m_drawFlags=flags};b2DebugDraw.prototype.GetFlags=function(){return this.m_drawFlags};b2DebugDraw.prototype.AppendFlags=function(flags){if(flags===undefined)flags=0;this.m_drawFlags|=flags};b2DebugDraw.prototype.ClearFlags=function(flags){if(flags===undefined)flags=0;this.m_drawFlags&=~flags};b2DebugDraw.prototype.SetSprite=function(sprite){this.m_ctx=sprite};b2DebugDraw.prototype.GetSprite=function(){return this.m_ctx};b2DebugDraw.prototype.SetDrawScale=function(drawScale){if(drawScale===undefined)drawScale=0;this.m_drawScale=drawScale};b2DebugDraw.prototype.GetDrawScale=function(){return this.m_drawScale};b2DebugDraw.prototype.SetLineThickness=function(lineThickness){if(lineThickness===undefined)lineThickness=0;this.m_lineThickness=lineThickness;this.m_ctx.strokeWidth=lineThickness};b2DebugDraw.prototype.GetLineThickness=function(){return this.m_lineThickness};b2DebugDraw.prototype.SetAlpha=function(alpha){if(alpha===undefined)alpha=0;this.m_alpha=alpha};b2DebugDraw.prototype.GetAlpha=function(){return this.m_alpha};b2DebugDraw.prototype.SetFillAlpha=function(alpha){if(alpha===undefined)alpha=0;this.m_fillAlpha=alpha};b2DebugDraw.prototype.GetFillAlpha=function(){return this.m_fillAlpha};b2DebugDraw.prototype.SetXFormScale=function(xformScale){if(xformScale===undefined)xformScale=0;this.m_xformScale=xformScale};b2DebugDraw.prototype.GetXFormScale=function(){return this.m_xformScale};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.color,this.m_alpha);s.moveTo(vertices[0].x*drawScale,vertices[0].y*drawScale);for(var i=1;ihi?hi:a}function b2Swap(a,b){const tmp=a[0];a[0]=b[0];b[0]=tmp}const b2IsValid=isFinite;function b2Sq(n){return n*n}function b2InvSqrt(n){return 1/Math.sqrt(n)}const b2Sqrt=Math.sqrt;const b2Pow=Math.pow;function b2DegToRad(degrees){return degrees*b2_pi_over_180}function b2RadToDeg(radians){return radians*b2_180_over_pi}const b2Cos=Math.cos;const b2Sin=Math.sin;const b2Acos=Math.acos;const b2Asin=Math.asin;const b2Atan2=Math.atan2;function b2NextPowerOfTwo(x){x|=x>>1&2147483647;x|=x>>2&1073741823;x|=x>>4&268435455;x|=x>>8&16777215;x|=x>>16&65535;return x+1}function b2IsPowerOfTwo(x){return x>0&&(x&x-1)===0}function b2Random(){return Math.random()*2-1}function b2RandomRange(lo,hi){return(hi-lo)*Math.random()+lo}class b2Vec2{constructor(x=0,y=0){this.x=x;this.y=y}Clone(){return new b2Vec2(this.x,this.y)}SetZero(){this.x=0;this.y=0;return this}Set(x,y){this.x=x;this.y=y;return this}Copy(other){this.x=other.x;this.y=other.y;return this}SelfAdd(v){this.x+=v.x;this.y+=v.y;return this}SelfAddXY(x,y){this.x+=x;this.y+=y;return this}SelfSub(v){this.x-=v.x;this.y-=v.y;return this}SelfSubXY(x,y){this.x-=x;this.y-=y;return this}SelfMul(s){this.x*=s;this.y*=s;return this}SelfMulAdd(s,v){this.x+=s*v.x;this.y+=s*v.y;return this}SelfMulSub(s,v){this.x-=s*v.x;this.y-=s*v.y;return this}Dot(v){return this.x*v.x+this.y*v.y}Cross(v){return this.x*v.y-this.y*v.x}Length(){const x=this.x;const y=this.y;return Math.sqrt(x*x+y*y)}LengthSquared(){const x=this.x;const y=this.y;return x*x+y*y}Normalize(){const length=this.Length();if(length>=b2_epsilon){const inv_length=1/length;this.x*=inv_length;this.y*=inv_length}return length}SelfNormalize(){const length=this.Length();if(length>=b2_epsilon){const inv_length=1/length;this.x*=inv_length;this.y*=inv_length}return this}SelfRotate(radians){const c=Math.cos(radians);const s=Math.sin(radians);const x=this.x;this.x=c*x-s*this.y;this.y=s*x+c*this.y;return this}IsValid(){return isFinite(this.x)&&isFinite(this.y)}SelfCrossVS(s){const x=this.x;this.x=s*this.y;this.y=-s*x;return this}SelfCrossSV(s){const x=this.x;this.x=-s*this.y;this.y=s*x;return this}SelfMinV(v){this.x=b2Min(this.x,v.x);this.y=b2Min(this.y,v.y);return this}SelfMaxV(v){this.x=b2Max(this.x,v.x);this.y=b2Max(this.y,v.y);return this}SelfAbs(){this.x=b2Abs(this.x);this.y=b2Abs(this.y);return this}SelfNeg(){this.x=-this.x;this.y=-this.y;return this}SelfSkew(){const x=this.x;this.x=-this.y;this.y=x;return this}static MakeArray(length){return b2MakeArray(length,i=>new b2Vec2)}static AbsV(v,out){out.x=b2Abs(v.x);out.y=b2Abs(v.y);return out}static MinV(a,b,out){out.x=b2Min(a.x,b.x);out.y=b2Min(a.y,b.y);return out}static MaxV(a,b,out){out.x=b2Max(a.x,b.x);out.y=b2Max(a.y,b.y);return out}static ClampV(v,lo,hi,out){out.x=b2Clamp(v.x,lo.x,hi.x);out.y=b2Clamp(v.y,lo.y,hi.y);return out}static RotateV(v,radians,out){const v_x=v.x;const v_y=v.y;const c=Math.cos(radians);const s=Math.sin(radians);out.x=c*v_x-s*v_y;out.y=s*v_x+c*v_y;return out}static DotVV(a,b){return a.x*b.x+a.y*b.y}static CrossVV(a,b){return a.x*b.y-a.y*b.x}static CrossVS(v,s,out){const v_x=v.x;out.x=s*v.y;out.y=-s*v_x;return out}static CrossVOne(v,out){const v_x=v.x;out.x=v.y;out.y=-v_x;return out}static CrossSV(s,v,out){const v_x=v.x;out.x=-s*v.y;out.y=s*v_x;return out}static CrossOneV(v,out){const v_x=v.x;out.x=-v.y;out.y=v_x;return out}static AddVV(a,b,out){out.x=a.x+b.x;out.y=a.y+b.y;return out}static SubVV(a,b,out){out.x=a.x-b.x;out.y=a.y-b.y;return out}static MulSV(s,v,out){out.x=v.x*s;out.y=v.y*s;return out}static MulVS(v,s,out){out.x=v.x*s;out.y=v.y*s;return out}static AddVMulSV(a,s,b,out){out.x=a.x+s*b.x;out.y=a.y+s*b.y;return out}static SubVMulSV(a,s,b,out){out.x=a.x-s*b.x;out.y=a.y-s*b.y;return out}static AddVCrossSV(a,s,v,out){const v_x=v.x;out.x=a.x-s*v.y;out.y=a.y+s*v_x;return out}static MidVV(a,b,out){out.x=(a.x+b.x)*0.5;out.y=(a.y+b.y)*0.5;return out}static ExtVV(a,b,out){out.x=(b.x-a.x)*0.5;out.y=(b.y-a.y)*0.5;return out}static IsEqualToV(a,b){return a.x===b.x&&a.y===b.y}static DistanceVV(a,b){const c_x=a.x-b.x;const c_y=a.y-b.y;return Math.sqrt(c_x*c_x+c_y*c_y)}static DistanceSquaredVV(a,b){const c_x=a.x-b.x;const c_y=a.y-b.y;return c_x*c_x+c_y*c_y}static NegV(v,out){out.x=-v.x;out.y=-v.y;return out}}b2Vec2.ZERO=new b2Vec2(0,0);b2Vec2.UNITX=new b2Vec2(1,0);b2Vec2.UNITY=new b2Vec2(0,1);b2Vec2.s_t0=new b2Vec2;b2Vec2.s_t1=new b2Vec2;b2Vec2.s_t2=new b2Vec2;b2Vec2.s_t3=new b2Vec2;const b2Vec2_zero=new b2Vec2(0,0);class b2Vec3{constructor(x=0,y=0,z=0){this.x=x;this.y=y;this.z=z}Clone(){return new b2Vec3(this.x,this.y,this.z)}SetZero(){this.x=0;this.y=0;this.z=0;return this}SetXYZ(x,y,z){this.x=x;this.y=y;this.z=z;return this}Copy(other){this.x=other.x;this.y=other.y;this.z=other.z;return this}SelfNeg(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this}SelfAdd(v){this.x+=v.x;this.y+=v.y;this.z+=v.z;return this}SelfAddXYZ(x,y,z){this.x+=x;this.y+=y;this.z+=z;return this}SelfSub(v){this.x-=v.x;this.y-=v.y;this.z-=v.z;return this}SelfSubXYZ(x,y,z){this.x-=x;this.y-=y;this.z-=z;return this}SelfMul(s){this.x*=s;this.y*=s;this.z*=s;return this}static DotV3V3(a,b){return a.x*b.x+a.y*b.y+a.z*b.z}static CrossV3V3(a,b,out){const a_x=a.x;const a_y=a.y;const a_z=a.z;const b_x=b.x;const b_y=b.y;const b_z=b.z;out.x=a_y*b_z-a_z*b_y;out.y=a_z*b_x-a_x*b_z;out.z=a_x*b_y-a_y*b_x;return out}}b2Vec3.ZERO=new b2Vec3(0,0,0);b2Vec3.s_t0=new b2Vec3;class b2Mat22{constructor(){this.ex=new b2Vec2(1,0);this.ey=new b2Vec2(0,1)}Clone(){return new b2Mat22().Copy(this)}static FromVV(c1,c2){return new b2Mat22().SetVV(c1,c2)}static FromSSSS(r1c1,r1c2,r2c1,r2c2){return new b2Mat22().SetSSSS(r1c1,r1c2,r2c1,r2c2)}static FromAngle(radians){return new b2Mat22().SetAngle(radians)}SetSSSS(r1c1,r1c2,r2c1,r2c2){this.ex.Set(r1c1,r2c1);this.ey.Set(r1c2,r2c2);return this}SetVV(c1,c2){this.ex.Copy(c1);this.ey.Copy(c2);return this}SetAngle(radians){const c=Math.cos(radians);const s=Math.sin(radians);this.ex.Set(c,s);this.ey.Set(-s,c);return this}Copy(other){this.ex.Copy(other.ex);this.ey.Copy(other.ey);return this}SetIdentity(){this.ex.Set(1,0);this.ey.Set(0,1);return this}SetZero(){this.ex.SetZero();this.ey.SetZero();return this}GetAngle(){return Math.atan2(this.ex.y,this.ex.x)}GetInverse(out){const a=this.ex.x;const b=this.ey.x;const c=this.ex.y;const d=this.ey.y;let det=a*d-b*c;if(det!==0){det=1/det}out.ex.x=det*d;out.ey.x=-det*b;out.ex.y=-det*c;out.ey.y=det*a;return out}Solve(b_x,b_y,out){const a11=this.ex.x;const a12=this.ey.x;const a21=this.ex.y;const a22=this.ey.y;let det=a11*a22-a12*a21;if(det!==0){det=1/det}out.x=det*(a22*b_x-a12*b_y);out.y=det*(a11*b_y-a21*b_x);return out}SelfAbs(){this.ex.SelfAbs();this.ey.SelfAbs();return this}SelfInv(){this.GetInverse(this);return this}SelfAddM(M){this.ex.SelfAdd(M.ex);this.ey.SelfAdd(M.ey);return this}SelfSubM(M){this.ex.SelfSub(M.ex);this.ey.SelfSub(M.ey);return this}static AbsM(M,out){const M_ex=M.ex;const M_ey=M.ey;out.ex.x=b2Abs(M_ex.x);out.ex.y=b2Abs(M_ex.y);out.ey.x=b2Abs(M_ey.x);out.ey.y=b2Abs(M_ey.y);return out}static MulMV(M,v,out){const M_ex=M.ex;const M_ey=M.ey;const v_x=v.x;const v_y=v.y;out.x=M_ex.x*v_x+M_ey.x*v_y;out.y=M_ex.y*v_x+M_ey.y*v_y;return out}static MulTMV(M,v,out){const M_ex=M.ex;const M_ey=M.ey;const v_x=v.x;const v_y=v.y;out.x=M_ex.x*v_x+M_ex.y*v_y;out.y=M_ey.x*v_x+M_ey.y*v_y;return out}static AddMM(A,B,out){const A_ex=A.ex;const A_ey=A.ey;const B_ex=B.ex;const B_ey=B.ey;out.ex.x=A_ex.x+B_ex.x;out.ex.y=A_ex.y+B_ex.y;out.ey.x=A_ey.x+B_ey.x;out.ey.y=A_ey.y+B_ey.y;return out}static MulMM(A,B,out){const A_ex_x=A.ex.x;const A_ex_y=A.ex.y;const A_ey_x=A.ey.x;const A_ey_y=A.ey.y;const B_ex_x=B.ex.x;const B_ex_y=B.ex.y;const B_ey_x=B.ey.x;const B_ey_y=B.ey.y;out.ex.x=A_ex_x*B_ex_x+A_ey_x*B_ex_y;out.ex.y=A_ex_y*B_ex_x+A_ey_y*B_ex_y;out.ey.x=A_ex_x*B_ey_x+A_ey_x*B_ey_y;out.ey.y=A_ex_y*B_ey_x+A_ey_y*B_ey_y;return out}static MulTMM(A,B,out){const A_ex_x=A.ex.x;const A_ex_y=A.ex.y;const A_ey_x=A.ey.x;const A_ey_y=A.ey.y;const B_ex_x=B.ex.x;const B_ex_y=B.ex.y;const B_ey_x=B.ey.x;const B_ey_y=B.ey.y;out.ex.x=A_ex_x*B_ex_x+A_ex_y*B_ex_y;out.ex.y=A_ey_x*B_ex_x+A_ey_y*B_ex_y;out.ey.x=A_ex_x*B_ey_x+A_ex_y*B_ey_y;out.ey.y=A_ey_x*B_ey_x+A_ey_y*B_ey_y;return out}}b2Mat22.IDENTITY=new b2Mat22;class b2Mat33{constructor(){this.ex=new b2Vec3(1,0,0);this.ey=new b2Vec3(0,1,0);this.ez=new b2Vec3(0,0,1)}Clone(){return new b2Mat33().Copy(this)}SetVVV(c1,c2,c3){this.ex.Copy(c1);this.ey.Copy(c2);this.ez.Copy(c3);return this}Copy(other){this.ex.Copy(other.ex);this.ey.Copy(other.ey);this.ez.Copy(other.ez);return this}SetIdentity(){this.ex.SetXYZ(1,0,0);this.ey.SetXYZ(0,1,0);this.ez.SetXYZ(0,0,1);return this}SetZero(){this.ex.SetZero();this.ey.SetZero();this.ez.SetZero();return this}SelfAddM(M){this.ex.SelfAdd(M.ex);this.ey.SelfAdd(M.ey);this.ez.SelfAdd(M.ez);return this}Solve33(b_x,b_y,b_z,out){const a11=this.ex.x;const a21=this.ex.y;const a31=this.ex.z;const a12=this.ey.x;const a22=this.ey.y;const a32=this.ey.z;const a13=this.ez.x;const a23=this.ez.y;const a33=this.ez.z;let 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*(b_x*(a22*a33-a32*a23)+b_y*(a32*a13-a12*a33)+b_z*(a12*a23-a22*a13));out.y=det*(a11*(b_y*a33-b_z*a23)+a21*(b_z*a13-b_x*a33)+a31*(b_x*a23-b_y*a13));out.z=det*(a11*(a22*b_z-a32*b_y)+a21*(a32*b_x-a12*b_z)+a31*(a12*b_y-a22*b_x));return out}Solve22(b_x,b_y,out){const a11=this.ex.x;const a12=this.ey.x;const a21=this.ex.y;const a22=this.ey.y;let det=a11*a22-a12*a21;if(det!==0){det=1/det}out.x=det*(a22*b_x-a12*b_y);out.y=det*(a11*b_y-a21*b_x);return out}GetInverse22(M){const a=this.ex.x;const b=this.ey.x;const c=this.ex.y;const d=this.ey.y;let det=a*d-b*c;if(det!==0){det=1/det}M.ex.x=det*d;M.ey.x=-det*b;M.ex.z=0;M.ex.y=-det*c;M.ey.y=det*a;M.ey.z=0;M.ez.x=0;M.ez.y=0;M.ez.z=0}GetSymInverse33(M){let det=b2Vec3.DotV3V3(this.ex,b2Vec3.CrossV3V3(this.ey,this.ez,b2Vec3.s_t0));if(det!==0){det=1/det}const a11=this.ex.x;const a12=this.ey.x;const a13=this.ez.x;const a22=this.ey.y;const a23=this.ez.y;const a33=this.ez.z;M.ex.x=det*(a22*a33-a23*a23);M.ex.y=det*(a13*a23-a12*a33);M.ex.z=det*(a12*a23-a13*a22);M.ey.x=M.ex.y;M.ey.y=det*(a11*a33-a13*a13);M.ey.z=det*(a13*a12-a11*a23);M.ez.x=M.ex.z;M.ez.y=M.ey.z;M.ez.z=det*(a11*a22-a12*a12)}static MulM33V3(A,v,out){const v_x=v.x;const v_y=v.y;const v_z=v.z;out.x=A.ex.x*v_x+A.ey.x*v_y+A.ez.x*v_z;out.y=A.ex.y*v_x+A.ey.y*v_y+A.ez.y*v_z;out.z=A.ex.z*v_x+A.ey.z*v_y+A.ez.z*v_z;return out}static MulM33XYZ(A,x,y,z,out){out.x=A.ex.x*x+A.ey.x*y+A.ez.x*z;out.y=A.ex.y*x+A.ey.y*y+A.ez.y*z;out.z=A.ex.z*x+A.ey.z*y+A.ez.z*z;return out}static MulM33V2(A,v,out){const v_x=v.x;const v_y=v.y;out.x=A.ex.x*v_x+A.ey.x*v_y;out.y=A.ex.y*v_x+A.ey.y*v_y;return out}static MulM33XY(A,x,y,out){out.x=A.ex.x*x+A.ey.x*y;out.y=A.ex.y*x+A.ey.y*y;return out}}b2Mat33.IDENTITY=new b2Mat33;class b2Rot{constructor(angle=0){this.s=0;this.c=1;if(angle){this.s=Math.sin(angle);this.c=Math.cos(angle)}}Clone(){return new b2Rot().Copy(this)}Copy(other){this.s=other.s;this.c=other.c;return this}SetAngle(angle){this.s=Math.sin(angle);this.c=Math.cos(angle);return this}SetIdentity(){this.s=0;this.c=1;return this}GetAngle(){return Math.atan2(this.s,this.c)}GetXAxis(out){out.x=this.c;out.y=this.s;return out}GetYAxis(out){out.x=-this.s;out.y=this.c;return out}static MulRR(q,r,out){const q_c=q.c;const q_s=q.s;const r_c=r.c;const r_s=r.s;out.s=q_s*r_c+q_c*r_s;out.c=q_c*r_c-q_s*r_s;return out}static MulTRR(q,r,out){const q_c=q.c;const q_s=q.s;const r_c=r.c;const r_s=r.s;out.s=q_c*r_s-q_s*r_c;out.c=q_c*r_c+q_s*r_s;return out}static MulRV(q,v,out){const q_c=q.c;const q_s=q.s;const v_x=v.x;const v_y=v.y;out.x=q_c*v_x-q_s*v_y;out.y=q_s*v_x+q_c*v_y;return out}static MulTRV(q,v,out){const q_c=q.c;const q_s=q.s;const v_x=v.x;const v_y=v.y;out.x=q_c*v_x+q_s*v_y;out.y=-q_s*v_x+q_c*v_y;return out}}b2Rot.IDENTITY=new b2Rot;class b2Transform{constructor(){this.p=new b2Vec2;this.q=new b2Rot}Clone(){return new b2Transform().Copy(this)}Copy(other){this.p.Copy(other.p);this.q.Copy(other.q);return this}SetIdentity(){this.p.SetZero();this.q.SetIdentity();return this}SetPositionRotation(position,q){this.p.Copy(position);this.q.Copy(q);return this}SetPositionAngle(pos,a){this.p.Copy(pos);this.q.SetAngle(a);return this}SetPosition(position){this.p.Copy(position);return this}SetPositionXY(x,y){this.p.Set(x,y);return this}SetRotation(rotation){this.q.Copy(rotation);return this}SetRotationAngle(radians){this.q.SetAngle(radians);return this}GetPosition(){return this.p}GetRotation(){return this.q}GetRotationAngle(){return this.q.GetAngle()}GetAngle(){return this.q.GetAngle()}static MulXV(T,v,out){const T_q_c=T.q.c;const T_q_s=T.q.s;const v_x=v.x;const v_y=v.y;out.x=T_q_c*v_x-T_q_s*v_y+T.p.x;out.y=T_q_s*v_x+T_q_c*v_y+T.p.y;return out}static MulTXV(T,v,out){const T_q_c=T.q.c;const T_q_s=T.q.s;const p_x=v.x-T.p.x;const p_y=v.y-T.p.y;out.x=T_q_c*p_x+T_q_s*p_y;out.y=-T_q_s*p_x+T_q_c*p_y;return out}static MulXX(A,B,out){b2Rot.MulRR(A.q,B.q,out.q);b2Vec2.AddVV(b2Rot.MulRV(A.q,B.p,out.p),A.p,out.p);return out}static MulTXX(A,B,out){b2Rot.MulTRR(A.q,B.q,out.q);b2Rot.MulTRV(A.q,b2Vec2.SubVV(B.p,A.p,out.p),out.p);return out}}b2Transform.IDENTITY=new b2Transform;class b2Sweep{constructor(){this.localCenter=new b2Vec2;this.c0=new b2Vec2;this.c=new b2Vec2;this.a0=0;this.a=0;this.alpha0=0}Clone(){return new b2Sweep().Copy(this)}Copy(other){this.localCenter.Copy(other.localCenter);this.c0.Copy(other.c0);this.c.Copy(other.c);this.a0=other.a0;this.a=other.a;this.alpha0=other.alpha0;return this}GetTransform(xf,beta){const one_minus_beta=1-beta;xf.p.x=one_minus_beta*this.c0.x+beta*this.c.x;xf.p.y=one_minus_beta*this.c0.y+beta*this.c.y;const angle=one_minus_beta*this.a0+beta*this.a;xf.q.SetAngle(angle);xf.p.SelfSub(b2Rot.MulRV(xf.q,this.localCenter,b2Vec2.s_t0));return xf}Advance(alpha){const beta=(alpha-this.alpha0)/(1-this.alpha0);const one_minus_beta=1-beta;this.c0.x=one_minus_beta*this.c0.x+beta*this.c.x;this.c0.y=one_minus_beta*this.c0.y+beta*this.c.y;this.a0=one_minus_beta*this.a0+beta*this.a;this.alpha0=alpha}Normalize(){const d=b2_two_pi*Math.floor(this.a0/b2_two_pi);this.a0-=d;this.a-=d}}class b2Color{constructor(rr=0.5,gg=0.5,bb=0.5,aa=1){this.r=rr;this.g=gg;this.b=bb;this.a=aa}Clone(){return new b2Color().Copy(this)}Copy(other){this.r=other.r;this.g=other.g;this.b=other.b;this.a=other.a;return this}IsEqual(color){return this.r===color.r&&this.g===color.g&&this.b===color.b&&this.a===color.a}IsZero(){return this.r===0&&this.g===0&&this.b===0&&this.a===0}Set(r,g,b,a=this.a){this.SetRGBA(r,g,b,a)}SetByteRGB(r,g,b){this.r=r/255;this.g=g/255;this.b=b/255;return this}SetByteRGBA(r,g,b,a){this.r=r/255;this.g=g/255;this.b=b/255;this.a=a/255;return this}SetRGB(rr,gg,bb){this.r=rr;this.g=gg;this.b=bb;return this}SetRGBA(rr,gg,bb,aa){this.r=rr;this.g=gg;this.b=bb;this.a=aa;return this}SelfAdd(color){this.r+=color.r;this.g+=color.g;this.b+=color.b;this.a+=color.a;return this}Add(color,out){out.r=this.r+color.r;out.g=this.g+color.g;out.b=this.b+color.b;out.a=this.a+color.a;return out}SelfSub(color){this.r-=color.r;this.g-=color.g;this.b-=color.b;this.a-=color.a;return this}Sub(color,out){out.r=this.r-color.r;out.g=this.g-color.g;out.b=this.b-color.b;out.a=this.a-color.a;return out}SelfMul(s){this.r*=s;this.g*=s;this.b*=s;this.a*=s;return this}Mul(s,out){out.r=this.r*s;out.g=this.g*s;out.b=this.b*s;out.a=this.a*s;return out}Mix(mixColor,strength){b2Color.MixColors(this,mixColor,strength)}static MixColors(colorA,colorB,strength){const dr=strength*(colorB.r-colorA.r);const dg=strength*(colorB.g-colorA.g);const db=strength*(colorB.b-colorA.b);const da=strength*(colorB.a-colorA.a);colorA.r+=dr;colorA.g+=dg;colorA.b+=db;colorA.a+=da;colorB.r-=dr;colorB.g-=dg;colorB.b-=db;colorB.a-=da}MakeStyleString(alpha=this.a){return b2Color.MakeStyleString(this.r,this.g,this.b,alpha)}static MakeStyleString(r,g,b,a=1){r*=255;g*=255;b*=255;if(a<1){return`rgba(${r},${g},${b},${a})`}else{return`rgb(${r},${g},${b})`}}}b2Color.ZERO=new b2Color(0,0,0,0);b2Color.RED=new b2Color(1,0,0);b2Color.GREEN=new b2Color(0,1,0);b2Color.BLUE=new b2Color(0,0,1);(function(b2DrawFlags){b2DrawFlags[b2DrawFlags.e_none=0]="e_none";b2DrawFlags[b2DrawFlags.e_shapeBit=1]="e_shapeBit";b2DrawFlags[b2DrawFlags.e_jointBit=2]="e_jointBit";b2DrawFlags[b2DrawFlags.e_aabbBit=4]="e_aabbBit";b2DrawFlags[b2DrawFlags.e_pairBit=8]="e_pairBit";b2DrawFlags[b2DrawFlags.e_centerOfMassBit=16]="e_centerOfMassBit";b2DrawFlags[b2DrawFlags.e_particleBit=32]="e_particleBit";b2DrawFlags[b2DrawFlags.e_controllerBit=64]="e_controllerBit";b2DrawFlags[b2DrawFlags.e_all=63]="e_all"})(exports.b2DrawFlags||(exports.b2DrawFlags={}));class b2Draw{constructor(){this.m_drawFlags=0}SetFlags(flags){this.m_drawFlags=flags}GetFlags(){return this.m_drawFlags}AppendFlags(flags){this.m_drawFlags|=flags}ClearFlags(flags){this.m_drawFlags&=~flags}PushTransform(xf){}PopTransform(xf){}DrawPolygon(vertices,vertexCount,color){}DrawSolidPolygon(vertices,vertexCount,color){}DrawCircle(center,radius,color){}DrawSolidCircle(center,radius,axis,color){}DrawParticles(centers,radius,colors,count){}DrawSegment(p1,p2,color){}DrawTransform(xf){}}class b2Timer{constructor(){this.m_start=Date.now()}Reset(){this.m_start=Date.now();return this}GetMilliseconds(){return Date.now()-this.m_start}}class b2Counter{constructor(){this.m_count=0;this.m_min_count=0;this.m_max_count=0}GetCount(){return this.m_count}GetMinCount(){return this.m_min_count}GetMaxCount(){return this.m_max_count}ResetCount(){const count=this.m_count;this.m_count=0;return count}ResetMinCount(){this.m_min_count=0}ResetMaxCount(){this.m_max_count=0}Increment(){this.m_count++;if(this.m_max_countthis.m_count){this.m_min_count=this.m_count}}}class b2GrowableStack{constructor(N){this.m_stack=[];this.m_count=0;this.m_stack=b2MakeArray(N,index=>null);this.m_count=0}Reset(){this.m_count=0;return this}Push(element){this.m_stack[this.m_count]=element;this.m_count++}Pop(){this.m_count--;const element=this.m_stack[this.m_count];this.m_stack[this.m_count]=null;if(element===null){throw new Error}return element}GetCount(){return this.m_count}}class b2BlockAllocator{}class b2StackAllocator{}class b2DistanceProxy{constructor(){this.m_buffer=b2Vec2.MakeArray(2);this.m_vertices=this.m_buffer;this.m_count=0;this.m_radius=0}Reset(){this.m_vertices=this.m_buffer;this.m_count=0;this.m_radius=0;return this}SetShape(shape,index){shape.SetupDistanceProxy(this,index)}GetSupport(d){let bestIndex=0;let bestValue=b2Vec2.DotVV(this.m_vertices[0],d);for(let i=1;ibestValue){bestIndex=i;bestValue=value}}return bestIndex}GetSupportVertex(d){let bestIndex=0;let bestValue=b2Vec2.DotVV(this.m_vertices[0],d);for(let i=1;ibestValue){bestIndex=i;bestValue=value}}return this.m_vertices[bestIndex]}GetVertexCount(){return this.m_count}GetVertex(index){return this.m_vertices[index]}}class b2SimplexCache{constructor(){this.metric=0;this.count=0;this.indexA=[0,0,0];this.indexB=[0,0,0]}Reset(){this.metric=0;this.count=0;return this}}class b2DistanceInput{constructor(){this.proxyA=new b2DistanceProxy;this.proxyB=new b2DistanceProxy;this.transformA=new b2Transform;this.transformB=new b2Transform;this.useRadii=false}Reset(){this.proxyA.Reset();this.proxyB.Reset();this.transformA.SetIdentity();this.transformB.SetIdentity();this.useRadii=false;return this}}class b2DistanceOutput{constructor(){this.pointA=new b2Vec2;this.pointB=new b2Vec2;this.distance=0;this.iterations=0}Reset(){this.pointA.SetZero();this.pointB.SetZero();this.distance=0;this.iterations=0;return this}}exports.b2_gjkCalls=0;exports.b2_gjkIters=0;exports.b2_gjkMaxIters=0;function b2_gjk_reset(){exports.b2_gjkCalls=0;exports.b2_gjkIters=0;exports.b2_gjkMaxIters=0}class b2SimplexVertex{constructor(){this.wA=new b2Vec2;this.wB=new b2Vec2;this.w=new b2Vec2;this.a=0;this.indexA=0;this.indexB=0}Copy(other){this.wA.Copy(other.wA);this.wB.Copy(other.wB);this.w.Copy(other.w);this.a=other.a;this.indexA=other.indexA;this.indexB=other.indexB;return this}}class b2Simplex{constructor(){this.m_v1=new b2SimplexVertex;this.m_v2=new b2SimplexVertex;this.m_v3=new b2SimplexVertex;this.m_vertices=[];this.m_count=0;this.m_vertices[0]=this.m_v1;this.m_vertices[1]=this.m_v2;this.m_vertices[2]=this.m_v3}ReadCache(cache,proxyA,transformA,proxyB,transformB){this.m_count=cache.count;const vertices=this.m_vertices;for(let i=0;i1){const metric1=cache.metric;const metric2=this.GetMetric();if(metric2<0.5*metric1||2*metric10){return b2Vec2.CrossOneV(e12,out)}else{return b2Vec2.CrossVOne(e12,out)}}default:return out.SetZero();}}GetClosestPoint(out){switch(this.m_count){case 0:return out.SetZero();case 1:return out.Copy(this.m_v1.w);case 2:return out.Set(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);case 3:return out.SetZero();default:return out.SetZero();}}GetWitnessPoints(pA,pB){switch(this.m_count){case 0:break;case 1:pA.Copy(this.m_v1.wA);pB.Copy(this.m_v1.wB);break;case 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;break;case 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;break;default:break;}}GetMetric(){switch(this.m_count){case 0:return 0;case 1:return 0;case 2:return b2Vec2.DistanceVV(this.m_v1.w,this.m_v2.w);case 3:return b2Vec2.CrossVV(b2Vec2.SubVV(this.m_v2.w,this.m_v1.w,b2Vec2.s_t0),b2Vec2.SubVV(this.m_v3.w,this.m_v1.w,b2Vec2.s_t1));default:return 0;}}Solve2(){const w1=this.m_v1.w;const w2=this.m_v2.w;const e12=b2Vec2.SubVV(w2,w1,b2Simplex.s_e12);const d12_2=-b2Vec2.DotVV(w1,e12);if(d12_2<=0){this.m_v1.a=1;this.m_count=1;return}const d12_1=b2Vec2.DotVV(w2,e12);if(d12_1<=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Copy(this.m_v2);return}const 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}Solve3(){const w1=this.m_v1.w;const w2=this.m_v2.w;const w3=this.m_v3.w;const e12=b2Vec2.SubVV(w2,w1,b2Simplex.s_e12);const w1e12=b2Vec2.DotVV(w1,e12);const w2e12=b2Vec2.DotVV(w2,e12);const d12_1=w2e12;const d12_2=-w1e12;const e13=b2Vec2.SubVV(w3,w1,b2Simplex.s_e13);const w1e13=b2Vec2.DotVV(w1,e13);const w3e13=b2Vec2.DotVV(w3,e13);const d13_1=w3e13;const d13_2=-w1e13;const e23=b2Vec2.SubVV(w3,w2,b2Simplex.s_e23);const w2e23=b2Vec2.DotVV(w2,e23);const w3e23=b2Vec2.DotVV(w3,e23);const d23_1=w3e23;const d23_2=-w2e23;const n123=b2Vec2.CrossVV(e12,e13);const d123_1=n123*b2Vec2.CrossVV(w2,w3);const d123_2=n123*b2Vec2.CrossVV(w3,w1);const d123_3=n123*b2Vec2.CrossVV(w1,w2);if(d12_2<=0&&d13_2<=0){this.m_v1.a=1;this.m_count=1;return}if(d12_1>0&&d12_2>0&&d123_3<=0){const 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>0&&d13_2>0&&d123_2<=0){const 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.Copy(this.m_v3);return}if(d12_1<=0&&d23_2<=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Copy(this.m_v2);return}if(d13_1<=0&&d23_1<=0){this.m_v3.a=1;this.m_count=1;this.m_v1.Copy(this.m_v3);return}if(d23_1>0&&d23_2>0&&d123_1<=0){const 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.Copy(this.m_v3);return}const 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}}b2Simplex.s_e12=new b2Vec2;b2Simplex.s_e13=new b2Vec2;b2Simplex.s_e23=new b2Vec2;const b2Distance_s_simplex=new b2Simplex;const b2Distance_s_saveA=[0,0,0];const b2Distance_s_saveB=[0,0,0];const b2Distance_s_p=new b2Vec2;const b2Distance_s_d=new b2Vec2;const b2Distance_s_normal=new b2Vec2;const b2Distance_s_supportA=new b2Vec2;const b2Distance_s_supportB=new b2Vec2;function b2Distance(output,cache,input){++exports.b2_gjkCalls;const proxyA=input.proxyA;const proxyB=input.proxyB;const transformA=input.transformA;const transformB=input.transformB;const simplex=b2Distance_s_simplex;simplex.ReadCache(cache,proxyA,transformA,proxyB,transformB);const vertices=simplex.m_vertices;const k_maxIters=20;const saveA=b2Distance_s_saveA;const saveB=b2Distance_s_saveB;let saveCount=0;let distanceSqr1=b2_maxFloat;let distanceSqr2=distanceSqr1;let iter=0;while(iterrA+rB&&output.distance>b2_epsilon){output.distance-=rA+rB;const normal=b2Vec2.SubVV(output.pointB,output.pointA,b2Distance_s_normal);normal.Normalize();output.pointA.SelfMulAdd(rA,normal);output.pointB.SelfMulSub(rB,normal)}else{const p=b2Vec2.MidVV(output.pointA,output.pointB,b2Distance_s_p);output.pointA.Copy(p);output.pointB.Copy(p);output.distance=0}}}(function(b2ContactFeatureType){b2ContactFeatureType[b2ContactFeatureType.e_vertex=0]="e_vertex";b2ContactFeatureType[b2ContactFeatureType.e_face=1]="e_face"})(exports.b2ContactFeatureType||(exports.b2ContactFeatureType={}));class b2ContactFeature{constructor(){this._key=0;this._key_invalid=false;this._indexA=0;this._indexB=0;this._typeA=0;this._typeB=0}get key(){if(this._key_invalid){this._key_invalid=false;this._key=this._indexA|this._indexB<<8|this._typeA<<16|this._typeB<<24}return this._key}set key(value){this._key=value;this._key_invalid=false;this._indexA=this._key&255;this._indexB=this._key>>8&255;this._typeA=this._key>>16&255;this._typeB=this._key>>24&255}get indexA(){return this._indexA}set indexA(value){this._indexA=value;this._key_invalid=true}get indexB(){return this._indexB}set indexB(value){this._indexB=value;this._key_invalid=true}get typeA(){return this._typeA}set typeA(value){this._typeA=value;this._key_invalid=true}get typeB(){return this._typeB}set typeB(value){this._typeB=value;this._key_invalid=true}}class b2ContactID{constructor(){this.cf=new b2ContactFeature}Copy(o){this.key=o.key;return this}Clone(){return new b2ContactID().Copy(this)}get key(){return this.cf.key}set key(value){this.cf.key=value}}class b2ManifoldPoint{constructor(){this.localPoint=new b2Vec2;this.normalImpulse=0;this.tangentImpulse=0;this.id=new b2ContactID}static MakeArray(length){return b2MakeArray(length,i=>new b2ManifoldPoint)}Reset(){this.localPoint.SetZero();this.normalImpulse=0;this.tangentImpulse=0;this.id.key=0}Copy(o){this.localPoint.Copy(o.localPoint);this.normalImpulse=o.normalImpulse;this.tangentImpulse=o.tangentImpulse;this.id.Copy(o.id);return this}}(function(b2ManifoldType){b2ManifoldType[b2ManifoldType.e_unknown=-1]="e_unknown";b2ManifoldType[b2ManifoldType.e_circles=0]="e_circles";b2ManifoldType[b2ManifoldType.e_faceA=1]="e_faceA";b2ManifoldType[b2ManifoldType.e_faceB=2]="e_faceB"})(exports.b2ManifoldType||(exports.b2ManifoldType={}));class b2Manifold{constructor(){this.points=b2ManifoldPoint.MakeArray(b2_maxManifoldPoints);this.localNormal=new b2Vec2;this.localPoint=new b2Vec2;this.type=exports.b2ManifoldType.e_unknown;this.pointCount=0}Reset(){for(let i=0;ib2_epsilon_sq){b2Vec2.SubVV(pointB,pointA,this.normal).SelfNormalize()}const cA=b2Vec2.AddVMulSV(pointA,radiusA,this.normal,b2WorldManifold.Initialize_s_cA);const cB=b2Vec2.SubVMulSV(pointB,radiusB,this.normal,b2WorldManifold.Initialize_s_cB);b2Vec2.MidVV(cA,cB,this.points[0]);this.separations[0]=b2Vec2.DotVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),this.normal)}break;case exports.b2ManifoldType.e_faceA:{b2Rot.MulRV(xfA.q,manifold.localNormal,this.normal);const planePoint=b2Transform.MulXV(xfA,manifold.localPoint,b2WorldManifold.Initialize_s_planePoint);for(let i=0;inew b2ClipVertex)}Copy(other){this.v.Copy(other.v);this.id.Copy(other.id);return this}}class b2RayCastInput{constructor(){this.p1=new b2Vec2;this.p2=new b2Vec2;this.maxFraction=1}Copy(o){this.p1.Copy(o.p1);this.p2.Copy(o.p2);this.maxFraction=o.maxFraction;return this}}class b2RayCastOutput{constructor(){this.normal=new b2Vec2;this.fraction=0}Copy(o){this.normal.Copy(o.normal);this.fraction=o.fraction;return this}}class b2AABB{constructor(){this.lowerBound=new b2Vec2;this.upperBound=new b2Vec2;this.m_cache_center=new b2Vec2;this.m_cache_extent=new b2Vec2}Copy(o){this.lowerBound.Copy(o.lowerBound);this.upperBound.Copy(o.upperBound);return this}IsValid(){const d_x=this.upperBound.x-this.lowerBound.x;const d_y=this.upperBound.y-this.lowerBound.y;let valid=d_x>=0&&d_y>=0;valid=valid&&this.lowerBound.IsValid()&&this.upperBound.IsValid();return valid}GetCenter(){return b2Vec2.MidVV(this.lowerBound,this.upperBound,this.m_cache_center)}GetExtents(){return b2Vec2.ExtVV(this.lowerBound,this.upperBound,this.m_cache_extent)}GetPerimeter(){const wx=this.upperBound.x-this.lowerBound.x;const wy=this.upperBound.y-this.lowerBound.y;return 2*(wx+wy)}Combine1(aabb){this.lowerBound.x=b2Min(this.lowerBound.x,aabb.lowerBound.x);this.lowerBound.y=b2Min(this.lowerBound.y,aabb.lowerBound.y);this.upperBound.x=b2Max(this.upperBound.x,aabb.upperBound.x);this.upperBound.y=b2Max(this.upperBound.y,aabb.upperBound.y);return this}Combine2(aabb1,aabb2){this.lowerBound.x=b2Min(aabb1.lowerBound.x,aabb2.lowerBound.x);this.lowerBound.y=b2Min(aabb1.lowerBound.y,aabb2.lowerBound.y);this.upperBound.x=b2Max(aabb1.upperBound.x,aabb2.upperBound.x);this.upperBound.y=b2Max(aabb1.upperBound.y,aabb2.upperBound.y);return this}static Combine(aabb1,aabb2,out){out.Combine2(aabb1,aabb2);return out}Contains(aabb){let result=true;result=result&&this.lowerBound.x<=aabb.lowerBound.x;result=result&&this.lowerBound.y<=aabb.lowerBound.y;result=result&&aabb.upperBound.x<=this.upperBound.x;result=result&&aabb.upperBound.y<=this.upperBound.y;return result}RayCast(output,input){let tmin=-b2_maxFloat;let tmax=b2_maxFloat;const p_x=input.p1.x;const p_y=input.p1.y;const d_x=input.p2.x-input.p1.x;const d_y=input.p2.y-input.p1.y;const absD_x=b2Abs(d_x);const absD_y=b2Abs(d_y);const normal=output.normal;if(absD_xt2){const t3=t1;t1=t2;t2=t3;s=1}if(t1>tmin){normal.x=s;normal.y=0;tmin=t1}tmax=b2Min(tmax,t2);if(tmin>tmax){return false}}if(absD_yt2){const t3=t1;t1=t2;t2=t3;s=1}if(t1>tmin){normal.x=0;normal.y=s;tmin=t1}tmax=b2Min(tmax,t2);if(tmin>tmax){return false}}if(tmin<0||input.maxFraction0||d1_y>0){return false}if(d2_x>0||d2_y>0){return false}return true}}function b2TestOverlapAABB(a,b){const d1_x=b.lowerBound.x-a.upperBound.x;const d1_y=b.lowerBound.y-a.upperBound.y;const d2_x=a.lowerBound.x-b.upperBound.x;const d2_y=a.lowerBound.y-b.upperBound.y;if(d1_x>0||d1_y>0){return false}if(d2_x>0||d2_y>0){return false}return true}function b2ClipSegmentToLine(vOut,vIn,normal,offset,vertexIndexA){let numOut=0;const vIn0=vIn[0];const vIn1=vIn[1];const distance0=b2Vec2.DotVV(normal,vIn0.v)-offset;const distance1=b2Vec2.DotVV(normal,vIn1.v)-offset;if(distance0<=0){vOut[numOut++].Copy(vIn0)}if(distance1<=0){vOut[numOut++].Copy(vIn1)}if(distance0*distance1<0){const interp=distance0/(distance0-distance1);const v=vOut[numOut].v;v.x=vIn0.v.x+interp*(vIn1.v.x-vIn0.v.x);v.y=vIn0.v.y+interp*(vIn1.v.y-vIn0.v.y);const id=vOut[numOut].id;id.cf.indexA=vertexIndexA;id.cf.indexB=vIn0.id.cf.indexB;id.cf.typeA=exports.b2ContactFeatureType.e_vertex;id.cf.typeB=exports.b2ContactFeatureType.e_face;++numOut}return numOut}const b2TestOverlapShape_s_input=new b2DistanceInput;const b2TestOverlapShape_s_simplexCache=new b2SimplexCache;const b2TestOverlapShape_s_output=new b2DistanceOutput;function b2TestOverlapShape(shapeA,indexA,shapeB,indexB,xfA,xfB){const input=b2TestOverlapShape_s_input.Reset();input.proxyA.SetShape(shapeA,indexA);input.proxyB.SetShape(shapeB,indexB);input.transformA.Copy(xfA);input.transformB.Copy(xfB);input.useRadii=true;const simplexCache=b2TestOverlapShape_s_simplexCache.Reset();simplexCache.count=0;const output=b2TestOverlapShape_s_output.Reset();b2Distance(output,simplexCache,input);return output.distance<10*b2_epsilon}function verify(value){if(value===null){throw new Error}return value}class b2TreeNode{constructor(id=0){this.m_id=0;this.aabb=new b2AABB;this.parent=null;this.child1=null;this.child2=null;this.height=0;this.m_id=id}IsLeaf(){return this.child1===null}}class b2DynamicTree{constructor(){this.m_root=null;this.m_freeList=null;this.m_path=0;this.m_insertionCount=0;this.m_stack=new b2GrowableStack(256)}Query(aabb,callback){if(this.m_root===null){return}const stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){const node=stack.Pop();if(node.aabb.TestOverlap(aabb)){if(node.IsLeaf()){const proceed=callback(node);if(!proceed){return}}else{stack.Push(verify(node.child1));stack.Push(verify(node.child2))}}}}QueryPoint(point,callback){if(this.m_root===null){return}const stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){const node=stack.Pop();if(node.aabb.TestContain(point)){if(node.IsLeaf()){const proceed=callback(node);if(!proceed){return}}else{stack.Push(verify(node.child1));stack.Push(verify(node.child2))}}}}RayCast(input,callback){if(this.m_root===null){return}const p1=input.p1;const p2=input.p2;const r=b2Vec2.SubVV(p2,p1,b2DynamicTree.s_r);r.Normalize();const v=b2Vec2.CrossOneV(r,b2DynamicTree.s_v);const abs_v=b2Vec2.AbsV(v,b2DynamicTree.s_abs_v);let maxFraction=input.maxFraction;const segmentAABB=b2DynamicTree.s_segmentAABB;let t_x=p1.x+maxFraction*(p2.x-p1.x);let t_y=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=b2Min(p1.x,t_x);segmentAABB.lowerBound.y=b2Min(p1.y,t_y);segmentAABB.upperBound.x=b2Max(p1.x,t_x);segmentAABB.upperBound.y=b2Max(p1.y,t_y);const stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){const node=stack.Pop();if(!b2TestOverlapAABB(node.aabb,segmentAABB)){continue}const c=node.aabb.GetCenter();const h=node.aabb.GetExtents();const separation=b2Abs(b2Vec2.DotVV(v,b2Vec2.SubVV(p1,c,b2Vec2.s_t0)))-b2Vec2.DotVV(abs_v,h);if(separation>0){continue}if(node.IsLeaf()){const subInput=b2DynamicTree.s_subInput;subInput.p1.Copy(input.p1);subInput.p2.Copy(input.p2);subInput.maxFraction=maxFraction;const value=callback(subInput,node);if(value===0){return}if(value>0){maxFraction=value;t_x=p1.x+maxFraction*(p2.x-p1.x);t_y=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=b2Min(p1.x,t_x);segmentAABB.lowerBound.y=b2Min(p1.y,t_y);segmentAABB.upperBound.x=b2Max(p1.x,t_x);segmentAABB.upperBound.y=b2Max(p1.y,t_y)}}else{stack.Push(verify(node.child1));stack.Push(verify(node.child2))}}}AllocateNode(){if(this.m_freeList){const node=this.m_freeList;this.m_freeList=node.parent;node.parent=null;node.child1=null;node.child2=null;node.height=0;delete node.userData;return node}return new b2TreeNode(b2DynamicTree.s_node_id++)}FreeNode(node){node.parent=this.m_freeList;node.child1=null;node.child2=null;node.height=-1;delete node.userData;this.m_freeList=node}CreateProxy(aabb,userData){const node=this.AllocateNode();const r_x=b2_aabbExtension;const r_y=b2_aabbExtension;node.aabb.lowerBound.x=aabb.lowerBound.x-r_x;node.aabb.lowerBound.y=aabb.lowerBound.y-r_y;node.aabb.upperBound.x=aabb.upperBound.x+r_x;node.aabb.upperBound.y=aabb.upperBound.y+r_y;node.userData=userData;node.height=0;this.InsertLeaf(node);return node}DestroyProxy(proxy){this.RemoveLeaf(proxy);this.FreeNode(proxy)}MoveProxy(proxy,aabb,displacement){if(proxy.aabb.Contains(aabb)){return false}this.RemoveLeaf(proxy);const r_x=b2_aabbExtension+b2_aabbMultiplier*(displacement.x>0?displacement.x:-displacement.x);const r_y=b2_aabbExtension+b2_aabbMultiplier*(displacement.y>0?displacement.y:-displacement.y);proxy.aabb.lowerBound.x=aabb.lowerBound.x-r_x;proxy.aabb.lowerBound.y=aabb.lowerBound.y-r_y;proxy.aabb.upperBound.x=aabb.upperBound.x+r_x;proxy.aabb.upperBound.y=aabb.upperBound.y+r_y;this.InsertLeaf(proxy);return true}InsertLeaf(leaf){++this.m_insertionCount;if(this.m_root===null){this.m_root=leaf;this.m_root.parent=null;return}const leafAABB=leaf.aabb;let index=this.m_root;while(!index.IsLeaf()){const child1=verify(index.child1);const child2=verify(index.child2);const area=index.aabb.GetPerimeter();const combinedAABB=b2DynamicTree.s_combinedAABB;combinedAABB.Combine2(index.aabb,leafAABB);const combinedArea=combinedAABB.GetPerimeter();const cost=2*combinedArea;const inheritanceCost=2*(combinedArea-area);let cost1;const aabb=b2DynamicTree.s_aabb;let oldArea;let newArea;if(child1.IsLeaf()){aabb.Combine2(leafAABB,child1.aabb);cost1=aabb.GetPerimeter()+inheritanceCost}else{aabb.Combine2(leafAABB,child1.aabb);oldArea=child1.aabb.GetPerimeter();newArea=aabb.GetPerimeter();cost1=newArea-oldArea+inheritanceCost}let cost2;if(child2.IsLeaf()){aabb.Combine2(leafAABB,child2.aabb);cost2=aabb.GetPerimeter()+inheritanceCost}else{aabb.Combine2(leafAABB,child2.aabb);oldArea=child2.aabb.GetPerimeter();newArea=aabb.GetPerimeter();cost2=newArea-oldArea+inheritanceCost}if(cost1){const F=verify(C.child1);const G=verify(C.child2);C.child1=A;C.parent=A.parent;A.parent=C;if(C.parent!==null){if(C.parent.child1===A){C.parent.child1=C}else{C.parent.child2=C}}else{this.m_root=C}if(F.height>G.height){C.child2=F;A.child2=G;G.parent=A;A.aabb.Combine2(B.aabb,G.aabb);C.aabb.Combine2(A.aabb,F.aabb);A.height=1+b2Max(B.height,G.height);C.height=1+b2Max(A.height,F.height)}else{C.child2=G;A.child2=F;F.parent=A;A.aabb.Combine2(B.aabb,F.aabb);C.aabb.Combine2(A.aabb,G.aabb);A.height=1+b2Max(B.height,F.height);C.height=1+b2Max(A.height,G.height)}return C}if(balance<-1){const D=verify(B.child1);const E=verify(B.child2);B.child1=A;B.parent=A.parent;A.parent=B;if(B.parent!==null){if(B.parent.child1===A){B.parent.child1=B}else{B.parent.child2=B}}else{this.m_root=B}if(D.height>E.height){B.child2=D;A.child1=E;E.parent=A;A.aabb.Combine2(C.aabb,E.aabb);B.aabb.Combine2(A.aabb,D.aabb);A.height=1+b2Max(C.height,E.height);B.height=1+b2Max(A.height,D.height)}else{B.child2=E;A.child1=D;D.parent=A;A.aabb.Combine2(C.aabb,D.aabb);B.aabb.Combine2(A.aabb,E.aabb);A.height=1+b2Max(C.height,D.height);B.height=1+b2Max(A.height,E.height)}return B}return A}GetHeight(){if(this.m_root===null){return 0}return this.m_root.height}static GetAreaNode(node){if(node===null){return 0}if(node.IsLeaf()){return 0}let area=node.aabb.GetPerimeter();area+=b2DynamicTree.GetAreaNode(node.child1);area+=b2DynamicTree.GetAreaNode(node.child2);return area}GetAreaRatio(){if(this.m_root===null){return 0}const root=this.m_root;const rootArea=root.aabb.GetPerimeter();const totalArea=b2DynamicTree.GetAreaNode(this.m_root);return totalArea/rootArea}ComputeHeightNode(node){if(!node||node.IsLeaf()){return 0}const height1=this.ComputeHeightNode(node.child1);const height2=this.ComputeHeightNode(node.child2);return 1+b2Max(height1,height2)}ComputeHeight(){const height=this.ComputeHeightNode(this.m_root);return height}ValidateStructure(index){if(index===null){return}if(index===this.m_root);const node=index;if(node.IsLeaf()){return}const child1=verify(node.child1);const child2=verify(node.child2);this.ValidateStructure(child1);this.ValidateStructure(child2)}ValidateMetrics(index){if(index===null){return}const node=index;if(node.IsLeaf()){return}const child1=verify(node.child1);const child2=verify(node.child2);const aabb=b2DynamicTree.s_aabb;aabb.Combine2(child1.aabb,child2.aabb);this.ValidateMetrics(child1);this.ValidateMetrics(child2)}Validate(){this.ValidateStructure(this.m_root);this.ValidateMetrics(this.m_root);let freeIndex=this.m_freeList;while(freeIndex!==null){freeIndex=freeIndex.parent}}static GetMaxBalanceNode(node,maxBalance){if(node===null){return maxBalance}if(node.height<=1){return maxBalance}const child1=verify(node.child1);const child2=verify(node.child2);const balance=b2Abs(child2.height-child1.height);return b2Max(maxBalance,balance)}GetMaxBalance(){const maxBalance=b2DynamicTree.GetMaxBalanceNode(this.m_root,0);return maxBalance}RebuildBottomUp(){this.Validate()}static ShiftOriginNode(node,newOrigin){if(node===null){return}if(node.height<=1){return}const child1=node.child1;const child2=node.child2;b2DynamicTree.ShiftOriginNode(child1,newOrigin);b2DynamicTree.ShiftOriginNode(child2,newOrigin);node.aabb.lowerBound.SelfSub(newOrigin);node.aabb.upperBound.SelfSub(newOrigin)}ShiftOrigin(newOrigin){b2DynamicTree.ShiftOriginNode(this.m_root,newOrigin)}}b2DynamicTree.s_r=new b2Vec2;b2DynamicTree.s_v=new b2Vec2;b2DynamicTree.s_abs_v=new b2Vec2;b2DynamicTree.s_segmentAABB=new b2AABB;b2DynamicTree.s_subInput=new b2RayCastInput;b2DynamicTree.s_combinedAABB=new b2AABB;b2DynamicTree.s_aabb=new b2AABB;b2DynamicTree.s_node_id=0;class b2Pair{constructor(proxyA,proxyB){this.proxyA=proxyA;this.proxyB=proxyB}}class b2BroadPhase{constructor(){this.m_tree=new b2DynamicTree;this.m_proxyCount=0;this.m_moveCount=0;this.m_moveBuffer=[];this.m_pairCount=0;this.m_pairBuffer=[]}CreateProxy(aabb,userData){const proxy=this.m_tree.CreateProxy(aabb,userData);++this.m_proxyCount;this.BufferMove(proxy);return proxy}DestroyProxy(proxy){this.UnBufferMove(proxy);--this.m_proxyCount;this.m_tree.DestroyProxy(proxy)}MoveProxy(proxy,aabb,displacement){const buffer=this.m_tree.MoveProxy(proxy,aabb,displacement);if(buffer){this.BufferMove(proxy)}}TouchProxy(proxy){this.BufferMove(proxy)}GetProxyCount(){return this.m_proxyCount}UpdatePairs(callback){this.m_pairCount=0;for(let i=0;i{if(proxy.m_id===queryProxy.m_id){return true}let proxyA;let proxyB;if(proxy.m_idtarget+tolerance){output.state=exports.b2TOIOutputState.e_separated;output.t=tMax;done=true;break}if(s2>target-tolerance){t1=t2;break}let s1=fcn.Evaluate(indexA[0],indexB[0],t1);if(s1target){a1=t;s1=s}else{a2=t;s2=s}if(rootIterCount===50){break}}exports.b2_toiMaxRootIters=b2Max(exports.b2_toiMaxRootIters,rootIterCount);++pushBackIter;if(pushBackIter===b2_maxPolygonVertices){break}}++iter;++exports.b2_toiIters;if(done){break}if(iter===k_maxIterations){output.state=exports.b2TOIOutputState.e_failed;output.t=t1;break}}exports.b2_toiMaxIters=b2Max(exports.b2_toiMaxIters,iter);const time=timer.GetMilliseconds();exports.b2_toiMaxTime=b2Max(exports.b2_toiMaxTime,time);exports.b2_toiTime+=time}const b2CollideCircles_s_pA=new b2Vec2;const b2CollideCircles_s_pB=new b2Vec2;function b2CollideCircles(manifold,circleA,xfA,circleB,xfB){manifold.pointCount=0;const pA=b2Transform.MulXV(xfA,circleA.m_p,b2CollideCircles_s_pA);const pB=b2Transform.MulXV(xfB,circleB.m_p,b2CollideCircles_s_pB);const distSqr=b2Vec2.DistanceSquaredVV(pA,pB);const radius=circleA.m_radius+circleB.m_radius;if(distSqr>radius*radius){return}manifold.type=exports.b2ManifoldType.e_circles;manifold.localPoint.Copy(circleA.m_p);manifold.localNormal.SetZero();manifold.pointCount=1;manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0}const b2CollidePolygonAndCircle_s_c=new b2Vec2;const b2CollidePolygonAndCircle_s_cLocal=new b2Vec2;const b2CollidePolygonAndCircle_s_faceCenter=new b2Vec2;function b2CollidePolygonAndCircle(manifold,polygonA,xfA,circleB,xfB){manifold.pointCount=0;const c=b2Transform.MulXV(xfB,circleB.m_p,b2CollidePolygonAndCircle_s_c);const cLocal=b2Transform.MulTXV(xfA,c,b2CollidePolygonAndCircle_s_cLocal);let normalIndex=0;let separation=-b2_maxFloat;const radius=polygonA.m_radius+circleB.m_radius;const vertexCount=polygonA.m_count;const vertices=polygonA.m_vertices;const normals=polygonA.m_normals;for(let i=0;iradius){return}if(s>separation){separation=s;normalIndex=i}}const vertIndex1=normalIndex;const vertIndex2=(vertIndex1+1)%vertexCount;const v1=vertices[vertIndex1];const v2=vertices[vertIndex2];if(separationradius*radius){return}manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_faceA;b2Vec2.SubVV(cLocal,v1,manifold.localNormal).SelfNormalize();manifold.localPoint.Copy(v1);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0}else if(u2<=0){if(b2Vec2.DistanceSquaredVV(cLocal,v2)>radius*radius){return}manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_faceA;b2Vec2.SubVV(cLocal,v2,manifold.localNormal).SelfNormalize();manifold.localPoint.Copy(v2);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0}else{const faceCenter=b2Vec2.MidVV(v1,v2,b2CollidePolygonAndCircle_s_faceCenter);separation=b2Vec2.DotVV(b2Vec2.SubVV(cLocal,faceCenter,b2Vec2.s_t1),normals[vertIndex1]);if(separation>radius){return}manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_faceA;manifold.localNormal.Copy(normals[vertIndex1]).SelfNormalize();manifold.localPoint.Copy(faceCenter);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0}}const b2EdgeSeparation_s_normal1World=new b2Vec2;const b2EdgeSeparation_s_normal1=new b2Vec2;const b2EdgeSeparation_s_v1=new b2Vec2;const b2EdgeSeparation_s_v2=new b2Vec2;function b2EdgeSeparation(poly1,xf1,edge1,poly2,xf2){const vertices1=poly1.m_vertices;const normals1=poly1.m_normals;const count2=poly2.m_count;const vertices2=poly2.m_vertices;const normal1World=b2Rot.MulRV(xf1.q,normals1[edge1],b2EdgeSeparation_s_normal1World);const normal1=b2Rot.MulTRV(xf2.q,normal1World,b2EdgeSeparation_s_normal1);let index=0;let minDot=b2_maxFloat;for(let i=0;imaxDot){maxDot=dot;edge=i}}let s=b2EdgeSeparation(poly1,xf1,edge,poly2,xf2);const prevEdge=(edge+count1-1)%count1;const sPrev=b2EdgeSeparation(poly1,xf1,prevEdge,poly2,xf2);const nextEdge=(edge+1)%count1;const sNext=b2EdgeSeparation(poly1,xf1,nextEdge,poly2,xf2);let bestEdge=0;let bestSeparation=0;let increment=0;if(sPrev>s&&sPrev>sNext){increment=-1;bestEdge=prevEdge;bestSeparation=sPrev}else if(sNext>s){increment=1;bestEdge=nextEdge;bestSeparation=sNext}else{edgeIndex[0]=edge;return s}while(true){if(increment===-1){edge=(bestEdge+count1-1)%count1}else{edge=(bestEdge+1)%count1}s=b2EdgeSeparation(poly1,xf1,edge,poly2,xf2);if(s>bestSeparation){bestEdge=edge;bestSeparation=s}else{break}}edgeIndex[0]=bestEdge;return bestSeparation}const b2FindIncidentEdge_s_normal1=new b2Vec2;function b2FindIncidentEdge(c,poly1,xf1,edge1,poly2,xf2){const normals1=poly1.m_normals;const count2=poly2.m_count;const vertices2=poly2.m_vertices;const normals2=poly2.m_normals;const normal1=b2Rot.MulTRV(xf2.q,b2Rot.MulRV(xf1.q,normals1[edge1],b2Vec2.s_t0),b2FindIncidentEdge_s_normal1);let index=0;let minDot=b2_maxFloat;for(let i=0;itotalRadius){return}const edgeB=b2CollidePolygons_s_edgeB;edgeB[0]=0;const separationB=b2FindMaxSeparation(edgeB,polyB,xfB,polyA,xfA);if(separationB>totalRadius){return}let poly1;let poly2;let xf1,xf2;let edge1=0;let flip=0;const k_relativeTol=0.98;const k_absoluteTol=0.001;if(separationB>k_relativeTol*separationA+k_absoluteTol){poly1=polyB;poly2=polyA;xf1=xfB;xf2=xfA;edge1=edgeB[0];manifold.type=exports.b2ManifoldType.e_faceB;flip=1}else{poly1=polyA;poly2=polyB;xf1=xfA;xf2=xfB;edge1=edgeA[0];manifold.type=exports.b2ManifoldType.e_faceA;flip=0}const incidentEdge=b2CollidePolygons_s_incidentEdge;b2FindIncidentEdge(incidentEdge,poly1,xf1,edge1,poly2,xf2);const count1=poly1.m_count;const vertices1=poly1.m_vertices;const iv1=edge1;const iv2=(edge1+1)%count1;const local_v11=vertices1[iv1];const local_v12=vertices1[iv2];const localTangent=b2Vec2.SubVV(local_v12,local_v11,b2CollidePolygons_s_localTangent);localTangent.Normalize();const localNormal=b2Vec2.CrossVOne(localTangent,b2CollidePolygons_s_localNormal);const planePoint=b2Vec2.MidVV(local_v11,local_v12,b2CollidePolygons_s_planePoint);const tangent=b2Rot.MulRV(xf1.q,localTangent,b2CollidePolygons_s_tangent);const normal=b2Vec2.CrossVOne(tangent,b2CollidePolygons_s_normal);const v11=b2Transform.MulXV(xf1,local_v11,b2CollidePolygons_s_v11);const v12=b2Transform.MulXV(xf1,local_v12,b2CollidePolygons_s_v12);const frontOffset=b2Vec2.DotVV(normal,v11);const sideOffset1=-b2Vec2.DotVV(tangent,v11)+totalRadius;const sideOffset2=b2Vec2.DotVV(tangent,v12)+totalRadius;const clipPoints1=b2CollidePolygons_s_clipPoints1;const clipPoints2=b2CollidePolygons_s_clipPoints2;let np;const ntangent=b2Vec2.NegV(tangent,b2CollidePolygons_s_ntangent);np=b2ClipSegmentToLine(clipPoints1,incidentEdge,ntangent,sideOffset1,iv1);if(np<2){return}np=b2ClipSegmentToLine(clipPoints2,clipPoints1,tangent,sideOffset2,iv2);if(np<2){return}manifold.localNormal.Copy(localNormal);manifold.localPoint.Copy(planePoint);let pointCount=0;for(let i=0;iradius*radius){return}if(edgeA.m_hasVertex0){const A1=edgeA.m_vertex0;const B1=A;const e1=b2Vec2.SubVV(B1,A1,b2CollideEdgeAndCircle_s_e1);const u1=b2Vec2.DotVV(e1,b2Vec2.SubVV(B1,Q,b2Vec2.s_t0));if(u1>0){return}}id.cf.indexA=0;id.cf.typeA=exports.b2ContactFeatureType.e_vertex;manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_circles;manifold.localNormal.SetZero();manifold.localPoint.Copy(P);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p);return}if(u<=0){const P=B;const d=b2Vec2.SubVV(Q,P,b2CollideEdgeAndCircle_s_d);const dd=b2Vec2.DotVV(d,d);if(dd>radius*radius){return}if(edgeA.m_hasVertex3){const B2=edgeA.m_vertex3;const A2=B;const e2=b2Vec2.SubVV(B2,A2,b2CollideEdgeAndCircle_s_e2);const v2=b2Vec2.DotVV(e2,b2Vec2.SubVV(Q,A2,b2Vec2.s_t0));if(v2>0){return}}id.cf.indexA=1;id.cf.typeA=exports.b2ContactFeatureType.e_vertex;manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_circles;manifold.localNormal.SetZero();manifold.localPoint.Copy(P);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p);return}const den=b2Vec2.DotVV(e,e);const P=b2CollideEdgeAndCircle_s_P;P.x=1/den*(u*A.x+v*B.x);P.y=1/den*(u*A.y+v*B.y);const d=b2Vec2.SubVV(Q,P,b2CollideEdgeAndCircle_s_d);const dd=b2Vec2.DotVV(d,d);if(dd>radius*radius){return}const n=b2CollideEdgeAndCircle_s_n.Set(-e.y,e.x);if(b2Vec2.DotVV(n,b2Vec2.SubVV(Q,A,b2Vec2.s_t0))<0){n.Set(-n.x,-n.y)}n.Normalize();id.cf.indexA=0;id.cf.typeA=exports.b2ContactFeatureType.e_face;manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_faceA;manifold.localNormal.Copy(n);manifold.localPoint.Copy(A);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p)}class b2EPAxis{constructor(){this.type=0;this.index=0;this.separation=0}}class b2TempPolygon{constructor(){this.vertices=b2Vec2.MakeArray(b2_maxPolygonVertices);this.normals=b2Vec2.MakeArray(b2_maxPolygonVertices);this.count=0}}class b2ReferenceFace{constructor(){this.i1=0;this.i2=0;this.v1=new b2Vec2;this.v2=new b2Vec2;this.normal=new b2Vec2;this.sideNormal1=new b2Vec2;this.sideOffset1=0;this.sideNormal2=new b2Vec2;this.sideOffset2=0}}class b2EPCollider{constructor(){this.m_polygonB=new b2TempPolygon;this.m_xf=new b2Transform;this.m_centroidB=new b2Vec2;this.m_v0=new b2Vec2;this.m_v1=new b2Vec2;this.m_v2=new b2Vec2;this.m_v3=new b2Vec2;this.m_normal0=new b2Vec2;this.m_normal1=new b2Vec2;this.m_normal2=new b2Vec2;this.m_normal=new b2Vec2;this.m_type1=0;this.m_type2=0;this.m_lowerLimit=new b2Vec2;this.m_upperLimit=new b2Vec2;this.m_radius=0;this.m_front=false}Collide(manifold,edgeA,xfA,polygonB,xfB){b2Transform.MulTXX(xfA,xfB,this.m_xf);b2Transform.MulXV(this.m_xf,polygonB.m_centroid,this.m_centroidB);this.m_v0.Copy(edgeA.m_vertex0);this.m_v1.Copy(edgeA.m_vertex1);this.m_v2.Copy(edgeA.m_vertex2);this.m_v3.Copy(edgeA.m_vertex3);const hasVertex0=edgeA.m_hasVertex0;const hasVertex3=edgeA.m_hasVertex3;const edge1=b2Vec2.SubVV(this.m_v2,this.m_v1,b2EPCollider.s_edge1);edge1.Normalize();this.m_normal1.Set(edge1.y,-edge1.x);const offset1=b2Vec2.DotVV(this.m_normal1,b2Vec2.SubVV(this.m_centroidB,this.m_v1,b2Vec2.s_t0));let offset0=0;let offset2=0;let convex1=false;let convex2=false;if(hasVertex0){const edge0=b2Vec2.SubVV(this.m_v1,this.m_v0,b2EPCollider.s_edge0);edge0.Normalize();this.m_normal0.Set(edge0.y,-edge0.x);convex1=b2Vec2.CrossVV(edge0,edge1)>=0;offset0=b2Vec2.DotVV(this.m_normal0,b2Vec2.SubVV(this.m_centroidB,this.m_v0,b2Vec2.s_t0))}if(hasVertex3){const edge2=b2Vec2.SubVV(this.m_v3,this.m_v2,b2EPCollider.s_edge2);edge2.Normalize();this.m_normal2.Set(edge2.y,-edge2.x);convex2=b2Vec2.CrossVV(edge1,edge2)>0;offset2=b2Vec2.DotVV(this.m_normal2,b2Vec2.SubVV(this.m_centroidB,this.m_v2,b2Vec2.s_t0))}if(hasVertex0&&hasVertex3){if(convex1&&convex2){this.m_front=offset0>=0||offset1>=0||offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal0);this.m_upperLimit.Copy(this.m_normal2)}else{this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1).SelfNeg()}}else if(convex1){this.m_front=offset0>=0||offset1>=0&&offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal0);this.m_upperLimit.Copy(this.m_normal1)}else{this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal2).SelfNeg();this.m_upperLimit.Copy(this.m_normal1).SelfNeg()}}else if(convex2){this.m_front=offset2>=0||offset0>=0&&offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal2)}else{this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal0).SelfNeg()}}else{this.m_front=offset0>=0&&offset1>=0&&offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1)}else{this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal2).SelfNeg();this.m_upperLimit.Copy(this.m_normal0).SelfNeg()}}}else if(hasVertex0){if(convex1){this.m_front=offset0>=0||offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal0);this.m_upperLimit.Copy(this.m_normal1).SelfNeg()}else{this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1).SelfNeg()}}else{this.m_front=offset0>=0&&offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1).SelfNeg()}else{this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal0).SelfNeg()}}}else if(hasVertex3){if(convex2){this.m_front=offset1>=0||offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal2)}else{this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1)}}else{this.m_front=offset1>=0&&offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1)}else{this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal2).SelfNeg();this.m_upperLimit.Copy(this.m_normal1)}}}else{this.m_front=offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1).SelfNeg()}else{this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1)}}this.m_polygonB.count=polygonB.m_count;for(let i=0;ithis.m_radius){return}const polygonAxis=this.ComputePolygonSeparation(b2EPCollider.s_polygonAxis);if(polygonAxis.type!==0&&polygonAxis.separation>this.m_radius){return}const k_relativeTol=0.98;const k_absoluteTol=0.001;let primaryAxis;if(polygonAxis.type===0){primaryAxis=edgeAxis}else if(polygonAxis.separation>k_relativeTol*edgeAxis.separation+k_absoluteTol){primaryAxis=polygonAxis}else{primaryAxis=edgeAxis}const ie=b2EPCollider.s_ie;const rf=b2EPCollider.s_rf;if(primaryAxis.type===1){manifold.type=exports.b2ManifoldType.e_faceA;let bestIndex=0;let bestValue=b2Vec2.DotVV(this.m_normal,this.m_polygonB.normals[0]);for(let i=1;ithis.m_radius){axis.type=2;axis.index=i;axis.separation=s;return axis}if(b2Vec2.DotVV(n,perp)>=0){if(b2Vec2.DotVV(b2Vec2.SubVV(n,this.m_upperLimit,b2Vec2.s_t0),this.m_normal)<-b2_angularSlop){continue}}else{if(b2Vec2.DotVV(b2Vec2.SubVV(n,this.m_lowerLimit,b2Vec2.s_t0),this.m_normal)<-b2_angularSlop){continue}}if(s>axis.separation){axis.type=2;axis.index=i;axis.separation=s}}return axis}}b2EPCollider.s_edge1=new b2Vec2;b2EPCollider.s_edge0=new b2Vec2;b2EPCollider.s_edge2=new b2Vec2;b2EPCollider.s_ie=b2ClipVertex.MakeArray(2);b2EPCollider.s_rf=new b2ReferenceFace;b2EPCollider.s_clipPoints1=b2ClipVertex.MakeArray(2);b2EPCollider.s_clipPoints2=b2ClipVertex.MakeArray(2);b2EPCollider.s_edgeAxis=new b2EPAxis;b2EPCollider.s_polygonAxis=new b2EPAxis;b2EPCollider.s_n=new b2Vec2;b2EPCollider.s_perp=new b2Vec2;const b2CollideEdgeAndPolygon_s_collider=new b2EPCollider;function b2CollideEdgeAndPolygon(manifold,edgeA,xfA,polygonB,xfB){const collider=b2CollideEdgeAndPolygon_s_collider;collider.Collide(manifold,edgeA,xfA,polygonB,xfB)}class b2MassData{constructor(){this.mass=0;this.center=new b2Vec2(0,0);this.I=0}}(function(b2ShapeType){b2ShapeType[b2ShapeType.e_unknown=-1]="e_unknown";b2ShapeType[b2ShapeType.e_circleShape=0]="e_circleShape";b2ShapeType[b2ShapeType.e_edgeShape=1]="e_edgeShape";b2ShapeType[b2ShapeType.e_polygonShape=2]="e_polygonShape";b2ShapeType[b2ShapeType.e_chainShape=3]="e_chainShape";b2ShapeType[b2ShapeType.e_shapeTypeCount=4]="e_shapeTypeCount"})(exports.b2ShapeType||(exports.b2ShapeType={}));class b2Shape{constructor(type,radius){this.m_type=exports.b2ShapeType.e_unknown;this.m_radius=0;this.m_type=type;this.m_radius=radius}Copy(other){this.m_radius=other.m_radius;return this}GetType(){return this.m_type}}class b2CircleShape extends b2Shape{constructor(radius=0){super(exports.b2ShapeType.e_circleShape,radius);this.m_p=new b2Vec2}Set(position,radius=this.m_radius){this.m_p.Copy(position);this.m_radius=radius;return this}Clone(){return new b2CircleShape().Copy(this)}Copy(other){super.Copy(other);this.m_p.Copy(other.m_p);return this}GetChildCount(){return 1}TestPoint(transform,p){const center=b2Transform.MulXV(transform,this.m_p,b2CircleShape.TestPoint_s_center);const d=b2Vec2.SubVV(p,center,b2CircleShape.TestPoint_s_d);return b2Vec2.DotVV(d,d)<=b2Sq(this.m_radius)}ComputeDistance(xf,p,normal,childIndex){const center=b2Transform.MulXV(xf,this.m_p,b2CircleShape.ComputeDistance_s_center);b2Vec2.SubVV(p,center,normal);return normal.Normalize()-this.m_radius}RayCast(output,input,transform,childIndex){const position=b2Transform.MulXV(transform,this.m_p,b2CircleShape.RayCast_s_position);const s=b2Vec2.SubVV(input.p1,position,b2CircleShape.RayCast_s_s);const b=b2Vec2.DotVV(s,s)-b2Sq(this.m_radius);const r=b2Vec2.SubVV(input.p2,input.p1,b2CircleShape.RayCast_s_r);const c=b2Vec2.DotVV(s,r);const rr=b2Vec2.DotVV(r,r);const sigma=c*c-rr*b;if(sigma<0||rr=0&&a<=input.maxFraction*rr){a/=rr;output.fraction=a;b2Vec2.AddVMulSV(s,a,r,output.normal).SelfNormalize();return true}return false}ComputeAABB(aabb,transform,childIndex){const p=b2Transform.MulXV(transform,this.m_p,b2CircleShape.ComputeAABB_s_p);aabb.lowerBound.Set(p.x-this.m_radius,p.y-this.m_radius);aabb.upperBound.Set(p.x+this.m_radius,p.y+this.m_radius)}ComputeMass(massData,density){const radius_sq=b2Sq(this.m_radius);massData.mass=density*b2_pi*radius_sq;massData.center.Copy(this.m_p);massData.I=massData.mass*(0.5*radius_sq+b2Vec2.DotVV(this.m_p,this.m_p))}SetupDistanceProxy(proxy,index){proxy.m_vertices=proxy.m_buffer;proxy.m_vertices[0].Copy(this.m_p);proxy.m_count=1;proxy.m_radius=this.m_radius}ComputeSubmergedArea(normal,offset,xf,c){const p=b2Transform.MulXV(xf,this.m_p,new b2Vec2);const l=-(b2Vec2.DotVV(normal,p)-offset);if(l<-this.m_radius+b2_epsilon){return 0}if(l>this.m_radius){c.Copy(p);return b2_pi*this.m_radius*this.m_radius}const r2=this.m_radius*this.m_radius;const l2=l*l;const area=r2*(b2Asin(l/this.m_radius)+b2_pi/2)+l*b2Sqrt(r2-l2);const com=-2/3*b2Pow(r2-l2,1.5)/area;c.x=p.x+normal.x*com;c.y=p.y+normal.y*com;return area}Dump(log){log(" const shape: b2CircleShape = new b2CircleShape();\n");log(" shape.m_radius = %.15f;\n",this.m_radius);log(" shape.m_p.Set(%.15f, %.15f);\n",this.m_p.x,this.m_p.y)}}b2CircleShape.TestPoint_s_center=new b2Vec2;b2CircleShape.TestPoint_s_d=new b2Vec2;b2CircleShape.ComputeDistance_s_center=new b2Vec2;b2CircleShape.RayCast_s_position=new b2Vec2;b2CircleShape.RayCast_s_s=new b2Vec2;b2CircleShape.RayCast_s_r=new b2Vec2;b2CircleShape.ComputeAABB_s_p=new b2Vec2;class b2PolygonShape extends b2Shape{constructor(){super(exports.b2ShapeType.e_polygonShape,b2_polygonRadius);this.m_centroid=new b2Vec2(0,0);this.m_vertices=[];this.m_normals=[];this.m_count=0}Clone(){return new b2PolygonShape().Copy(this)}Copy(other){super.Copy(other);this.m_centroid.Copy(other.m_centroid);this.m_count=other.m_count;this.m_vertices=b2Vec2.MakeArray(this.m_count);this.m_normals=b2Vec2.MakeArray(this.m_count);for(let i=0;ix0||x===x0&&ps[i].yr.LengthSquared()){ie=j}}++m;ih=ie;if(ie===i0){break}}this.m_count=m;this.m_vertices=b2Vec2.MakeArray(this.m_count);this.m_normals=b2Vec2.MakeArray(this.m_count);for(let i=0;i0){return false}}return true}ComputeDistance(xf,p,normal,childIndex){const pLocal=b2Transform.MulTXV(xf,p,b2PolygonShape.ComputeDistance_s_pLocal);let maxDistance=-b2_maxFloat;const normalForMaxDistance=b2PolygonShape.ComputeDistance_s_normalForMaxDistance.Copy(pLocal);for(let i=0;imaxDistance){maxDistance=dot;normalForMaxDistance.Copy(this.m_normals[i])}}if(maxDistance>0){const minDistance=b2PolygonShape.ComputeDistance_s_minDistance.Copy(normalForMaxDistance);let minDistance2=maxDistance*maxDistance;for(let i=0;idistance2){minDistance.Copy(distance);minDistance2=distance2}}b2Rot.MulRV(xf.q,minDistance,normal);normal.Normalize();return Math.sqrt(minDistance2)}else{b2Rot.MulRV(xf.q,normalForMaxDistance,normal);return maxDistance}}RayCast(output,input,xf,childIndex){const p1=b2Transform.MulTXV(xf,input.p1,b2PolygonShape.RayCast_s_p1);const p2=b2Transform.MulTXV(xf,input.p2,b2PolygonShape.RayCast_s_p2);const d=b2Vec2.SubVV(p2,p1,b2PolygonShape.RayCast_s_d);let lower=0;let upper=input.maxFraction;let index=-1;for(let i=0;i0&&numerator=0){output.fraction=lower;b2Rot.MulRV(xf.q,this.m_normals[index],output.normal);return true}return false}ComputeAABB(aabb,xf,childIndex){const lower=b2Transform.MulXV(xf,this.m_vertices[0],aabb.lowerBound);const upper=aabb.upperBound.Copy(lower);for(let i=0;i0){if(isSubmerged){if(!lastSubmerged){intoIndex=i-1;diveCount++}}else{if(lastSubmerged){outoIndex=i-1;diveCount++}}}lastSubmerged=isSubmerged}switch(diveCount){case 0:if(lastSubmerged){const md=b2PolygonShape.ComputeSubmergedArea_s_md;this.ComputeMass(md,1);b2Transform.MulXV(xf,md.center,c);return md.mass}else{return 0}case 1:if(intoIndex===-1){intoIndex=this.m_count-1}else{outoIndex=this.m_count-1}break;}const intoIndex2=(intoIndex+1)%this.m_count;const outoIndex2=(outoIndex+1)%this.m_count;const intoLamdda=(0-depths[intoIndex])/(depths[intoIndex2]-depths[intoIndex]);const outoLamdda=(0-depths[outoIndex])/(depths[outoIndex2]-depths[outoIndex]);const intoVec=b2PolygonShape.ComputeSubmergedArea_s_intoVec.Set(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);const outoVec=b2PolygonShape.ComputeSubmergedArea_s_outoVec.Set(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);let area=0;const center=b2PolygonShape.ComputeSubmergedArea_s_center.SetZero();let p2=this.m_vertices[intoIndex2];let p3;let i=intoIndex2;while(i!==outoIndex2){i=(i+1)%this.m_count;if(i===outoIndex2){p3=outoVec}else{p3=this.m_vertices[i]}const triangleArea=0.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}center.SelfMul(1/area);b2Transform.MulXV(xf,center,c);return area}Dump(log){log(" const shape: b2PolygonShape = new b2PolygonShape();\n");log(" const vs: b2Vec2[] = b2Vec2.MakeArray(%d);\n",b2_maxPolygonVertices);for(let i=0;i0){const s2=b2Vec2.DotVV(s,s);if(ds>s2){b2Vec2.SubVV(p,v2,d)}else{d.SelfMulSub(ds/s2,s)}}normal.Copy(d);return normal.Normalize()}RayCast(output,input,xf,childIndex){const p1=b2Transform.MulTXV(xf,input.p1,b2EdgeShape.RayCast_s_p1);const p2=b2Transform.MulTXV(xf,input.p2,b2EdgeShape.RayCast_s_p2);const d=b2Vec2.SubVV(p2,p1,b2EdgeShape.RayCast_s_d);const v1=this.m_vertex1;const v2=this.m_vertex2;const e=b2Vec2.SubVV(v2,v1,b2EdgeShape.RayCast_s_e);const normal=output.normal.Set(e.y,-e.x).SelfNormalize();const numerator=b2Vec2.DotVV(normal,b2Vec2.SubVV(v1,p1,b2Vec2.s_t0));const denominator=b2Vec2.DotVV(normal,d);if(denominator===0){return false}const t=numerator/denominator;if(t<0||input.maxFraction1){return false}output.fraction=t;b2Rot.MulRV(xf.q,output.normal,output.normal);if(numerator>0){output.normal.SelfNeg()}return true}ComputeAABB(aabb,xf,childIndex){const v1=b2Transform.MulXV(xf,this.m_vertex1,b2EdgeShape.ComputeAABB_s_v1);const v2=b2Transform.MulXV(xf,this.m_vertex2,b2EdgeShape.ComputeAABB_s_v2);b2Vec2.MinV(v1,v2,aabb.lowerBound);b2Vec2.MaxV(v1,v2,aabb.upperBound);const r=this.m_radius;aabb.lowerBound.SelfSubXY(r,r);aabb.upperBound.SelfAddXY(r,r)}ComputeMass(massData,density){massData.mass=0;b2Vec2.MidVV(this.m_vertex1,this.m_vertex2,massData.center);massData.I=0}SetupDistanceProxy(proxy,index){proxy.m_vertices=proxy.m_buffer;proxy.m_vertices[0].Copy(this.m_vertex1);proxy.m_vertices[1].Copy(this.m_vertex2);proxy.m_count=2;proxy.m_radius=this.m_radius}ComputeSubmergedArea(normal,offset,xf,c){c.SetZero();return 0}Dump(log){log(" const shape: b2EdgeShape = new b2EdgeShape();\n");log(" shape.m_radius = %.15f;\n",this.m_radius);log(" shape.m_vertex0.Set(%.15f, %.15f);\n",this.m_vertex0.x,this.m_vertex0.y);log(" shape.m_vertex1.Set(%.15f, %.15f);\n",this.m_vertex1.x,this.m_vertex1.y);log(" shape.m_vertex2.Set(%.15f, %.15f);\n",this.m_vertex2.x,this.m_vertex2.y);log(" shape.m_vertex3.Set(%.15f, %.15f);\n",this.m_vertex3.x,this.m_vertex3.y);log(" shape.m_hasVertex0 = %s;\n",this.m_hasVertex0);log(" shape.m_hasVertex3 = %s;\n",this.m_hasVertex3)}}b2EdgeShape.ComputeDistance_s_v1=new b2Vec2;b2EdgeShape.ComputeDistance_s_v2=new b2Vec2;b2EdgeShape.ComputeDistance_s_d=new b2Vec2;b2EdgeShape.ComputeDistance_s_s=new b2Vec2;b2EdgeShape.RayCast_s_p1=new b2Vec2;b2EdgeShape.RayCast_s_p2=new b2Vec2;b2EdgeShape.RayCast_s_d=new b2Vec2;b2EdgeShape.RayCast_s_e=new b2Vec2;b2EdgeShape.RayCast_s_q=new b2Vec2;b2EdgeShape.RayCast_s_r=new b2Vec2;b2EdgeShape.ComputeAABB_s_v1=new b2Vec2;b2EdgeShape.ComputeAABB_s_v2=new b2Vec2;class b2ChainShape extends b2Shape{constructor(){super(exports.b2ShapeType.e_chainShape,b2_polygonRadius);this.m_vertices=[];this.m_count=0;this.m_prevVertex=new b2Vec2;this.m_nextVertex=new b2Vec2;this.m_hasPrevVertex=false;this.m_hasNextVertex=false}CreateLoop(vertices,count=vertices.length,start=0){this.m_count=count+1;this.m_vertices=b2Vec2.MakeArray(this.m_count);for(let i=0;i0){edge.m_vertex0.Copy(this.m_vertices[index-1]);edge.m_hasVertex0=true}else{edge.m_vertex0.Copy(this.m_prevVertex);edge.m_hasVertex0=this.m_hasPrevVertex}if(indexnew b2FixtureProxy(this));this.m_proxyCount=0;this.m_density=b2Maybe(def.density,0)}Destroy(){}CreateProxies(xf){const broadPhase=this.m_body.m_world.m_contactManager.m_broadPhase;this.m_proxyCount=this.m_shape.GetChildCount();for(let i=0;i0){this.ResetMassData()}this.m_world.m_newFixture=true;return fixture}CreateFixtureShapeDensity(shape,density=0){const def=b2Body.CreateFixtureShapeDensity_s_def;def.shape=shape;def.density=density;return this.CreateFixtureDef(def)}DestroyFixture(fixture){if(this.m_world.IsLocked()){throw new Error}let node=this.m_fixtureList;let ppF=null;while(node!==null){if(node===fixture){if(ppF){ppF.m_next=fixture.m_next}else{this.m_fixtureList=fixture.m_next}break}ppF=node;node=node.m_next}let edge=this.m_contactList;while(edge){const c=edge.contact;edge=edge.next;const fixtureA=c.GetFixtureA();const fixtureB=c.GetFixtureB();if(fixture===fixtureA||fixture===fixtureB){this.m_world.m_contactManager.Destroy(c)}}if(this.m_activeFlag){fixture.DestroyProxies()}fixture.Destroy();fixture.m_next=null;--this.m_fixtureCount;this.ResetMassData()}SetTransformVec(position,angle){this.SetTransformXY(position.x,position.y,angle)}SetTransformXY(x,y,angle){if(!this.m_world)return;if(this.m_world.IsLocked()){throw new Error}this.m_xf.q.SetAngle(angle);this.m_xf.p.Set(x,y);this.m_xf0.Copy(this.m_xf);b2Transform.MulXV(this.m_xf,this.m_sweep.localCenter,this.m_sweep.c);this.m_sweep.a=angle;this.m_sweep.c0.Copy(this.m_sweep.c);this.m_sweep.a0=angle;for(let f=this.m_fixtureList;f;f=f.m_next){f.Synchronize(this.m_xf,this.m_xf)}this.m_world.m_contactManager.FindNewContacts()}SetTransform(xf){this.SetTransformVec(xf.p,xf.GetAngle())}GetTransform(){return this.m_xf}GetPosition(){return this.m_xf?this.m_xf.p:0}SetPosition(position){this.SetTransformVec(position,this.GetAngle())}SetPositionXY(x,y){this.SetTransformXY(x,y,this.GetAngle())}GetAngle(){return this.m_sweep&&this.m_sweep.a||0}SetAngle(angle){this.SetTransformVec(this.GetPosition(),angle)}GetWorldCenter(){return this.m_sweep.c}GetLocalCenter(){return this.m_sweep.localCenter}SetLinearVelocity(v){if(this.m_type===exports.b2BodyType.b2_staticBody){return}if(b2Vec2.DotVV(v,v)>0){this.SetAwake(true)}this.m_linearVelocity.Copy(v)}GetLinearVelocity(){return this.m_linearVelocity}SetAngularVelocity(w){if(this.m_type===exports.b2BodyType.b2_staticBody){return}if(w*w>0){this.SetAwake(true)}this.m_angularVelocity=w}GetAngularVelocity(){return this.m_angularVelocity}GetDefinition(bd){bd.type=this.GetType();bd.allowSleep=this.m_autoSleepFlag;bd.angle=this.GetAngle();bd.angularDamping=this.m_angularDamping;bd.gravityScale=this.m_gravityScale;bd.angularVelocity=this.m_angularVelocity;bd.fixedRotation=this.m_fixedRotationFlag;bd.bullet=this.m_bulletFlag;bd.awake=this.m_awakeFlag;bd.linearDamping=this.m_linearDamping;bd.linearVelocity.Copy(this.GetLinearVelocity());bd.position.Copy(this.GetPosition());bd.userData=this.GetUserData();return bd}ApplyForce(force,point,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return}if(wake&&!this.m_awakeFlag){this.SetAwake(true)}if(this.m_awakeFlag){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}}ApplyForceToCenter(force,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return}if(wake&&!this.m_awakeFlag){this.SetAwake(true)}if(this.m_awakeFlag){this.m_force.x+=force.x;this.m_force.y+=force.y}}ApplyTorque(torque,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return}if(wake&&!this.m_awakeFlag){this.SetAwake(true)}if(this.m_awakeFlag){this.m_torque+=torque}}ApplyLinearImpulse(impulse,point,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return}if(wake&&!this.m_awakeFlag){this.SetAwake(true)}if(this.m_awakeFlag){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)}}ApplyLinearImpulseToCenter(impulse,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return}if(wake&&!this.m_awakeFlag){this.SetAwake(true)}if(this.m_awakeFlag){this.m_linearVelocity.x+=this.m_invMass*impulse.x;this.m_linearVelocity.y+=this.m_invMass*impulse.y}}ApplyAngularImpulse(impulse,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return}if(wake&&!this.m_awakeFlag){this.SetAwake(true)}if(this.m_awakeFlag){this.m_angularVelocity+=this.m_invI*impulse}}GetMass(){return this.m_mass}GetInertia(){return this.m_I+this.m_mass*b2Vec2.DotVV(this.m_sweep.localCenter,this.m_sweep.localCenter)}GetMassData(data){data.mass=this.m_mass;data.I=this.m_I+this.m_mass*b2Vec2.DotVV(this.m_sweep.localCenter,this.m_sweep.localCenter);data.center.Copy(this.m_sweep.localCenter);return data}SetMassData(massData){if(this.m_world.IsLocked()){throw new Error}if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return}this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_mass=massData.mass;if(this.m_mass<=0){this.m_mass=1}this.m_invMass=1/this.m_mass;if(massData.I>0&&!this.m_fixedRotationFlag){this.m_I=massData.I-this.m_mass*b2Vec2.DotVV(massData.center,massData.center);this.m_invI=1/this.m_I}const oldCenter=b2Body.SetMassData_s_oldCenter.Copy(this.m_sweep.c);this.m_sweep.localCenter.Copy(massData.center);b2Transform.MulXV(this.m_xf,this.m_sweep.localCenter,this.m_sweep.c);this.m_sweep.c0.Copy(this.m_sweep.c);b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(this.m_sweep.c,oldCenter,b2Vec2.s_t0),this.m_linearVelocity)}ResetMassData(){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===exports.b2BodyType.b2_staticBody||this.m_type===exports.b2BodyType.b2_kinematicBody){this.m_sweep.c0.Copy(this.m_xf.p);this.m_sweep.c.Copy(this.m_xf.p);this.m_sweep.a0=this.m_sweep.a;return}const localCenter=b2Body.ResetMassData_s_localCenter.SetZero();for(let f=this.m_fixtureList;f;f=f.m_next){if(f.m_density===0){continue}const massData=f.GetMassData(b2Body.ResetMassData_s_massData);this.m_mass+=massData.mass;localCenter.x+=massData.center.x*massData.mass;localCenter.y+=massData.center.y*massData.mass;this.m_I+=massData.I}if(this.m_mass>0){this.m_invMass=1/this.m_mass;localCenter.x*=this.m_invMass;localCenter.y*=this.m_invMass}else{this.m_mass=1;this.m_invMass=1}if(this.m_I>0&&!this.m_fixedRotationFlag){this.m_I-=this.m_mass*b2Vec2.DotVV(localCenter,localCenter);this.m_invI=1/this.m_I}else{this.m_I=0;this.m_invI=0}const oldCenter=b2Body.ResetMassData_s_oldCenter.Copy(this.m_sweep.c);this.m_sweep.localCenter.Copy(localCenter);b2Transform.MulXV(this.m_xf,this.m_sweep.localCenter,this.m_sweep.c);this.m_sweep.c0.Copy(this.m_sweep.c);b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(this.m_sweep.c,oldCenter,b2Vec2.s_t0),this.m_linearVelocity)}GetWorldPoint(localPoint,out){return b2Transform.MulXV(this.m_xf,localPoint,out)}GetWorldVector(localVector,out){return b2Rot.MulRV(this.m_xf.q,localVector,out)}GetLocalPoint(worldPoint,out){return b2Transform.MulTXV(this.m_xf,worldPoint,out)}GetLocalVector(worldVector,out){return b2Rot.MulTRV(this.m_xf.q,worldVector,out)}GetLinearVelocityFromWorldPoint(worldPoint,out){return b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(worldPoint,this.m_sweep.c,b2Vec2.s_t0),out)}GetLinearVelocityFromLocalPoint(localPoint,out){return this.GetLinearVelocityFromWorldPoint(this.GetWorldPoint(localPoint,out),out)}GetLinearDamping(){return this.m_linearDamping}SetLinearDamping(linearDamping){this.m_linearDamping=linearDamping}GetAngularDamping(){return this.m_angularDamping}SetAngularDamping(angularDamping){this.m_angularDamping=angularDamping}GetGravityScale(){return this.m_gravityScale}SetGravityScale(scale){this.m_gravityScale=scale}SetType(type){if(this.m_world.IsLocked()){throw new Error}if(this.m_type===type){return}this.m_type=type;this.ResetMassData();if(this.m_type===exports.b2BodyType.b2_staticBody){this.m_linearVelocity.SetZero();this.m_angularVelocity=0;this.m_sweep.a0=this.m_sweep.a;this.m_sweep.c0.Copy(this.m_sweep.c);this.SynchronizeFixtures()}this.SetAwake(true);this.m_force.SetZero();this.m_torque=0;let ce=this.m_contactList;while(ce){const ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact)}this.m_contactList=null;for(let f=this.m_fixtureList;f;f=f.m_next){f.TouchProxies()}}GetType(){return this.m_type}SetBullet(flag){this.m_bulletFlag=flag}IsBullet(){return this.m_bulletFlag}SetSleepingAllowed(flag){this.m_autoSleepFlag=flag;if(!flag){this.SetAwake(true)}}IsSleepingAllowed(){return this.m_autoSleepFlag}SetAwake(flag){if(flag){if(!this.m_awakeFlag){this.m_awakeFlag=true;this.m_sleepTime=0}}else{this.m_awakeFlag=false;this.m_sleepTime=0;this.m_linearVelocity.SetZero();this.m_angularVelocity=0;this.m_force.SetZero();this.m_torque=0}}IsAwake(){return this.m_awakeFlag}SetActive(flag){if(this.m_world.IsLocked()){throw new Error}if(flag===this.IsActive()){return}this.m_activeFlag=flag;if(flag){for(let f=this.m_fixtureList;f;f=f.m_next){f.CreateProxies(this.m_xf)}}else{for(let f=this.m_fixtureList;f;f=f.m_next){f.DestroyProxies()}let ce=this.m_contactList;while(ce){const ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact)}this.m_contactList=null}}IsActive(){return this.m_activeFlag}SetFixedRotation(flag){if(this.m_fixedRotationFlag===flag){return}this.m_fixedRotationFlag=flag;this.m_angularVelocity=0;this.ResetMassData()}IsFixedRotation(){return this.m_fixedRotationFlag}GetFixtureList(){return this.m_fixtureList}GetJointList(){return this.m_jointList}GetContactList(){return this.m_contactList}GetNext(){return this.m_next}GetUserData(){return this.m_userData}SetUserData(data){this.m_userData=data}GetWorld(){return this.m_world}Dump(log){const bodyIndex=this.m_islandIndex;log("{\n");log(" const bd: b2BodyDef = new b2BodyDef();\n");let type_str="";switch(this.m_type){case exports.b2BodyType.b2_staticBody:type_str="b2BodyType.b2_staticBody";break;case exports.b2BodyType.b2_kinematicBody:type_str="b2BodyType.b2_kinematicBody";break;case exports.b2BodyType.b2_dynamicBody:type_str="b2BodyType.b2_dynamicBody";break;default:break;}log(" bd.type = %s;\n",type_str);log(" bd.position.Set(%.15f, %.15f);\n",this.m_xf.p.x,this.m_xf.p.y);log(" bd.angle = %.15f;\n",this.m_sweep.a);log(" bd.linearVelocity.Set(%.15f, %.15f);\n",this.m_linearVelocity.x,this.m_linearVelocity.y);log(" bd.angularVelocity = %.15f;\n",this.m_angularVelocity);log(" bd.linearDamping = %.15f;\n",this.m_linearDamping);log(" bd.angularDamping = %.15f;\n",this.m_angularDamping);log(" bd.allowSleep = %s;\n",this.m_autoSleepFlag?"true":"false");log(" bd.awake = %s;\n",this.m_awakeFlag?"true":"false");log(" bd.fixedRotation = %s;\n",this.m_fixedRotationFlag?"true":"false");log(" bd.bullet = %s;\n",this.m_bulletFlag?"true":"false");log(" bd.active = %s;\n",this.m_activeFlag?"true":"false");log(" bd.gravityScale = %.15f;\n",this.m_gravityScale);log("\n");log(" bodies[%d] = this.m_world.CreateBody(bd);\n",this.m_islandIndex);log("\n");for(let f=this.m_fixtureList;f;f=f.m_next){log(" {\n");f.Dump(log,bodyIndex);log(" }\n")}log("}\n")}SynchronizeFixtures(){const xf1=b2Body.SynchronizeFixtures_s_xf1;xf1.q.SetAngle(this.m_sweep.a0);b2Rot.MulRV(xf1.q,this.m_sweep.localCenter,xf1.p);b2Vec2.SubVV(this.m_sweep.c0,xf1.p,xf1.p);for(let f=this.m_fixtureList;f;f=f.m_next){f.Synchronize(xf1,this.m_xf)}}SynchronizeTransform(){this.m_xf.q.SetAngle(this.m_sweep.a);b2Rot.MulRV(this.m_xf.q,this.m_sweep.localCenter,this.m_xf.p);b2Vec2.SubVV(this.m_sweep.c,this.m_xf.p,this.m_xf.p)}ShouldCollide(other){if(this.m_type===exports.b2BodyType.b2_staticBody&&other.m_type===exports.b2BodyType.b2_staticBody){return false}return this.ShouldCollideConnected(other)}ShouldCollideConnected(other){for(let jn=this.m_jointList;jn;jn=jn.next){if(jn.other===other){if(!jn.joint.m_collideConnected){return false}}}return true}Advance(alpha){this.m_sweep.Advance(alpha);this.m_sweep.c.Copy(this.m_sweep.c0);this.m_sweep.a=this.m_sweep.a0;this.m_xf.q.SetAngle(this.m_sweep.a);b2Rot.MulRV(this.m_xf.q,this.m_sweep.localCenter,this.m_xf.p);b2Vec2.SubVV(this.m_sweep.c,this.m_xf.p,this.m_xf.p)}GetControllerList(){return this.m_controllerList}GetControllerCount(){return this.m_controllerCount}Destroy(){this.m_userData=null;this.m_sweep=null;this.m_xf=null;this.m_linearVelocity=null;this.m_force=null;this.m_world=null;this.m_prev=null;this.m_next=null;this.m_fixtureList=null;this.m_controllerList=null;this.m_jointList=null;this.m_contactList=null}}b2Body.CreateFixtureShapeDensity_s_def=new b2FixtureDef;b2Body.SetMassData_s_oldCenter=new b2Vec2;b2Body.ResetMassData_s_localCenter=new b2Vec2;b2Body.ResetMassData_s_oldCenter=new b2Vec2;b2Body.ResetMassData_s_massData=new b2MassData;b2Body.SynchronizeFixtures_s_xf1=new b2Transform;(function(b2JointType){b2JointType[b2JointType.e_unknownJoint=0]="e_unknownJoint";b2JointType[b2JointType.e_revoluteJoint=1]="e_revoluteJoint";b2JointType[b2JointType.e_prismaticJoint=2]="e_prismaticJoint";b2JointType[b2JointType.e_distanceJoint=3]="e_distanceJoint";b2JointType[b2JointType.e_pulleyJoint=4]="e_pulleyJoint";b2JointType[b2JointType.e_mouseJoint=5]="e_mouseJoint";b2JointType[b2JointType.e_gearJoint=6]="e_gearJoint";b2JointType[b2JointType.e_wheelJoint=7]="e_wheelJoint";b2JointType[b2JointType.e_weldJoint=8]="e_weldJoint";b2JointType[b2JointType.e_frictionJoint=9]="e_frictionJoint";b2JointType[b2JointType.e_ropeJoint=10]="e_ropeJoint";b2JointType[b2JointType.e_motorJoint=11]="e_motorJoint";b2JointType[b2JointType.e_areaJoint=12]="e_areaJoint"})(exports.b2JointType||(exports.b2JointType={}));(function(b2LimitState){b2LimitState[b2LimitState.e_inactiveLimit=0]="e_inactiveLimit";b2LimitState[b2LimitState.e_atLowerLimit=1]="e_atLowerLimit";b2LimitState[b2LimitState.e_atUpperLimit=2]="e_atUpperLimit";b2LimitState[b2LimitState.e_equalLimits=3]="e_equalLimits"})(exports.b2LimitState||(exports.b2LimitState={}));class b2Jacobian{constructor(){this.linear=new b2Vec2;this.angularA=0;this.angularB=0}SetZero(){this.linear.SetZero();this.angularA=0;this.angularB=0;return this}Set(x,a1,a2){this.linear.Copy(x);this.angularA=a1;this.angularB=a2;return this}}class b2JointEdge{constructor(joint,other){this.prev=null;this.next=null;this.joint=joint;this.other=other}}class b2JointDef{constructor(type){this.type=exports.b2JointType.e_unknownJoint;this.userData=null;this.collideConnected=false;this.type=type}}class b2Joint{constructor(def){this.m_type=exports.b2JointType.e_unknownJoint;this.m_prev=null;this.m_next=null;this.m_index=0;this.m_islandFlag=false;this.m_collideConnected=false;this.m_userData=null;this.m_type=def.type;this.m_edgeA=new b2JointEdge(this,def.bodyB);this.m_edgeB=new b2JointEdge(this,def.bodyA);this.m_bodyA=def.bodyA;this.m_bodyB=def.bodyB;this.m_collideConnected=b2Maybe(def.collideConnected,false);this.m_userData=def.userData}GetType(){return this.m_type}GetBodyA(){return this.m_bodyA}GetBodyB(){return this.m_bodyB}GetNext(){return this.m_next}GetUserData(){return this.m_userData}SetUserData(data){this.m_userData=data}IsActive(){return this.m_bodyA.IsActive()&&this.m_bodyB.IsActive()}GetCollideConnected(){return this.m_collideConnected}Dump(log){log("// Dump is not supported for this joint type.\n")}ShiftOrigin(newOrigin){}}class b2DistanceJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_distanceJoint);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2;this.length=1;this.frequencyHz=0;this.dampingRatio=0}Initialize(b1,b2,anchor1,anchor2){this.bodyA=b1;this.bodyB=b2;this.bodyA.GetLocalPoint(anchor1,this.localAnchorA);this.bodyB.GetLocalPoint(anchor2,this.localAnchorB);this.length=b2Vec2.DistanceVV(anchor1,anchor2);this.frequencyHz=0;this.dampingRatio=0}}class b2DistanceJoint extends b2Joint{constructor(def){super(def);this.m_frequencyHz=0;this.m_dampingRatio=0;this.m_bias=0;this.m_localAnchorA=new b2Vec2;this.m_localAnchorB=new b2Vec2;this.m_gamma=0;this.m_impulse=0;this.m_length=0;this.m_indexA=0;this.m_indexB=0;this.m_u=new b2Vec2;this.m_rA=new b2Vec2;this.m_rB=new b2Vec2;this.m_localCenterA=new b2Vec2;this.m_localCenterB=new b2Vec2;this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_mass=0;this.m_qA=new b2Rot;this.m_qB=new b2Rot;this.m_lalcA=new b2Vec2;this.m_lalcB=new b2Vec2;this.m_frequencyHz=b2Maybe(def.frequencyHz,0);this.m_dampingRatio=b2Maybe(def.dampingRatio,0);this.m_localAnchorA.Copy(def.localAnchorA);this.m_localAnchorB.Copy(def.localAnchorB);this.m_length=def.length}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out)}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out)}GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse*this.m_u.x;out.y=inv_dt*this.m_impulse*this.m_u.y;return out}GetReactionTorque(inv_dt){return 0}GetLocalAnchorA(){return this.m_localAnchorA}GetLocalAnchorB(){return this.m_localAnchorB}SetLength(length){this.m_length=length}Length(){return this.m_length}SetFrequency(hz){this.m_frequencyHz=hz}GetFrequency(){return this.m_frequencyHz}SetDampingRatio(ratio){this.m_dampingRatio=ratio}GetDampingRatio(){return this.m_dampingRatio}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log(" const jd: b2DistanceJointDef = new b2DistanceJointDef();\n");log(" jd.bodyA = bodies[%d];\n",indexA);log(" jd.bodyB = bodies[%d];\n",indexB);log(" jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log(" jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log(" jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log(" jd.length = %.15f;\n",this.m_length);log(" jd.frequencyHz = %.15f;\n",this.m_frequencyHz);log(" jd.dampingRatio = %.15f;\n",this.m_dampingRatio);log(" joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index)}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);this.m_u.x=cB.x+this.m_rB.x-cA.x-this.m_rA.x;this.m_u.y=cB.y+this.m_rB.y-cA.y-this.m_rA.y;const length=this.m_u.Length();if(length>b2_linearSlop){this.m_u.SelfMul(1/length)}else{this.m_u.SetZero()}const crAu=b2Vec2.CrossVV(this.m_rA,this.m_u);const crBu=b2Vec2.CrossVV(this.m_rB,this.m_u);let invMass=this.m_invMassA+this.m_invIA*crAu*crAu+this.m_invMassB+this.m_invIB*crBu*crBu;this.m_mass=invMass!==0?1/invMass:0;if(this.m_frequencyHz>0){const C=length-this.m_length;const omega=2*b2_pi*this.m_frequencyHz;const d=2*this.m_mass*this.m_dampingRatio*omega;const k=this.m_mass*omega*omega;const h=data.step.dt;this.m_gamma=h*(d+h*k);this.m_gamma=this.m_gamma!==0?1/this.m_gamma:0;this.m_bias=C*h*k*this.m_gamma;invMass+=this.m_gamma;this.m_mass=invMass!==0?1/invMass:0}else{this.m_gamma=0;this.m_bias=0}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;const P=b2Vec2.MulSV(this.m_impulse,this.m_u,b2DistanceJoint.InitVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P)}else{this.m_impulse=0}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2DistanceJoint.SolveVelocityConstraints_s_vpA);const vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2DistanceJoint.SolveVelocityConstraints_s_vpB);const Cdot=b2Vec2.DotVV(this.m_u,b2Vec2.SubVV(vpB,vpA,b2Vec2.s_t0));const impulse=-this.m_mass*(Cdot+this.m_bias+this.m_gamma*this.m_impulse);this.m_impulse+=impulse;const P=b2Vec2.MulSV(impulse,this.m_u,b2DistanceJoint.SolveVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){if(this.m_frequencyHz>0){return true}const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const u=this.m_u;u.x=cB.x+rB.x-cA.x-rA.x;u.y=cB.y+rB.y-cA.y-rA.y;const length=this.m_u.Normalize();let C=length-this.m_length;C=b2Clamp(C,-b2_maxLinearCorrection,b2_maxLinearCorrection);const impulse=-this.m_mass*C;const P=b2Vec2.MulSV(impulse,u,b2DistanceJoint.SolvePositionConstraints_s_P);cA.SelfMulSub(this.m_invMassA,P);aA-=this.m_invIA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(this.m_invMassB,P);aB+=this.m_invIB*b2Vec2.CrossVV(rB,P);data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return b2Abs(C)b2Sq(b2_maxLinearCorrection)){delta.SelfMul(b2_maxLinearCorrection/b2Sqrt(norm_sq))}if(norm_sq>b2Sq(b2_linearSlop)){done=false}body_c.x+=delta.x;body_c.y+=delta.y}return done}}class b2FrictionJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_frictionJoint);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2;this.maxForce=0;this.maxTorque=0}Initialize(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB)}}class b2FrictionJoint extends b2Joint{constructor(def){super(def);this.m_localAnchorA=new b2Vec2;this.m_localAnchorB=new b2Vec2;this.m_linearImpulse=new b2Vec2;this.m_angularImpulse=0;this.m_maxForce=0;this.m_maxTorque=0;this.m_indexA=0;this.m_indexB=0;this.m_rA=new b2Vec2;this.m_rB=new b2Vec2;this.m_localCenterA=new b2Vec2;this.m_localCenterB=new b2Vec2;this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_linearMass=new b2Mat22;this.m_angularMass=0;this.m_qA=new b2Rot;this.m_qB=new b2Rot;this.m_lalcA=new b2Vec2;this.m_lalcB=new b2Vec2;this.m_K=new b2Mat22;this.m_localAnchorA.Copy(def.localAnchorA);this.m_localAnchorB.Copy(def.localAnchorB);this.m_linearImpulse.SetZero();this.m_maxForce=b2Maybe(def.maxForce,0);this.m_maxTorque=b2Maybe(def.maxTorque,0);this.m_linearMass.SetZero()}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;const K=this.m_K;K.ex.x=mA+mB+iA*rA.y*rA.y+iB*rB.y*rB.y;K.ex.y=-iA*rA.x*rA.y-iB*rB.x*rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*rA.x*rA.x+iB*rB.x*rB.x;K.GetInverse(this.m_linearMass);this.m_angularMass=iA+iB;if(this.m_angularMass>0){this.m_angularMass=1/this.m_angularMass}if(data.step.warmStarting){this.m_linearImpulse.SelfMul(data.step.dtRatio);this.m_angularImpulse*=data.step.dtRatio;const P=this.m_linearImpulse;vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+this.m_angularImpulse);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+this.m_angularImpulse)}else{this.m_linearImpulse.SetZero();this.m_angularImpulse=0}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;const h=data.step.dt;{const Cdot=wB-wA;let impulse=-this.m_angularMass*Cdot;const oldImpulse=this.m_angularImpulse;const maxImpulse=h*this.m_maxTorque;this.m_angularImpulse=b2Clamp(this.m_angularImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_angularImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse}{const Cdot_v2=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2);const impulseV=b2Mat22.MulMV(this.m_linearMass,Cdot_v2,b2FrictionJoint.SolveVelocityConstraints_s_impulseV).SelfNeg();const oldImpulseV=b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV.Copy(this.m_linearImpulse);this.m_linearImpulse.SelfAdd(impulseV);const maxImpulse=h*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()>maxImpulse*maxImpulse){this.m_linearImpulse.Normalize();this.m_linearImpulse.SelfMul(maxImpulse)}b2Vec2.SubVV(this.m_linearImpulse,oldImpulseV,impulseV);vA.SelfMulSub(mA,impulseV);wA-=iA*b2Vec2.CrossVV(this.m_rA,impulseV);vB.SelfMulAdd(mB,impulseV);wB+=iB*b2Vec2.CrossVV(this.m_rB,impulseV)}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){return true}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out)}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out)}GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_linearImpulse.x;out.y=inv_dt*this.m_linearImpulse.y;return out}GetReactionTorque(inv_dt){return inv_dt*this.m_angularImpulse}GetLocalAnchorA(){return this.m_localAnchorA}GetLocalAnchorB(){return this.m_localAnchorB}SetMaxForce(force){this.m_maxForce=force}GetMaxForce(){return this.m_maxForce}SetMaxTorque(torque){this.m_maxTorque=torque}GetMaxTorque(){return this.m_maxTorque}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log(" const jd: b2FrictionJointDef = new b2FrictionJointDef();\n");log(" jd.bodyA = bodies[%d];\n",indexA);log(" jd.bodyB = bodies[%d];\n",indexB);log(" jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log(" jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log(" jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log(" jd.maxForce = %.15f;\n",this.m_maxForce);log(" jd.maxTorque = %.15f;\n",this.m_maxTorque);log(" joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index)}}b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2;b2FrictionJoint.SolveVelocityConstraints_s_impulseV=new b2Vec2;b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV=new b2Vec2;class b2GearJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_gearJoint);this.ratio=1}}class b2GearJoint extends b2Joint{constructor(def){super(def);this.m_typeA=exports.b2JointType.e_unknownJoint;this.m_typeB=exports.b2JointType.e_unknownJoint;this.m_localAnchorA=new b2Vec2;this.m_localAnchorB=new b2Vec2;this.m_localAnchorC=new b2Vec2;this.m_localAnchorD=new b2Vec2;this.m_localAxisC=new b2Vec2;this.m_localAxisD=new b2Vec2;this.m_referenceAngleA=0;this.m_referenceAngleB=0;this.m_constant=0;this.m_ratio=0;this.m_impulse=0;this.m_indexA=0;this.m_indexB=0;this.m_indexC=0;this.m_indexD=0;this.m_lcA=new b2Vec2;this.m_lcB=new b2Vec2;this.m_lcC=new b2Vec2;this.m_lcD=new b2Vec2;this.m_mA=0;this.m_mB=0;this.m_mC=0;this.m_mD=0;this.m_iA=0;this.m_iB=0;this.m_iC=0;this.m_iD=0;this.m_JvAC=new b2Vec2;this.m_JvBD=new b2Vec2;this.m_JwA=0;this.m_JwB=0;this.m_JwC=0;this.m_JwD=0;this.m_mass=0;this.m_qA=new b2Rot;this.m_qB=new b2Rot;this.m_qC=new b2Rot;this.m_qD=new b2Rot;this.m_lalcA=new b2Vec2;this.m_lalcB=new b2Vec2;this.m_lalcC=new b2Vec2;this.m_lalcD=new b2Vec2;this.m_joint1=def.joint1;this.m_joint2=def.joint2;this.m_typeA=this.m_joint1.GetType();this.m_typeB=this.m_joint2.GetType();let coordinateA,coordinateB;this.m_bodyC=this.m_joint1.GetBodyA();this.m_bodyA=this.m_joint1.GetBodyB();const xfA=this.m_bodyA.m_xf;const aA=this.m_bodyA.m_sweep.a;const xfC=this.m_bodyC.m_xf;const aC=this.m_bodyC.m_sweep.a;if(this.m_typeA===exports.b2JointType.e_revoluteJoint){const revolute=def.joint1;this.m_localAnchorC.Copy(revolute.m_localAnchorA);this.m_localAnchorA.Copy(revolute.m_localAnchorB);this.m_referenceAngleA=revolute.m_referenceAngle;this.m_localAxisC.SetZero();coordinateA=aA-aC-this.m_referenceAngleA}else{const prismatic=def.joint1;this.m_localAnchorC.Copy(prismatic.m_localAnchorA);this.m_localAnchorA.Copy(prismatic.m_localAnchorB);this.m_referenceAngleA=prismatic.m_referenceAngle;this.m_localAxisC.Copy(prismatic.m_localXAxisA);const pC=this.m_localAnchorC;const pA=b2Rot.MulTRV(xfC.q,b2Vec2.AddVV(b2Rot.MulRV(xfA.q,this.m_localAnchorA,b2Vec2.s_t0),b2Vec2.SubVV(xfA.p,xfC.p,b2Vec2.s_t1),b2Vec2.s_t0),b2Vec2.s_t0);coordinateA=b2Vec2.DotVV(b2Vec2.SubVV(pA,pC,b2Vec2.s_t0),this.m_localAxisC)}this.m_bodyD=this.m_joint2.GetBodyA();this.m_bodyB=this.m_joint2.GetBodyB();const xfB=this.m_bodyB.m_xf;const aB=this.m_bodyB.m_sweep.a;const xfD=this.m_bodyD.m_xf;const aD=this.m_bodyD.m_sweep.a;if(this.m_typeB===exports.b2JointType.e_revoluteJoint){const revolute=def.joint2;this.m_localAnchorD.Copy(revolute.m_localAnchorA);this.m_localAnchorB.Copy(revolute.m_localAnchorB);this.m_referenceAngleB=revolute.m_referenceAngle;this.m_localAxisD.SetZero();coordinateB=aB-aD-this.m_referenceAngleB}else{const prismatic=def.joint2;this.m_localAnchorD.Copy(prismatic.m_localAnchorA);this.m_localAnchorB.Copy(prismatic.m_localAnchorB);this.m_referenceAngleB=prismatic.m_referenceAngle;this.m_localAxisD.Copy(prismatic.m_localXAxisA);const pD=this.m_localAnchorD;const pB=b2Rot.MulTRV(xfD.q,b2Vec2.AddVV(b2Rot.MulRV(xfB.q,this.m_localAnchorB,b2Vec2.s_t0),b2Vec2.SubVV(xfB.p,xfD.p,b2Vec2.s_t1),b2Vec2.s_t0),b2Vec2.s_t0);coordinateB=b2Vec2.DotVV(b2Vec2.SubVV(pB,pD,b2Vec2.s_t0),this.m_localAxisD)}this.m_ratio=b2Maybe(def.ratio,1);this.m_constant=coordinateA+this.m_ratio*coordinateB;this.m_impulse=0}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_indexC=this.m_bodyC.m_islandIndex;this.m_indexD=this.m_bodyD.m_islandIndex;this.m_lcA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_lcB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_lcC.Copy(this.m_bodyC.m_sweep.localCenter);this.m_lcD.Copy(this.m_bodyD.m_sweep.localCenter);this.m_mA=this.m_bodyA.m_invMass;this.m_mB=this.m_bodyB.m_invMass;this.m_mC=this.m_bodyC.m_invMass;this.m_mD=this.m_bodyD.m_invMass;this.m_iA=this.m_bodyA.m_invI;this.m_iB=this.m_bodyB.m_invI;this.m_iC=this.m_bodyC.m_invI;this.m_iD=this.m_bodyD.m_invI;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const aC=data.positions[this.m_indexC].a;const vC=data.velocities[this.m_indexC].v;let wC=data.velocities[this.m_indexC].w;const aD=data.positions[this.m_indexD].a;const vD=data.velocities[this.m_indexD].v;let wD=data.velocities[this.m_indexD].w;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);const qC=this.m_qC.SetAngle(aC);const qD=this.m_qD.SetAngle(aD);this.m_mass=0;if(this.m_typeA===exports.b2JointType.e_revoluteJoint){this.m_JvAC.SetZero();this.m_JwA=1;this.m_JwC=1;this.m_mass+=this.m_iA+this.m_iC}else{const u=b2Rot.MulRV(qC,this.m_localAxisC,b2GearJoint.InitVelocityConstraints_s_u);b2Vec2.SubVV(this.m_localAnchorC,this.m_lcC,this.m_lalcC);const rC=b2Rot.MulRV(qC,this.m_lalcC,b2GearJoint.InitVelocityConstraints_s_rC);b2Vec2.SubVV(this.m_localAnchorA,this.m_lcA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,b2GearJoint.InitVelocityConstraints_s_rA);this.m_JvAC.Copy(u);this.m_JwC=b2Vec2.CrossVV(rC,u);this.m_JwA=b2Vec2.CrossVV(rA,u);this.m_mass+=this.m_mC+this.m_mA+this.m_iC*this.m_JwC*this.m_JwC+this.m_iA*this.m_JwA*this.m_JwA}if(this.m_typeB===exports.b2JointType.e_revoluteJoint){this.m_JvBD.SetZero();this.m_JwB=this.m_ratio;this.m_JwD=this.m_ratio;this.m_mass+=this.m_ratio*this.m_ratio*(this.m_iB+this.m_iD)}else{const u=b2Rot.MulRV(qD,this.m_localAxisD,b2GearJoint.InitVelocityConstraints_s_u);b2Vec2.SubVV(this.m_localAnchorD,this.m_lcD,this.m_lalcD);const rD=b2Rot.MulRV(qD,this.m_lalcD,b2GearJoint.InitVelocityConstraints_s_rD);b2Vec2.SubVV(this.m_localAnchorB,this.m_lcB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,b2GearJoint.InitVelocityConstraints_s_rB);b2Vec2.MulSV(this.m_ratio,u,this.m_JvBD);this.m_JwD=this.m_ratio*b2Vec2.CrossVV(rD,u);this.m_JwB=this.m_ratio*b2Vec2.CrossVV(rB,u);this.m_mass+=this.m_ratio*this.m_ratio*(this.m_mD+this.m_mB)+this.m_iD*this.m_JwD*this.m_JwD+this.m_iB*this.m_JwB*this.m_JwB}this.m_mass=this.m_mass>0?1/this.m_mass:0;if(data.step.warmStarting){vA.SelfMulAdd(this.m_mA*this.m_impulse,this.m_JvAC);wA+=this.m_iA*this.m_impulse*this.m_JwA;vB.SelfMulAdd(this.m_mB*this.m_impulse,this.m_JvBD);wB+=this.m_iB*this.m_impulse*this.m_JwB;vC.SelfMulSub(this.m_mC*this.m_impulse,this.m_JvAC);wC-=this.m_iC*this.m_impulse*this.m_JwC;vD.SelfMulSub(this.m_mD*this.m_impulse,this.m_JvBD);wD-=this.m_iD*this.m_impulse*this.m_JwD}else{this.m_impulse=0}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;data.velocities[this.m_indexC].w=wC;data.velocities[this.m_indexD].w=wD}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const vC=data.velocities[this.m_indexC].v;let wC=data.velocities[this.m_indexC].w;const vD=data.velocities[this.m_indexD].v;let wD=data.velocities[this.m_indexD].w;let Cdot=b2Vec2.DotVV(this.m_JvAC,b2Vec2.SubVV(vA,vC,b2Vec2.s_t0))+b2Vec2.DotVV(this.m_JvBD,b2Vec2.SubVV(vB,vD,b2Vec2.s_t0));Cdot+=this.m_JwA*wA-this.m_JwC*wC+(this.m_JwB*wB-this.m_JwD*wD);const impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;vA.SelfMulAdd(this.m_mA*impulse,this.m_JvAC);wA+=this.m_iA*impulse*this.m_JwA;vB.SelfMulAdd(this.m_mB*impulse,this.m_JvBD);wB+=this.m_iB*impulse*this.m_JwB;vC.SelfMulSub(this.m_mC*impulse,this.m_JvAC);wC-=this.m_iC*impulse*this.m_JwC;vD.SelfMulSub(this.m_mD*impulse,this.m_JvBD);wD-=this.m_iD*impulse*this.m_JwD;data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;data.velocities[this.m_indexC].w=wC;data.velocities[this.m_indexD].w=wD}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const cC=data.positions[this.m_indexC].c;let aC=data.positions[this.m_indexC].a;const cD=data.positions[this.m_indexD].c;let aD=data.positions[this.m_indexD].a;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);const qC=this.m_qC.SetAngle(aC);const qD=this.m_qD.SetAngle(aD);const linearError=0;let coordinateA,coordinateB;const JvAC=this.m_JvAC;const JvBD=this.m_JvBD;let JwA,JwB,JwC,JwD;let mass=0;if(this.m_typeA===exports.b2JointType.e_revoluteJoint){JvAC.SetZero();JwA=1;JwC=1;mass+=this.m_iA+this.m_iC;coordinateA=aA-aC-this.m_referenceAngleA}else{const u=b2Rot.MulRV(qC,this.m_localAxisC,b2GearJoint.SolvePositionConstraints_s_u);const rC=b2Rot.MulRV(qC,this.m_lalcC,b2GearJoint.SolvePositionConstraints_s_rC);const rA=b2Rot.MulRV(qA,this.m_lalcA,b2GearJoint.SolvePositionConstraints_s_rA);JvAC.Copy(u);JwC=b2Vec2.CrossVV(rC,u);JwA=b2Vec2.CrossVV(rA,u);mass+=this.m_mC+this.m_mA+this.m_iC*JwC*JwC+this.m_iA*JwA*JwA;const pC=this.m_lalcC;const pA=b2Rot.MulTRV(qC,b2Vec2.AddVV(rA,b2Vec2.SubVV(cA,cC,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.s_t0);coordinateA=b2Vec2.DotVV(b2Vec2.SubVV(pA,pC,b2Vec2.s_t0),this.m_localAxisC)}if(this.m_typeB===exports.b2JointType.e_revoluteJoint){JvBD.SetZero();JwB=this.m_ratio;JwD=this.m_ratio;mass+=this.m_ratio*this.m_ratio*(this.m_iB+this.m_iD);coordinateB=aB-aD-this.m_referenceAngleB}else{const u=b2Rot.MulRV(qD,this.m_localAxisD,b2GearJoint.SolvePositionConstraints_s_u);const rD=b2Rot.MulRV(qD,this.m_lalcD,b2GearJoint.SolvePositionConstraints_s_rD);const rB=b2Rot.MulRV(qB,this.m_lalcB,b2GearJoint.SolvePositionConstraints_s_rB);b2Vec2.MulSV(this.m_ratio,u,JvBD);JwD=this.m_ratio*b2Vec2.CrossVV(rD,u);JwB=this.m_ratio*b2Vec2.CrossVV(rB,u);mass+=this.m_ratio*this.m_ratio*(this.m_mD+this.m_mB)+this.m_iD*JwD*JwD+this.m_iB*JwB*JwB;const pD=this.m_lalcD;const pB=b2Rot.MulTRV(qD,b2Vec2.AddVV(rB,b2Vec2.SubVV(cB,cD,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.s_t0);coordinateB=b2Vec2.DotVV(b2Vec2.SubVV(pB,pD,b2Vec2.s_t0),this.m_localAxisD)}const C=coordinateA+this.m_ratio*coordinateB-this.m_constant;let impulse=0;if(mass>0){impulse=-C/mass}cA.SelfMulAdd(this.m_mA*impulse,JvAC);aA+=this.m_iA*impulse*JwA;cB.SelfMulAdd(this.m_mB*impulse,JvBD);aB+=this.m_iB*impulse*JwB;cC.SelfMulSub(this.m_mC*impulse,JvAC);aC-=this.m_iC*impulse*JwC;cD.SelfMulSub(this.m_mD*impulse,JvBD);aD-=this.m_iD*impulse*JwD;data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;data.positions[this.m_indexC].a=aC;data.positions[this.m_indexD].a=aD;return linearError0){this.m_angularMass=1/this.m_angularMass}b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),this.m_linearError);this.m_angularError=aB-aA-this.m_angularOffset;if(data.step.warmStarting){this.m_linearImpulse.SelfMul(data.step.dtRatio);this.m_angularImpulse*=data.step.dtRatio;const P=this.m_linearImpulse;vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(rA,P)+this.m_angularImpulse);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(rB,P)+this.m_angularImpulse)}else{this.m_linearImpulse.SetZero();this.m_angularImpulse=0}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;const h=data.step.dt;const inv_h=data.step.inv_dt;{const Cdot=wB-wA+inv_h*this.m_correctionFactor*this.m_angularError;let impulse=-this.m_angularMass*Cdot;const oldImpulse=this.m_angularImpulse;const maxImpulse=h*this.m_maxTorque;this.m_angularImpulse=b2Clamp(this.m_angularImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_angularImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse}{const rA=this.m_rA;const rB=this.m_rB;const Cdot_v2=b2Vec2.AddVV(b2Vec2.SubVV(b2Vec2.AddVV(vB,b2Vec2.CrossSV(wB,rB,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.AddVV(vA,b2Vec2.CrossSV(wA,rA,b2Vec2.s_t1),b2Vec2.s_t1),b2Vec2.s_t2),b2Vec2.MulSV(inv_h*this.m_correctionFactor,this.m_linearError,b2Vec2.s_t3),b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2);const impulse_v2=b2Mat22.MulMV(this.m_linearMass,Cdot_v2,b2MotorJoint.SolveVelocityConstraints_s_impulse_v2).SelfNeg();const oldImpulse_v2=b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2.Copy(this.m_linearImpulse);this.m_linearImpulse.SelfAdd(impulse_v2);const maxImpulse=h*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()>maxImpulse*maxImpulse){this.m_linearImpulse.Normalize();this.m_linearImpulse.SelfMul(maxImpulse)}b2Vec2.SubVV(this.m_linearImpulse,oldImpulse_v2,impulse_v2);vA.SelfMulSub(mA,impulse_v2);wA-=iA*b2Vec2.CrossVV(rA,impulse_v2);vB.SelfMulAdd(mB,impulse_v2);wB+=iB*b2Vec2.CrossVV(rB,impulse_v2)}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){return true}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log(" const jd: b2MotorJointDef = new b2MotorJointDef();\n");log(" jd.bodyA = bodies[%d];\n",indexA);log(" jd.bodyB = bodies[%d];\n",indexB);log(" jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log(" jd.linearOffset.Set(%.15f, %.15f);\n",this.m_linearOffset.x,this.m_linearOffset.y);log(" jd.angularOffset = %.15f;\n",this.m_angularOffset);log(" jd.maxForce = %.15f;\n",this.m_maxForce);log(" jd.maxTorque = %.15f;\n",this.m_maxTorque);log(" jd.correctionFactor = %.15f;\n",this.m_correctionFactor);log(" joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index)}}b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2;b2MotorJoint.SolveVelocityConstraints_s_impulse_v2=new b2Vec2;b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2=new b2Vec2;class b2MouseJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_mouseJoint);this.target=new b2Vec2;this.maxForce=0;this.frequencyHz=5;this.dampingRatio=0.7}}class b2MouseJoint extends b2Joint{constructor(def){super(def);this.m_localAnchorB=new b2Vec2;this.m_targetA=new b2Vec2;this.m_frequencyHz=0;this.m_dampingRatio=0;this.m_beta=0;this.m_impulse=new b2Vec2;this.m_maxForce=0;this.m_gamma=0;this.m_indexA=0;this.m_indexB=0;this.m_rB=new b2Vec2;this.m_localCenterB=new b2Vec2;this.m_invMassB=0;this.m_invIB=0;this.m_mass=new b2Mat22;this.m_C=new b2Vec2;this.m_qB=new b2Rot;this.m_lalcB=new b2Vec2;this.m_K=new b2Mat22;this.m_targetA.Copy(b2Maybe(def.target,b2Vec2.ZERO));b2Transform.MulTXV(this.m_bodyB.GetTransform(),this.m_targetA,this.m_localAnchorB);this.m_maxForce=b2Maybe(def.maxForce,0);this.m_impulse.SetZero();this.m_frequencyHz=b2Maybe(def.frequencyHz,0);this.m_dampingRatio=b2Maybe(def.dampingRatio,0);this.m_beta=0;this.m_gamma=0}SetTarget(target){if(!this.m_bodyB.IsAwake()){this.m_bodyB.SetAwake(true)}this.m_targetA.Copy(target)}GetTarget(){return this.m_targetA}SetMaxForce(maxForce){this.m_maxForce=maxForce}GetMaxForce(){return this.m_maxForce}SetFrequency(hz){this.m_frequencyHz=hz}GetFrequency(){return this.m_frequencyHz}SetDampingRatio(ratio){this.m_dampingRatio=ratio}GetDampingRatio(){return this.m_dampingRatio}InitVelocityConstraints(data){this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIB=this.m_bodyB.m_invI;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qB=this.m_qB.SetAngle(aB);const mass=this.m_bodyB.GetMass();const omega=2*b2_pi*this.m_frequencyHz;const d=2*mass*this.m_dampingRatio*omega;const k=mass*(omega*omega);const h=data.step.dt;this.m_gamma=h*(d+h*k);if(this.m_gamma!==0){this.m_gamma=1/this.m_gamma}this.m_beta=h*k*this.m_gamma;b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const K=this.m_K;K.ex.x=this.m_invMassB+this.m_invIB*this.m_rB.y*this.m_rB.y+this.m_gamma;K.ex.y=-this.m_invIB*this.m_rB.x*this.m_rB.y;K.ey.x=K.ex.y;K.ey.y=this.m_invMassB+this.m_invIB*this.m_rB.x*this.m_rB.x+this.m_gamma;K.GetInverse(this.m_mass);this.m_C.x=cB.x+this.m_rB.x-this.m_targetA.x;this.m_C.y=cB.y+this.m_rB.y-this.m_targetA.y;this.m_C.SelfMul(this.m_beta);wB*=0.98;if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);vB.x+=this.m_invMassB*this.m_impulse.x;vB.y+=this.m_invMassB*this.m_impulse.y;wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,this.m_impulse)}else{this.m_impulse.SetZero()}data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const Cdot=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2MouseJoint.SolveVelocityConstraints_s_Cdot);const impulse=b2Mat22.MulMV(this.m_mass,b2Vec2.AddVV(Cdot,b2Vec2.AddVV(this.m_C,b2Vec2.MulSV(this.m_gamma,this.m_impulse,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.s_t0).SelfNeg(),b2MouseJoint.SolveVelocityConstraints_s_impulse);const oldImpulse=b2MouseJoint.SolveVelocityConstraints_s_oldImpulse.Copy(this.m_impulse);this.m_impulse.SelfAdd(impulse);const maxImpulse=data.step.dt*this.m_maxForce;if(this.m_impulse.LengthSquared()>maxImpulse*maxImpulse){this.m_impulse.SelfMul(maxImpulse/this.m_impulse.Length())}b2Vec2.SubVV(this.m_impulse,oldImpulse,impulse);vB.SelfMulAdd(this.m_invMassB,impulse);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,impulse);data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){return true}GetAnchorA(out){out.x=this.m_targetA.x;out.y=this.m_targetA.y;return out}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out)}GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt,this.m_impulse,out)}GetReactionTorque(inv_dt){return 0}Dump(log){log("Mouse joint dumping is not supported.\n")}ShiftOrigin(newOrigin){this.m_targetA.SelfSub(newOrigin)}}b2MouseJoint.SolveVelocityConstraints_s_Cdot=new b2Vec2;b2MouseJoint.SolveVelocityConstraints_s_impulse=new b2Vec2;b2MouseJoint.SolveVelocityConstraints_s_oldImpulse=new b2Vec2;class b2PrismaticJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_prismaticJoint);this.localAnchorA=new b2Vec2;this.localAnchorB=new b2Vec2;this.localAxisA=new b2Vec2(1,0);this.referenceAngle=0;this.enableLimit=false;this.lowerTranslation=0;this.upperTranslation=0;this.enableMotor=false;this.maxMotorForce=0;this.motorSpeed=0}Initialize(bA,bB,anchor,axis){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.bodyA.GetLocalVector(axis,this.localAxisA);this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle()}}class b2PrismaticJoint extends b2Joint{constructor(def){super(def);this.m_localAnchorA=new b2Vec2;this.m_localAnchorB=new b2Vec2;this.m_localXAxisA=new b2Vec2;this.m_localYAxisA=new b2Vec2;this.m_referenceAngle=0;this.m_impulse=new b2Vec3(0,0,0);this.m_motorImpulse=0;this.m_lowerTranslation=0;this.m_upperTranslation=0;this.m_maxMotorForce=0;this.m_motorSpeed=0;this.m_enableLimit=false;this.m_enableMotor=false;this.m_limitState=exports.b2LimitState.e_inactiveLimit;this.m_indexA=0;this.m_indexB=0;this.m_localCenterA=new b2Vec2;this.m_localCenterB=new b2Vec2;this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_axis=new b2Vec2(0,0);this.m_perp=new b2Vec2(0,0);this.m_s1=0;this.m_s2=0;this.m_a1=0;this.m_a2=0;this.m_K=new b2Mat33;this.m_K3=new b2Mat33;this.m_K2=new b2Mat22;this.m_motorMass=0;this.m_qA=new b2Rot;this.m_qB=new b2Rot;this.m_lalcA=new b2Vec2;this.m_lalcB=new b2Vec2;this.m_rA=new b2Vec2;this.m_rB=new b2Vec2;this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));this.m_localXAxisA.Copy(b2Maybe(def.localAxisA,new b2Vec2(1,0))).SelfNormalize();b2Vec2.CrossOneV(this.m_localXAxisA,this.m_localYAxisA);this.m_referenceAngle=b2Maybe(def.referenceAngle,0);this.m_lowerTranslation=b2Maybe(def.lowerTranslation,0);this.m_upperTranslation=b2Maybe(def.upperTranslation,0);this.m_maxMotorForce=b2Maybe(def.maxMotorForce,0);this.m_motorSpeed=b2Maybe(def.motorSpeed,0);this.m_enableLimit=b2Maybe(def.enableLimit,false);this.m_enableMotor=b2Maybe(def.enableMotor,false)}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const d=b2Vec2.AddVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),b2Vec2.SubVV(rB,rA,b2Vec2.s_t1),b2PrismaticJoint.InitVelocityConstraints_s_d);const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;{b2Rot.MulRV(qA,this.m_localXAxisA,this.m_axis);this.m_a1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_axis);this.m_a2=b2Vec2.CrossVV(rB,this.m_axis);this.m_motorMass=mA+mB+iA*this.m_a1*this.m_a1+iB*this.m_a2*this.m_a2;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass}}{b2Rot.MulRV(qA,this.m_localYAxisA,this.m_perp);this.m_s1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_perp);this.m_s2=b2Vec2.CrossVV(rB,this.m_perp);this.m_K.ex.x=mA+mB+iA*this.m_s1*this.m_s1+iB*this.m_s2*this.m_s2;this.m_K.ex.y=iA*this.m_s1+iB*this.m_s2;this.m_K.ex.z=iA*this.m_s1*this.m_a1+iB*this.m_s2*this.m_a2;this.m_K.ey.x=this.m_K.ex.y;this.m_K.ey.y=iA+iB;if(this.m_K.ey.y===0){this.m_K.ey.y=1}this.m_K.ey.z=iA*this.m_a1+iB*this.m_a2;this.m_K.ez.x=this.m_K.ex.z;this.m_K.ez.y=this.m_K.ey.z;this.m_K.ez.z=mA+mB+iA*this.m_a1*this.m_a1+iB*this.m_a2*this.m_a2}if(this.m_enableLimit){const jointTranslation=b2Vec2.DotVV(this.m_axis,d);if(b2Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2_linearSlop){this.m_limitState=exports.b2LimitState.e_equalLimits}else if(jointTranslation<=this.m_lowerTranslation){if(this.m_limitState!==exports.b2LimitState.e_atLowerLimit){this.m_limitState=exports.b2LimitState.e_atLowerLimit;this.m_impulse.z=0}}else if(jointTranslation>=this.m_upperTranslation){if(this.m_limitState!==exports.b2LimitState.e_atUpperLimit){this.m_limitState=exports.b2LimitState.e_atUpperLimit;this.m_impulse.z=0}}else{this.m_limitState=exports.b2LimitState.e_inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=exports.b2LimitState.e_inactiveLimit;this.m_impulse.z=0}if(!this.m_enableMotor){this.m_motorImpulse=0}if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);this.m_motorImpulse*=data.step.dtRatio;const P=b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse.x,this.m_perp,b2Vec2.s_t0),b2Vec2.MulSV(this.m_motorImpulse+this.m_impulse.z,this.m_axis,b2Vec2.s_t1),b2PrismaticJoint.InitVelocityConstraints_s_P);const LA=this.m_impulse.x*this.m_s1+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a1;const LB=this.m_impulse.x*this.m_s2+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a2;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB}else{this.m_impulse.SetZero();this.m_motorImpulse=0}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;if(this.m_enableMotor&&this.m_limitState!==exports.b2LimitState.e_equalLimits){const Cdot=b2Vec2.DotVV(this.m_axis,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_a2*wB-this.m_a1*wA;let impulse=this.m_motorMass*(this.m_motorSpeed-Cdot);const oldImpulse=this.m_motorImpulse;const maxImpulse=data.step.dt*this.m_maxMotorForce;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;const P=b2Vec2.MulSV(impulse,this.m_axis,b2PrismaticJoint.SolveVelocityConstraints_s_P);const LA=impulse*this.m_a1;const LB=impulse*this.m_a2;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB}const Cdot1_x=b2Vec2.DotVV(this.m_perp,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_s2*wB-this.m_s1*wA;const Cdot1_y=wB-wA;if(this.m_enableLimit&&this.m_limitState!==exports.b2LimitState.e_inactiveLimit){const Cdot2=b2Vec2.DotVV(this.m_axis,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_a2*wB-this.m_a1*wA;const f1=b2PrismaticJoint.SolveVelocityConstraints_s_f1.Copy(this.m_impulse);const df3=this.m_K.Solve33(-Cdot1_x,-Cdot1_y,-Cdot2,b2PrismaticJoint.SolveVelocityConstraints_s_df3);this.m_impulse.SelfAdd(df3);if(this.m_limitState===exports.b2LimitState.e_atLowerLimit){this.m_impulse.z=b2Max(this.m_impulse.z,0)}else if(this.m_limitState===exports.b2LimitState.e_atUpperLimit){this.m_impulse.z=b2Min(this.m_impulse.z,0)}const b_x=-Cdot1_x-(this.m_impulse.z-f1.z)*this.m_K.ez.x;const b_y=-Cdot1_y-(this.m_impulse.z-f1.z)*this.m_K.ez.y;const f2r=this.m_K.Solve22(b_x,b_y,b2PrismaticJoint.SolveVelocityConstraints_s_f2r);f2r.x+=f1.x;f2r.y+=f1.y;this.m_impulse.x=f2r.x;this.m_impulse.y=f2r.y;df3.x=this.m_impulse.x-f1.x;df3.y=this.m_impulse.y-f1.y;df3.z=this.m_impulse.z-f1.z;const P=b2Vec2.AddVV(b2Vec2.MulSV(df3.x,this.m_perp,b2Vec2.s_t0),b2Vec2.MulSV(df3.z,this.m_axis,b2Vec2.s_t1),b2PrismaticJoint.SolveVelocityConstraints_s_P);const LA=df3.x*this.m_s1+df3.y+df3.z*this.m_a1;const LB=df3.x*this.m_s2+df3.y+df3.z*this.m_a2;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB}else{const df2=this.m_K.Solve22(-Cdot1_x,-Cdot1_y,b2PrismaticJoint.SolveVelocityConstraints_s_df2);this.m_impulse.x+=df2.x;this.m_impulse.y+=df2.y;const P=b2Vec2.MulSV(df2.x,this.m_perp,b2PrismaticJoint.SolveVelocityConstraints_s_P);const LA=df2.x*this.m_s1+df2.y;const LB=df2.x*this.m_s2+df2.y;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const d=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2PrismaticJoint.SolvePositionConstraints_s_d);const axis=b2Rot.MulRV(qA,this.m_localXAxisA,this.m_axis);const a1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),axis);const a2=b2Vec2.CrossVV(rB,axis);const perp=b2Rot.MulRV(qA,this.m_localYAxisA,this.m_perp);const s1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),perp);const s2=b2Vec2.CrossVV(rB,perp);let impulse=b2PrismaticJoint.SolvePositionConstraints_s_impulse;const C1_x=b2Vec2.DotVV(perp,d);const C1_y=aB-aA-this.m_referenceAngle;let linearError=b2Abs(C1_x);const angularError=b2Abs(C1_y);let active=false;let C2=0;if(this.m_enableLimit){const translation=b2Vec2.DotVV(axis,d);if(b2Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2_linearSlop){C2=b2Clamp(translation,-b2_maxLinearCorrection,b2_maxLinearCorrection);linearError=b2Max(linearError,b2Abs(translation));active=true}else if(translation<=this.m_lowerTranslation){C2=b2Clamp(translation-this.m_lowerTranslation+b2_linearSlop,-b2_maxLinearCorrection,0);linearError=b2Max(linearError,this.m_lowerTranslation-translation);active=true}else if(translation>=this.m_upperTranslation){C2=b2Clamp(translation-this.m_upperTranslation-b2_linearSlop,0,b2_maxLinearCorrection);linearError=b2Max(linearError,translation-this.m_upperTranslation);active=true}}if(active){const k11=mA+mB+iA*s1*s1+iB*s2*s2;const k12=iA*s1+iB*s2;const k13=iA*s1*a1+iB*s2*a2;let k22=iA+iB;if(k22===0){k22=1}const k23=iA*a1+iB*a2;const k33=mA+mB+iA*a1*a1+iB*a2*a2;const K=this.m_K3;K.ex.SetXYZ(k11,k12,k13);K.ey.SetXYZ(k12,k22,k23);K.ez.SetXYZ(k13,k23,k33);impulse=K.Solve33(-C1_x,-C1_y,-C2,impulse)}else{const k11=mA+mB+iA*s1*s1+iB*s2*s2;const k12=iA*s1+iB*s2;let k22=iA+iB;if(k22===0){k22=1}const K2=this.m_K2;K2.ex.Set(k11,k12);K2.ey.Set(k12,k22);const impulse1=K2.Solve(-C1_x,-C1_y,b2PrismaticJoint.SolvePositionConstraints_s_impulse1);impulse.x=impulse1.x;impulse.y=impulse1.y;impulse.z=0}const P=b2Vec2.AddVV(b2Vec2.MulSV(impulse.x,perp,b2Vec2.s_t0),b2Vec2.MulSV(impulse.z,axis,b2Vec2.s_t1),b2PrismaticJoint.SolvePositionConstraints_s_P);const LA=impulse.x*s1+impulse.y+impulse.z*a1;const LB=impulse.x*s2+impulse.y+impulse.z*a2;cA.SelfMulSub(mA,P);aA-=iA*LA;cB.SelfMulAdd(mB,P);aB+=iB*LB;data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return linearError<=b2_linearSlop&&angularError<=b2_angularSlop}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out)}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out)}GetReactionForce(inv_dt,out){out.x=inv_dt*(this.m_impulse.x*this.m_perp.x+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.x);out.y=inv_dt*(this.m_impulse.x*this.m_perp.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.y);return out}GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.y}GetLocalAnchorA(){return this.m_localAnchorA}GetLocalAnchorB(){return this.m_localAnchorB}GetLocalAxisA(){return this.m_localXAxisA}GetReferenceAngle(){return this.m_referenceAngle}GetJointTranslation(){const pA=this.m_bodyA.GetWorldPoint(this.m_localAnchorA,b2PrismaticJoint.GetJointTranslation_s_pA);const pB=this.m_bodyB.GetWorldPoint(this.m_localAnchorB,b2PrismaticJoint.GetJointTranslation_s_pB);const d=b2Vec2.SubVV(pB,pA,b2PrismaticJoint.GetJointTranslation_s_d);const axis=this.m_bodyA.GetWorldVector(this.m_localXAxisA,b2PrismaticJoint.GetJointTranslation_s_axis);const translation=b2Vec2.DotVV(d,axis);return translation}GetJointSpeed(){const bA=this.m_bodyA;const bB=this.m_bodyB;b2Vec2.SubVV(this.m_localAnchorA,bA.m_sweep.localCenter,this.m_lalcA);const rA=b2Rot.MulRV(bA.m_xf.q,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,bB.m_sweep.localCenter,this.m_lalcB);const rB=b2Rot.MulRV(bB.m_xf.q,this.m_lalcB,this.m_rB);const pA=b2Vec2.AddVV(bA.m_sweep.c,rA,b2Vec2.s_t0);const pB=b2Vec2.AddVV(bB.m_sweep.c,rB,b2Vec2.s_t1);const d=b2Vec2.SubVV(pB,pA,b2Vec2.s_t2);const axis=bA.GetWorldVector(this.m_localXAxisA,this.m_axis);const vA=bA.m_linearVelocity;const vB=bB.m_linearVelocity;const wA=bA.m_angularVelocity;const wB=bB.m_angularVelocity;const speed=b2Vec2.DotVV(d,b2Vec2.CrossSV(wA,axis,b2Vec2.s_t0))+b2Vec2.DotVV(axis,b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,rA,b2Vec2.s_t1),b2Vec2.s_t0));return speed}IsLimitEnabled(){return this.m_enableLimit}EnableLimit(flag){if(flag!==this.m_enableLimit){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag;this.m_impulse.z=0}}GetLowerLimit(){return this.m_lowerTranslation}GetUpperLimit(){return this.m_upperTranslation}SetLimits(lower,upper){if(lower!==this.m_lowerTranslation||upper!==this.m_upperTranslation){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_lowerTranslation=lower;this.m_upperTranslation=upper;this.m_impulse.z=0}}IsMotorEnabled(){return this.m_enableMotor}EnableMotor(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag}SetMotorSpeed(speed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed}GetMotorSpeed(){return this.m_motorSpeed}SetMaxMotorForce(force){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorForce=force}GetMaxMotorForce(){return this.m_maxMotorForce}GetMotorForce(inv_dt){return inv_dt*this.m_motorImpulse}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log(" const jd: b2PrismaticJointDef = new b2PrismaticJointDef();\n");log(" jd.bodyA = bodies[%d];\n",indexA);log(" jd.bodyB = bodies[%d];\n",indexB);log(" jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log(" jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log(" jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log(" jd.localAxisA.Set(%.15f, %.15f);\n",this.m_localXAxisA.x,this.m_localXAxisA.y);log(" jd.referenceAngle = %.15f;\n",this.m_referenceAngle);log(" jd.enableLimit = %s;\n",this.m_enableLimit?"true":"false");log(" jd.lowerTranslation = %.15f;\n",this.m_lowerTranslation);log(" jd.upperTranslation = %.15f;\n",this.m_upperTranslation);log(" jd.enableMotor = %s;\n",this.m_enableMotor?"true":"false");log(" jd.motorSpeed = %.15f;\n",this.m_motorSpeed);log(" jd.maxMotorForce = %.15f;\n",this.m_maxMotorForce);log(" joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index)}}b2PrismaticJoint.InitVelocityConstraints_s_d=new b2Vec2;b2PrismaticJoint.InitVelocityConstraints_s_P=new b2Vec2;b2PrismaticJoint.SolveVelocityConstraints_s_P=new b2Vec2;b2PrismaticJoint.SolveVelocityConstraints_s_f2r=new b2Vec2;b2PrismaticJoint.SolveVelocityConstraints_s_f1=new b2Vec3;b2PrismaticJoint.SolveVelocityConstraints_s_df3=new b2Vec3;b2PrismaticJoint.SolveVelocityConstraints_s_df2=new b2Vec2;b2PrismaticJoint.SolvePositionConstraints_s_d=new b2Vec2;b2PrismaticJoint.SolvePositionConstraints_s_impulse=new b2Vec3;b2PrismaticJoint.SolvePositionConstraints_s_impulse1=new b2Vec2;b2PrismaticJoint.SolvePositionConstraints_s_P=new b2Vec2;b2PrismaticJoint.GetJointTranslation_s_pA=new b2Vec2;b2PrismaticJoint.GetJointTranslation_s_pB=new b2Vec2;b2PrismaticJoint.GetJointTranslation_s_d=new b2Vec2;b2PrismaticJoint.GetJointTranslation_s_axis=new b2Vec2;const b2_minPulleyLength=2;class b2PulleyJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_pulleyJoint);this.groundAnchorA=new b2Vec2(-1,1);this.groundAnchorB=new b2Vec2(1,1);this.localAnchorA=new b2Vec2(-1,0);this.localAnchorB=new b2Vec2(1,0);this.lengthA=0;this.lengthB=0;this.ratio=1;this.collideConnected=true}Initialize(bA,bB,groundA,groundB,anchorA,anchorB,r){this.bodyA=bA;this.bodyB=bB;this.groundAnchorA.Copy(groundA);this.groundAnchorB.Copy(groundB);this.bodyA.GetLocalPoint(anchorA,this.localAnchorA);this.bodyB.GetLocalPoint(anchorB,this.localAnchorB);this.lengthA=b2Vec2.DistanceVV(anchorA,groundA);this.lengthB=b2Vec2.DistanceVV(anchorB,groundB);this.ratio=r}}class b2PulleyJoint extends b2Joint{constructor(def){super(def);this.m_groundAnchorA=new b2Vec2;this.m_groundAnchorB=new b2Vec2;this.m_lengthA=0;this.m_lengthB=0;this.m_localAnchorA=new b2Vec2;this.m_localAnchorB=new b2Vec2;this.m_constant=0;this.m_ratio=0;this.m_impulse=0;this.m_indexA=0;this.m_indexB=0;this.m_uA=new b2Vec2;this.m_uB=new b2Vec2;this.m_rA=new b2Vec2;this.m_rB=new b2Vec2;this.m_localCenterA=new b2Vec2;this.m_localCenterB=new b2Vec2;this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_mass=0;this.m_qA=new b2Rot;this.m_qB=new b2Rot;this.m_lalcA=new b2Vec2;this.m_lalcB=new b2Vec2;this.m_groundAnchorA.Copy(b2Maybe(def.groundAnchorA,new b2Vec2(-1,1)));this.m_groundAnchorB.Copy(b2Maybe(def.groundAnchorB,new b2Vec2(1,0)));this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,new b2Vec2(-1,0)));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,new b2Vec2(1,0)));this.m_lengthA=b2Maybe(def.lengthA,0);this.m_lengthB=b2Maybe(def.lengthB,0);this.m_ratio=b2Maybe(def.ratio,1);this.m_constant=b2Maybe(def.lengthA,0)+this.m_ratio*b2Maybe(def.lengthB,0);this.m_impulse=0}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);this.m_uA.Copy(cA).SelfAdd(this.m_rA).SelfSub(this.m_groundAnchorA);this.m_uB.Copy(cB).SelfAdd(this.m_rB).SelfSub(this.m_groundAnchorB);const lengthA=this.m_uA.Length();const lengthB=this.m_uB.Length();if(lengthA>10*b2_linearSlop){this.m_uA.SelfMul(1/lengthA)}else{this.m_uA.SetZero()}if(lengthB>10*b2_linearSlop){this.m_uB.SelfMul(1/lengthB)}else{this.m_uB.SetZero()}const ruA=b2Vec2.CrossVV(this.m_rA,this.m_uA);const ruB=b2Vec2.CrossVV(this.m_rB,this.m_uB);const mA=this.m_invMassA+this.m_invIA*ruA*ruA;const mB=this.m_invMassB+this.m_invIB*ruB*ruB;this.m_mass=mA+this.m_ratio*this.m_ratio*mB;if(this.m_mass>0){this.m_mass=1/this.m_mass}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;const PA=b2Vec2.MulSV(-this.m_impulse,this.m_uA,b2PulleyJoint.InitVelocityConstraints_s_PA);const PB=b2Vec2.MulSV(-this.m_ratio*this.m_impulse,this.m_uB,b2PulleyJoint.InitVelocityConstraints_s_PB);vA.SelfMulAdd(this.m_invMassA,PA);wA+=this.m_invIA*b2Vec2.CrossVV(this.m_rA,PA);vB.SelfMulAdd(this.m_invMassB,PB);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,PB)}else{this.m_impulse=0}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2PulleyJoint.SolveVelocityConstraints_s_vpA);const vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2PulleyJoint.SolveVelocityConstraints_s_vpB);const Cdot=-b2Vec2.DotVV(this.m_uA,vpA)-this.m_ratio*b2Vec2.DotVV(this.m_uB,vpB);const impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;const PA=b2Vec2.MulSV(-impulse,this.m_uA,b2PulleyJoint.SolveVelocityConstraints_s_PA);const PB=b2Vec2.MulSV(-this.m_ratio*impulse,this.m_uB,b2PulleyJoint.SolveVelocityConstraints_s_PB);vA.SelfMulAdd(this.m_invMassA,PA);wA+=this.m_invIA*b2Vec2.CrossVV(this.m_rA,PA);vB.SelfMulAdd(this.m_invMassB,PB);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,PB);data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const uA=this.m_uA.Copy(cA).SelfAdd(rA).SelfSub(this.m_groundAnchorA);const uB=this.m_uB.Copy(cB).SelfAdd(rB).SelfSub(this.m_groundAnchorB);const lengthA=uA.Length();const lengthB=uB.Length();if(lengthA>10*b2_linearSlop){uA.SelfMul(1/lengthA)}else{uA.SetZero()}if(lengthB>10*b2_linearSlop){uB.SelfMul(1/lengthB)}else{uB.SetZero()}const ruA=b2Vec2.CrossVV(rA,uA);const ruB=b2Vec2.CrossVV(rB,uB);const mA=this.m_invMassA+this.m_invIA*ruA*ruA;const mB=this.m_invMassB+this.m_invIB*ruB*ruB;let mass=mA+this.m_ratio*this.m_ratio*mB;if(mass>0){mass=1/mass}const C=this.m_constant-lengthA-this.m_ratio*lengthB;const linearError=b2Abs(C);const impulse=-mass*C;const PA=b2Vec2.MulSV(-impulse,uA,b2PulleyJoint.SolvePositionConstraints_s_PA);const PB=b2Vec2.MulSV(-this.m_ratio*impulse,uB,b2PulleyJoint.SolvePositionConstraints_s_PB);cA.SelfMulAdd(this.m_invMassA,PA);aA+=this.m_invIA*b2Vec2.CrossVV(rA,PA);cB.SelfMulAdd(this.m_invMassB,PB);aB+=this.m_invIB*b2Vec2.CrossVV(rB,PB);data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return linearError0){this.m_motorMass=1/this.m_motorMass}if(!this.m_enableMotor||fixedRotation){this.m_motorImpulse=0}if(this.m_enableLimit&&!fixedRotation){const jointAngle=aB-aA-this.m_referenceAngle;if(b2Abs(this.m_upperAngle-this.m_lowerAngle)<2*b2_angularSlop){this.m_limitState=exports.b2LimitState.e_equalLimits}else if(jointAngle<=this.m_lowerAngle){if(this.m_limitState!==exports.b2LimitState.e_atLowerLimit){this.m_impulse.z=0}this.m_limitState=exports.b2LimitState.e_atLowerLimit}else if(jointAngle>=this.m_upperAngle){if(this.m_limitState!==exports.b2LimitState.e_atUpperLimit){this.m_impulse.z=0}this.m_limitState=exports.b2LimitState.e_atUpperLimit}else{this.m_limitState=exports.b2LimitState.e_inactiveLimit;this.m_impulse.z=0}}else{this.m_limitState=exports.b2LimitState.e_inactiveLimit}if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);this.m_motorImpulse*=data.step.dtRatio;const P=b2RevoluteJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x,this.m_impulse.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+this.m_motorImpulse+this.m_impulse.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+this.m_motorImpulse+this.m_impulse.z)}else{this.m_impulse.SetZero();this.m_motorImpulse=0}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;const fixedRotation=iA+iB===0;if(this.m_enableMotor&&this.m_limitState!==exports.b2LimitState.e_equalLimits&&!fixedRotation){const Cdot=wB-wA-this.m_motorSpeed;let impulse=-this.m_motorMass*Cdot;const oldImpulse=this.m_motorImpulse;const maxImpulse=data.step.dt*this.m_maxMotorTorque;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse}if(this.m_enableLimit&&this.m_limitState!==exports.b2LimitState.e_inactiveLimit&&!fixedRotation){const Cdot1=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2RevoluteJoint.SolveVelocityConstraints_s_Cdot1);const Cdot2=wB-wA;const impulse_v3=this.m_mass.Solve33(Cdot1.x,Cdot1.y,Cdot2,b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v3).SelfNeg();if(this.m_limitState===exports.b2LimitState.e_equalLimits){this.m_impulse.SelfAdd(impulse_v3)}else if(this.m_limitState===exports.b2LimitState.e_atLowerLimit){const newImpulse=this.m_impulse.z+impulse_v3.z;if(newImpulse<0){const rhs_x=-Cdot1.x+this.m_impulse.z*this.m_mass.ez.x;const rhs_y=-Cdot1.y+this.m_impulse.z*this.m_mass.ez.y;const reduced_v2=this.m_mass.Solve22(rhs_x,rhs_y,b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2);impulse_v3.x=reduced_v2.x;impulse_v3.y=reduced_v2.y;impulse_v3.z=-this.m_impulse.z;this.m_impulse.x+=reduced_v2.x;this.m_impulse.y+=reduced_v2.y;this.m_impulse.z=0}else{this.m_impulse.SelfAdd(impulse_v3)}}else if(this.m_limitState===exports.b2LimitState.e_atUpperLimit){const newImpulse=this.m_impulse.z+impulse_v3.z;if(newImpulse>0){const rhs_x=-Cdot1.x+this.m_impulse.z*this.m_mass.ez.x;const rhs_y=-Cdot1.y+this.m_impulse.z*this.m_mass.ez.y;const reduced_v2=this.m_mass.Solve22(rhs_x,rhs_y,b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2);impulse_v3.x=reduced_v2.x;impulse_v3.y=reduced_v2.y;impulse_v3.z=-this.m_impulse.z;this.m_impulse.x+=reduced_v2.x;this.m_impulse.y+=reduced_v2.y;this.m_impulse.z=0}else{this.m_impulse.SelfAdd(impulse_v3)}}const P=b2RevoluteJoint.SolveVelocityConstraints_s_P.Set(impulse_v3.x,impulse_v3.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+impulse_v3.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+impulse_v3.z)}else{const Cdot_v2=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2RevoluteJoint.SolveVelocityConstraints_s_Cdot_v2);const impulse_v2=this.m_mass.Solve22(-Cdot_v2.x,-Cdot_v2.y,b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v2);this.m_impulse.x+=impulse_v2.x;this.m_impulse.y+=impulse_v2.y;vA.SelfMulSub(mA,impulse_v2);wA-=iA*b2Vec2.CrossVV(this.m_rA,impulse_v2);vB.SelfMulAdd(mB,impulse_v2);wB+=iB*b2Vec2.CrossVV(this.m_rB,impulse_v2)}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);let angularError=0;let positionError=0;const fixedRotation=this.m_invIA+this.m_invIB===0;if(this.m_enableLimit&&this.m_limitState!==exports.b2LimitState.e_inactiveLimit&&!fixedRotation){const angle=aB-aA-this.m_referenceAngle;let limitImpulse=0;if(this.m_limitState===exports.b2LimitState.e_equalLimits){const C=b2Clamp(angle-this.m_lowerAngle,-b2_maxAngularCorrection,b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C;angularError=b2Abs(C)}else if(this.m_limitState===exports.b2LimitState.e_atLowerLimit){let C=angle-this.m_lowerAngle;angularError=-C;C=b2Clamp(C+b2_angularSlop,-b2_maxAngularCorrection,0);limitImpulse=-this.m_motorMass*C}else if(this.m_limitState===exports.b2LimitState.e_atUpperLimit){let C=angle-this.m_upperAngle;angularError=C;C=b2Clamp(C-b2_angularSlop,0,b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C}aA-=this.m_invIA*limitImpulse;aB+=this.m_invIB*limitImpulse}{qA.SetAngle(aA);qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const C_v2=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2RevoluteJoint.SolvePositionConstraints_s_C_v2);positionError=C_v2.Length();const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;const K=this.m_K;K.ex.x=mA+mB+iA*rA.y*rA.y+iB*rB.y*rB.y;K.ex.y=-iA*rA.x*rA.y-iB*rB.x*rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*rA.x*rA.x+iB*rB.x*rB.x;const impulse=K.Solve(C_v2.x,C_v2.y,b2RevoluteJoint.SolvePositionConstraints_s_impulse).SelfNeg();cA.SelfMulSub(mA,impulse);aA-=iA*b2Vec2.CrossVV(rA,impulse);cB.SelfMulAdd(mB,impulse);aB+=iB*b2Vec2.CrossVV(rB,impulse)}data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return positionError<=b2_linearSlop&&angularError<=b2_angularSlop}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out)}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out)}GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse.x;out.y=inv_dt*this.m_impulse.y;return out}GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.z}GetLocalAnchorA(){return this.m_localAnchorA}GetLocalAnchorB(){return this.m_localAnchorB}GetReferenceAngle(){return this.m_referenceAngle}GetJointAngle(){return this.m_bodyB.m_sweep.a-this.m_bodyA.m_sweep.a-this.m_referenceAngle}GetJointSpeed(){return this.m_bodyB.m_angularVelocity-this.m_bodyA.m_angularVelocity}IsMotorEnabled(){return this.m_enableMotor}EnableMotor(flag){if(this.m_enableMotor!==flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag}}GetMotorTorque(inv_dt){return inv_dt*this.m_motorImpulse}GetMotorSpeed(){return this.m_motorSpeed}SetMaxMotorTorque(torque){this.m_maxMotorTorque=torque}GetMaxMotorTorque(){return this.m_maxMotorTorque}IsLimitEnabled(){return this.m_enableLimit}EnableLimit(flag){if(flag!==this.m_enableLimit){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag;this.m_impulse.z=0}}GetLowerLimit(){return this.m_lowerAngle}GetUpperLimit(){return this.m_upperAngle}SetLimits(lower,upper){if(lower!==this.m_lowerAngle||upper!==this.m_upperAngle){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_impulse.z=0;this.m_lowerAngle=lower;this.m_upperAngle=upper}}SetMotorSpeed(speed){if(this.m_motorSpeed!==speed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed}}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log(" const jd: b2RevoluteJointDef = new b2RevoluteJointDef();\n");log(" jd.bodyA = bodies[%d];\n",indexA);log(" jd.bodyB = bodies[%d];\n",indexB);log(" jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log(" jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log(" jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log(" jd.referenceAngle = %.15f;\n",this.m_referenceAngle);log(" jd.enableLimit = %s;\n",this.m_enableLimit?"true":"false");log(" jd.lowerAngle = %.15f;\n",this.m_lowerAngle);log(" jd.upperAngle = %.15f;\n",this.m_upperAngle);log(" jd.enableMotor = %s;\n",this.m_enableMotor?"true":"false");log(" jd.motorSpeed = %.15f;\n",this.m_motorSpeed);log(" jd.maxMotorTorque = %.15f;\n",this.m_maxMotorTorque);log(" joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index)}}b2RevoluteJoint.InitVelocityConstraints_s_P=new b2Vec2;b2RevoluteJoint.SolveVelocityConstraints_s_P=new b2Vec2;b2RevoluteJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2;b2RevoluteJoint.SolveVelocityConstraints_s_Cdot1=new b2Vec2;b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v3=new b2Vec3;b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2=new b2Vec2;b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v2=new b2Vec2;b2RevoluteJoint.SolvePositionConstraints_s_C_v2=new b2Vec2;b2RevoluteJoint.SolvePositionConstraints_s_impulse=new b2Vec2;class b2RopeJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_ropeJoint);this.localAnchorA=new b2Vec2(-1,0);this.localAnchorB=new b2Vec2(1,0);this.maxLength=0}}class b2RopeJoint extends b2Joint{constructor(def){super(def);this.m_localAnchorA=new b2Vec2;this.m_localAnchorB=new b2Vec2;this.m_maxLength=0;this.m_length=0;this.m_impulse=0;this.m_indexA=0;this.m_indexB=0;this.m_u=new b2Vec2;this.m_rA=new b2Vec2;this.m_rB=new b2Vec2;this.m_localCenterA=new b2Vec2;this.m_localCenterB=new b2Vec2;this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_mass=0;this.m_state=exports.b2LimitState.e_inactiveLimit;this.m_qA=new b2Rot;this.m_qB=new b2Rot;this.m_lalcA=new b2Vec2;this.m_lalcB=new b2Vec2;this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,new b2Vec2(-1,0)));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,new b2Vec2(1,0)));this.m_maxLength=b2Maybe(def.maxLength,0)}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);this.m_u.Copy(cB).SelfAdd(this.m_rB).SelfSub(cA).SelfSub(this.m_rA);this.m_length=this.m_u.Length();const C=this.m_length-this.m_maxLength;if(C>0){this.m_state=exports.b2LimitState.e_atUpperLimit}else{this.m_state=exports.b2LimitState.e_inactiveLimit}if(this.m_length>b2_linearSlop){this.m_u.SelfMul(1/this.m_length)}else{this.m_u.SetZero();this.m_mass=0;this.m_impulse=0;return}const crA=b2Vec2.CrossVV(this.m_rA,this.m_u);const crB=b2Vec2.CrossVV(this.m_rB,this.m_u);const invMass=this.m_invMassA+this.m_invIA*crA*crA+this.m_invMassB+this.m_invIB*crB*crB;this.m_mass=invMass!==0?1/invMass:0;if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;const P=b2Vec2.MulSV(this.m_impulse,this.m_u,b2RopeJoint.InitVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P)}else{this.m_impulse=0}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2RopeJoint.SolveVelocityConstraints_s_vpA);const vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2RopeJoint.SolveVelocityConstraints_s_vpB);const C=this.m_length-this.m_maxLength;let Cdot=b2Vec2.DotVV(this.m_u,b2Vec2.SubVV(vpB,vpA,b2Vec2.s_t0));if(C<0){Cdot+=data.step.inv_dt*C}let impulse=-this.m_mass*Cdot;const oldImpulse=this.m_impulse;this.m_impulse=b2Min(0,this.m_impulse+impulse);impulse=this.m_impulse-oldImpulse;const P=b2Vec2.MulSV(impulse,this.m_u,b2RopeJoint.SolveVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const u=this.m_u.Copy(cB).SelfAdd(rB).SelfSub(cA).SelfSub(rA);const length=u.Normalize();let C=length-this.m_maxLength;C=b2Clamp(C,0,b2_maxLinearCorrection);const impulse=-this.m_mass*C;const P=b2Vec2.MulSV(impulse,u,b2RopeJoint.SolvePositionConstraints_s_P);cA.SelfMulSub(this.m_invMassA,P);aA-=this.m_invIA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(this.m_invMassB,P);aB+=this.m_invIB*b2Vec2.CrossVV(rB,P);data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return length-this.m_maxLength0){K.GetInverse22(this.m_mass);let invM=iA+iB;const m=invM>0?1/invM:0;const C=aB-aA-this.m_referenceAngle;const omega=2*b2_pi*this.m_frequencyHz;const d=2*m*this.m_dampingRatio*omega;const k=m*omega*omega;const h=data.step.dt;this.m_gamma=h*(d+h*k);this.m_gamma=this.m_gamma!==0?1/this.m_gamma:0;this.m_bias=C*h*k*this.m_gamma;invM+=this.m_gamma;this.m_mass.ez.z=invM!==0?1/invM:0}else{K.GetSymInverse33(this.m_mass);this.m_gamma=0;this.m_bias=0}if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);const P=b2WeldJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x,this.m_impulse.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+this.m_impulse.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+this.m_impulse.z)}else{this.m_impulse.SetZero()}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;if(this.m_frequencyHz>0){const Cdot2=wB-wA;const impulse2=-this.m_mass.ez.z*(Cdot2+this.m_bias+this.m_gamma*this.m_impulse.z);this.m_impulse.z+=impulse2;wA-=iA*impulse2;wB+=iB*impulse2;const Cdot1=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2WeldJoint.SolveVelocityConstraints_s_Cdot1);const impulse1=b2Mat33.MulM33XY(this.m_mass,Cdot1.x,Cdot1.y,b2WeldJoint.SolveVelocityConstraints_s_impulse1).SelfNeg();this.m_impulse.x+=impulse1.x;this.m_impulse.y+=impulse1.y;const P=impulse1;vA.SelfMulSub(mA,P);wA-=iA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(mB,P);wB+=iB*b2Vec2.CrossVV(this.m_rB,P)}else{const Cdot1=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2WeldJoint.SolveVelocityConstraints_s_Cdot1);const Cdot2=wB-wA;const impulse=b2Mat33.MulM33XYZ(this.m_mass,Cdot1.x,Cdot1.y,Cdot2,b2WeldJoint.SolveVelocityConstraints_s_impulse).SelfNeg();this.m_impulse.SelfAdd(impulse);const P=b2WeldJoint.SolveVelocityConstraints_s_P.Set(impulse.x,impulse.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+impulse.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+impulse.z)}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);let positionError,angularError;const K=this.m_K;K.ex.x=mA+mB+rA.y*rA.y*iA+rB.y*rB.y*iB;K.ey.x=-rA.y*rA.x*iA-rB.y*rB.x*iB;K.ez.x=-rA.y*iA-rB.y*iB;K.ex.y=K.ey.x;K.ey.y=mA+mB+rA.x*rA.x*iA+rB.x*rB.x*iB;K.ez.y=rA.x*iA+rB.x*iB;K.ex.z=K.ez.x;K.ey.z=K.ez.y;K.ez.z=iA+iB;if(this.m_frequencyHz>0){const C1=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WeldJoint.SolvePositionConstraints_s_C1);positionError=C1.Length();angularError=0;const P=K.Solve22(C1.x,C1.y,b2WeldJoint.SolvePositionConstraints_s_P).SelfNeg();cA.SelfMulSub(mA,P);aA-=iA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(mB,P);aB+=iB*b2Vec2.CrossVV(rB,P)}else{const C1=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WeldJoint.SolvePositionConstraints_s_C1);const C2=aB-aA-this.m_referenceAngle;positionError=C1.Length();angularError=b2Abs(C2);const impulse=K.Solve33(C1.x,C1.y,C2,b2WeldJoint.SolvePositionConstraints_s_impulse).SelfNeg();const P=b2WeldJoint.SolvePositionConstraints_s_P.Set(impulse.x,impulse.y);cA.SelfMulSub(mA,P);aA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+impulse.z);cB.SelfMulAdd(mB,P);aB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+impulse.z)}data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return positionError<=b2_linearSlop&&angularError<=b2_angularSlop}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out)}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out)}GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse.x;out.y=inv_dt*this.m_impulse.y;return out}GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.z}GetLocalAnchorA(){return this.m_localAnchorA}GetLocalAnchorB(){return this.m_localAnchorB}GetReferenceAngle(){return this.m_referenceAngle}SetFrequency(hz){this.m_frequencyHz=hz}GetFrequency(){return this.m_frequencyHz}SetDampingRatio(ratio){this.m_dampingRatio=ratio}GetDampingRatio(){return this.m_dampingRatio}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log(" const jd: b2WeldJointDef = new b2WeldJointDef();\n");log(" jd.bodyA = bodies[%d];\n",indexA);log(" jd.bodyB = bodies[%d];\n",indexB);log(" jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log(" jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log(" jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log(" jd.referenceAngle = %.15f;\n",this.m_referenceAngle);log(" jd.frequencyHz = %.15f;\n",this.m_frequencyHz);log(" jd.dampingRatio = %.15f;\n",this.m_dampingRatio);log(" joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index)}}b2WeldJoint.InitVelocityConstraints_s_P=new b2Vec2;b2WeldJoint.SolveVelocityConstraints_s_Cdot1=new b2Vec2;b2WeldJoint.SolveVelocityConstraints_s_impulse1=new b2Vec2;b2WeldJoint.SolveVelocityConstraints_s_impulse=new b2Vec3;b2WeldJoint.SolveVelocityConstraints_s_P=new b2Vec2;b2WeldJoint.SolvePositionConstraints_s_C1=new b2Vec2;b2WeldJoint.SolvePositionConstraints_s_P=new b2Vec2;b2WeldJoint.SolvePositionConstraints_s_impulse=new b2Vec3;class b2WheelJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_wheelJoint);this.localAnchorA=new b2Vec2(0,0);this.localAnchorB=new b2Vec2(0,0);this.localAxisA=new b2Vec2(1,0);this.enableMotor=false;this.maxMotorTorque=0;this.motorSpeed=0;this.frequencyHz=2;this.dampingRatio=0.7}Initialize(bA,bB,anchor,axis){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.bodyA.GetLocalVector(axis,this.localAxisA)}}class b2WheelJoint extends b2Joint{constructor(def){super(def);this.m_frequencyHz=0;this.m_dampingRatio=0;this.m_localAnchorA=new b2Vec2;this.m_localAnchorB=new b2Vec2;this.m_localXAxisA=new b2Vec2;this.m_localYAxisA=new b2Vec2;this.m_impulse=0;this.m_motorImpulse=0;this.m_springImpulse=0;this.m_maxMotorTorque=0;this.m_motorSpeed=0;this.m_enableMotor=false;this.m_indexA=0;this.m_indexB=0;this.m_localCenterA=new b2Vec2;this.m_localCenterB=new b2Vec2;this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_ax=new b2Vec2;this.m_ay=new b2Vec2;this.m_sAx=0;this.m_sBx=0;this.m_sAy=0;this.m_sBy=0;this.m_mass=0;this.m_motorMass=0;this.m_springMass=0;this.m_bias=0;this.m_gamma=0;this.m_qA=new b2Rot;this.m_qB=new b2Rot;this.m_lalcA=new b2Vec2;this.m_lalcB=new b2Vec2;this.m_rA=new b2Vec2;this.m_rB=new b2Vec2;this.m_frequencyHz=b2Maybe(def.frequencyHz,2);this.m_dampingRatio=b2Maybe(def.dampingRatio,0.7);this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));this.m_localXAxisA.Copy(b2Maybe(def.localAxisA,b2Vec2.UNITX));b2Vec2.CrossOneV(this.m_localXAxisA,this.m_localYAxisA);this.m_maxMotorTorque=b2Maybe(def.maxMotorTorque,0);this.m_motorSpeed=b2Maybe(def.motorSpeed,0);this.m_enableMotor=b2Maybe(def.enableMotor,false);this.m_ax.SetZero();this.m_ay.SetZero()}GetMotorSpeed(){return this.m_motorSpeed}GetMaxMotorTorque(){return this.m_maxMotorTorque}SetSpringFrequencyHz(hz){this.m_frequencyHz=hz}GetSpringFrequencyHz(){return this.m_frequencyHz}SetSpringDampingRatio(ratio){this.m_dampingRatio=ratio}GetSpringDampingRatio(){return this.m_dampingRatio}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const d=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WheelJoint.InitVelocityConstraints_s_d);{b2Rot.MulRV(qA,this.m_localYAxisA,this.m_ay);this.m_sAy=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_ay);this.m_sBy=b2Vec2.CrossVV(rB,this.m_ay);this.m_mass=mA+mB+iA*this.m_sAy*this.m_sAy+iB*this.m_sBy*this.m_sBy;if(this.m_mass>0){this.m_mass=1/this.m_mass}}this.m_springMass=0;this.m_bias=0;this.m_gamma=0;if(this.m_frequencyHz>0){b2Rot.MulRV(qA,this.m_localXAxisA,this.m_ax);this.m_sAx=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_ax);this.m_sBx=b2Vec2.CrossVV(rB,this.m_ax);const invMass=mA+mB+iA*this.m_sAx*this.m_sAx+iB*this.m_sBx*this.m_sBx;if(invMass>0){this.m_springMass=1/invMass;const C=b2Vec2.DotVV(d,this.m_ax);const omega=2*b2_pi*this.m_frequencyHz;const dc=2*this.m_springMass*this.m_dampingRatio*omega;const k=this.m_springMass*omega*omega;const h=data.step.dt;this.m_gamma=h*(dc+h*k);if(this.m_gamma>0){this.m_gamma=1/this.m_gamma}this.m_bias=C*h*k*this.m_gamma;this.m_springMass=invMass+this.m_gamma;if(this.m_springMass>0){this.m_springMass=1/this.m_springMass}}}else{this.m_springImpulse=0}if(this.m_enableMotor){this.m_motorMass=iA+iB;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass}}else{this.m_motorMass=0;this.m_motorImpulse=0}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;this.m_springImpulse*=data.step.dtRatio;this.m_motorImpulse*=data.step.dtRatio;const P=b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse,this.m_ay,b2Vec2.s_t0),b2Vec2.MulSV(this.m_springImpulse,this.m_ax,b2Vec2.s_t1),b2WheelJoint.InitVelocityConstraints_s_P);const LA=this.m_impulse*this.m_sAy+this.m_springImpulse*this.m_sAx+this.m_motorImpulse;const LB=this.m_impulse*this.m_sBy+this.m_springImpulse*this.m_sBx+this.m_motorImpulse;vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*LA;vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*LB}else{this.m_impulse=0;this.m_springImpulse=0;this.m_motorImpulse=0}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolveVelocityConstraints(data){const mA=this.m_invMassA;const mB=this.m_invMassB;const iA=this.m_invIA;const iB=this.m_invIB;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;{const Cdot=b2Vec2.DotVV(this.m_ax,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_sBx*wB-this.m_sAx*wA;const impulse=-this.m_springMass*(Cdot+this.m_bias+this.m_gamma*this.m_springImpulse);this.m_springImpulse+=impulse;const P=b2Vec2.MulSV(impulse,this.m_ax,b2WheelJoint.SolveVelocityConstraints_s_P);const LA=impulse*this.m_sAx;const LB=impulse*this.m_sBx;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB}{const Cdot=wB-wA-this.m_motorSpeed;let impulse=-this.m_motorMass*Cdot;const oldImpulse=this.m_motorImpulse;const maxImpulse=data.step.dt*this.m_maxMotorTorque;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse}{const Cdot=b2Vec2.DotVV(this.m_ay,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_sBy*wB-this.m_sAy*wA;const impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;const P=b2Vec2.MulSV(impulse,this.m_ay,b2WheelJoint.SolveVelocityConstraints_s_P);const LA=impulse*this.m_sAy;const LB=impulse*this.m_sBy;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA);const qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const d=b2Vec2.AddVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),b2Vec2.SubVV(rB,rA,b2Vec2.s_t1),b2WheelJoint.SolvePositionConstraints_s_d);const ay=b2Rot.MulRV(qA,this.m_localYAxisA,this.m_ay);const sAy=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),ay);const sBy=b2Vec2.CrossVV(rB,ay);const C=b2Vec2.DotVV(d,this.m_ay);const k=this.m_invMassA+this.m_invMassB+this.m_invIA*this.m_sAy*this.m_sAy+this.m_invIB*this.m_sBy*this.m_sBy;let impulse;if(k!==0){impulse=-C/k}else{impulse=0}const P=b2Vec2.MulSV(impulse,ay,b2WheelJoint.SolvePositionConstraints_s_P);const LA=impulse*sAy;const LB=impulse*sBy;cA.SelfMulSub(this.m_invMassA,P);aA-=this.m_invIA*LA;cB.SelfMulAdd(this.m_invMassB,P);aB+=this.m_invIB*LB;data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return b2Abs(C)<=b2_linearSlop}GetDefinition(def){return def}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out)}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out)}GetReactionForce(inv_dt,out){out.x=inv_dt*(this.m_impulse*this.m_ay.x+this.m_springImpulse*this.m_ax.x);out.y=inv_dt*(this.m_impulse*this.m_ay.y+this.m_springImpulse*this.m_ax.y);return out}GetReactionTorque(inv_dt){return inv_dt*this.m_motorImpulse}GetLocalAnchorA(){return this.m_localAnchorA}GetLocalAnchorB(){return this.m_localAnchorB}GetLocalAxisA(){return this.m_localXAxisA}GetJointTranslation(){return this.GetPrismaticJointTranslation()}GetJointSpeed(){return this.GetRevoluteJointSpeed()}GetPrismaticJointTranslation(){const bA=this.m_bodyA;const bB=this.m_bodyB;const pA=bA.GetWorldPoint(this.m_localAnchorA,new b2Vec2);const pB=bB.GetWorldPoint(this.m_localAnchorB,new b2Vec2);const d=b2Vec2.SubVV(pB,pA,new b2Vec2);const axis=bA.GetWorldVector(this.m_localXAxisA,new b2Vec2);const translation=b2Vec2.DotVV(d,axis);return translation}GetPrismaticJointSpeed(){const bA=this.m_bodyA;const bB=this.m_bodyB;b2Vec2.SubVV(this.m_localAnchorA,bA.m_sweep.localCenter,this.m_lalcA);const rA=b2Rot.MulRV(bA.m_xf.q,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,bB.m_sweep.localCenter,this.m_lalcB);const rB=b2Rot.MulRV(bB.m_xf.q,this.m_lalcB,this.m_rB);const pA=b2Vec2.AddVV(bA.m_sweep.c,rA,b2Vec2.s_t0);const pB=b2Vec2.AddVV(bB.m_sweep.c,rB,b2Vec2.s_t1);const d=b2Vec2.SubVV(pB,pA,b2Vec2.s_t2);const axis=bA.GetWorldVector(this.m_localXAxisA,new b2Vec2);const vA=bA.m_linearVelocity;const vB=bB.m_linearVelocity;const wA=bA.m_angularVelocity;const wB=bB.m_angularVelocity;const speed=b2Vec2.DotVV(d,b2Vec2.CrossSV(wA,axis,b2Vec2.s_t0))+b2Vec2.DotVV(axis,b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,rA,b2Vec2.s_t1),b2Vec2.s_t0));return speed}GetRevoluteJointAngle(){return this.m_bodyB.m_sweep.a-this.m_bodyA.m_sweep.a}GetRevoluteJointSpeed(){const wA=this.m_bodyA.m_angularVelocity;const wB=this.m_bodyB.m_angularVelocity;return wB-wA}IsMotorEnabled(){return this.m_enableMotor}EnableMotor(flag){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag}SetMotorSpeed(speed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed}SetMaxMotorTorque(force){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorTorque=force}GetMotorTorque(inv_dt){return inv_dt*this.m_motorImpulse}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log(" const jd: b2WheelJointDef = new b2WheelJointDef();\n");log(" jd.bodyA = bodies[%d];\n",indexA);log(" jd.bodyB = bodies[%d];\n",indexB);log(" jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log(" jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log(" jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log(" jd.localAxisA.Set(%.15f, %.15f);\n",this.m_localXAxisA.x,this.m_localXAxisA.y);log(" jd.enableMotor = %s;\n",this.m_enableMotor?"true":"false");log(" jd.motorSpeed = %.15f;\n",this.m_motorSpeed);log(" jd.maxMotorTorque = %.15f;\n",this.m_maxMotorTorque);log(" jd.frequencyHz = %.15f;\n",this.m_frequencyHz);log(" jd.dampingRatio = %.15f;\n",this.m_dampingRatio);log(" joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index)}}b2WheelJoint.InitVelocityConstraints_s_d=new b2Vec2;b2WheelJoint.InitVelocityConstraints_s_P=new b2Vec2;b2WheelJoint.SolveVelocityConstraints_s_P=new b2Vec2;b2WheelJoint.SolvePositionConstraints_s_d=new b2Vec2;b2WheelJoint.SolvePositionConstraints_s_P=new b2Vec2;class b2JointFactory{static Create(def,allocator){switch(def.type){case exports.b2JointType.e_distanceJoint:return new b2DistanceJoint(def);case exports.b2JointType.e_mouseJoint:return new b2MouseJoint(def);case exports.b2JointType.e_prismaticJoint:return new b2PrismaticJoint(def);case exports.b2JointType.e_revoluteJoint:return new b2RevoluteJoint(def);case exports.b2JointType.e_pulleyJoint:return new b2PulleyJoint(def);case exports.b2JointType.e_gearJoint:return new b2GearJoint(def);case exports.b2JointType.e_wheelJoint:return new b2WheelJoint(def);case exports.b2JointType.e_weldJoint:return new b2WeldJoint(def);case exports.b2JointType.e_frictionJoint:return new b2FrictionJoint(def);case exports.b2JointType.e_ropeJoint:return new b2RopeJoint(def);case exports.b2JointType.e_motorJoint:return new b2MotorJoint(def);case exports.b2JointType.e_areaJoint:return new b2AreaJoint(def);}throw new Error}static Destroy(joint,allocator){}}function b2MixFriction(friction1,friction2){return b2Sqrt(friction1*friction2)}function b2MixRestitution(restitution1,restitution2){return restitution1>restitution2?restitution1:restitution2}class b2ContactEdge{constructor(contact){this.prev=null;this.next=null;this.contact=contact}}class b2Contact{constructor(){this.m_islandFlag=false;this.m_touchingFlag=false;this.m_enabledFlag=false;this.m_filterFlag=false;this.m_bulletHitFlag=false;this.m_toiFlag=false;this.m_prev=null;this.m_next=null;this.m_indexA=0;this.m_indexB=0;this.m_manifold=new b2Manifold;this.m_toiCount=0;this.m_toi=0;this.m_friction=0;this.m_restitution=0;this.m_tangentSpeed=0;this.m_swaped=false;this.m_oldManifold=new b2Manifold;this.m_nodeA=new b2ContactEdge(this);this.m_nodeB=new b2ContactEdge(this)}GetManifold(){return this.m_manifold}GetWorldManifold(worldManifold){const bodyA=this.m_fixtureA.GetBody();const bodyB=this.m_fixtureB.GetBody();const shapeA=this.m_fixtureA.GetShape();const shapeB=this.m_fixtureB.GetShape();worldManifold.Initialize(this.m_manifold,bodyA.GetTransform(),shapeA.m_radius,bodyB.GetTransform(),shapeB.m_radius)}IsTouching(){return this.m_touchingFlag}SetEnabled(flag){this.m_enabledFlag=flag}IsEnabled(){return this.m_enabledFlag}GetNext(){return this.m_next}GetFixtureA(){return this.m_fixtureA}GetChildIndexA(){return this.m_indexA}GetFixtureB(){return this.m_fixtureB}GetChildIndexB(){return this.m_indexB}FlagForFiltering(){this.m_filterFlag=true}SetFriction(friction){this.m_friction=friction}GetFriction(){return this.m_friction}ResetFriction(){this.m_friction=b2MixFriction(this.m_fixtureA.m_friction,this.m_fixtureB.m_friction)}SetRestitution(restitution){this.m_restitution=restitution}GetRestitution(){return this.m_restitution}ResetRestitution(){this.m_restitution=b2MixRestitution(this.m_fixtureA.m_restitution,this.m_fixtureB.m_restitution)}SetTangentSpeed(speed){this.m_tangentSpeed=speed}GetTangentSpeed(){return this.m_tangentSpeed}Reset(fixtureA,indexA,fixtureB,indexB){this.m_islandFlag=false;this.m_touchingFlag=false;this.m_enabledFlag=true;this.m_filterFlag=false;this.m_bulletHitFlag=false;this.m_toiFlag=false;this.m_fixtureA=fixtureA;this.m_fixtureB=fixtureB;this.m_indexA=indexA;this.m_indexB=indexB;this.m_manifold.pointCount=0;this.m_prev=null;this.m_next=null;delete this.m_nodeA.contact;this.m_nodeA.prev=null;this.m_nodeA.next=null;delete this.m_nodeA.other;delete this.m_nodeB.contact;this.m_nodeB.prev=null;this.m_nodeB.next=null;delete this.m_nodeB.other;this.m_toiCount=0;if(this.m_fixtureA){this.m_friction=b2MixFriction(this.m_fixtureA.m_friction,this.m_fixtureB.m_friction);this.m_restitution=b2MixRestitution(this.m_fixtureA.m_restitution,this.m_fixtureB.m_restitution)}}Update(listener){const tManifold=this.m_oldManifold;this.m_oldManifold=this.m_manifold;this.m_manifold=tManifold;this.m_enabledFlag=true;let touching=false;const wasTouching=this.m_touchingFlag;const sensorA=this.m_fixtureA.IsSensor();const sensorB=this.m_fixtureB.IsSensor();const sensor=sensorA||sensorB;const bodyA=this.m_fixtureA.GetBody();const bodyB=this.m_fixtureB.GetBody();const xfA=bodyA.GetTransform();const xfB=bodyB.GetTransform();if(sensor){const shapeA=this.m_fixtureA.GetShape();const shapeB=this.m_fixtureB.GetShape();touching=b2TestOverlapShape(shapeA,this.m_indexA,shapeB,this.m_indexB,xfA,xfB);this.m_manifold.pointCount=0}else{this.Evaluate(this.m_manifold,xfA,xfB);touching=this.m_manifold.pointCount>0;for(let i=0;icreateFcn(this.m_allocator));function poolCreateFcn(allocator){return pool.pop()||createFcn(allocator)}function poolDestroyFcn(contact,allocator){pool.push(contact)}this.m_registers[type1][type2].createFcn=poolCreateFcn;this.m_registers[type1][type2].destroyFcn=poolDestroyFcn;this.m_registers[type1][type2].primary=true;if(type1!==type2){this.m_registers[type2][type1].createFcn=poolCreateFcn;this.m_registers[type2][type1].destroyFcn=poolDestroyFcn;this.m_registers[type2][type1].primary=false}}InitializeRegisters(){this.m_registers=[];for(let i=0;i0&&!fixtureA.IsSensor()&&!fixtureB.IsSensor()){fixtureA.GetBody().SetAwake(true);fixtureB.GetBody().SetAwake(true)}const typeA=fixtureA.GetType();const typeB=fixtureB.GetType();var reg=null;if(contact.m_swaped){reg=this.m_registers[typeB][typeA]}else{reg=this.m_registers[typeA][typeB]}contact.Reset();if(reg.destroyFcn){reg.destroyFcn(contact,this.m_allocator)}}}class b2DestructionListener{SayGoodbyeJoint(joint){}SayGoodbyeFixture(fixture){}SayGoodbyeParticleGroup(group){}SayGoodbyeParticle(system,index){}}class b2ContactFilter{ShouldCollide(fixtureA,fixtureB){const bodyA=fixtureA.GetBody();const bodyB=fixtureB.GetBody();if(bodyB.GetType()===exports.b2BodyType.b2_staticBody&&bodyA.GetType()===exports.b2BodyType.b2_staticBody){return false}if(!bodyB.ShouldCollideConnected(bodyA)){return false}const filter1=fixtureA.GetFilterData();const filter2=fixtureB.GetFilterData();if(filter1.groupIndex===filter2.groupIndex&&filter1.groupIndex!==0){return filter1.groupIndex>0}const collide=(filter1.maskBits&filter2.categoryBits)!==0&&(filter1.categoryBits&filter2.maskBits)!==0;return collide}ShouldCollideFixtureParticle(fixture,system,index){return true}ShouldCollideParticleParticle(system,indexA,indexB){return true}}b2ContactFilter.b2_defaultFilter=new b2ContactFilter;class b2ContactImpulse{constructor(){this.normalImpulses=b2MakeNumberArray(b2_maxManifoldPoints);this.tangentImpulses=b2MakeNumberArray(b2_maxManifoldPoints);this.count=0}}class b2ContactListener{BeginContact(contact){}EndContact(contact){}BeginContactFixtureParticle(system,contact){}EndContactFixtureParticle(system,contact){}BeginContactParticleParticle(system,contact){}EndContactParticleParticle(system,contact){}PreSolve(contact,oldManifold){}PostSolve(contact,impulse){}}b2ContactListener.b2_defaultListener=new b2ContactListener;class b2QueryCallback{ReportFixture(fixture){return true}ReportParticle(system,index){return false}ShouldQueryParticleSystem(system){return true}}class b2RayCastCallback{ReportFixture(fixture,point,normal,fraction){return fraction}ReportParticle(system,index,point,normal,fraction){return 0}ShouldQueryParticleSystem(system){return true}}class b2ContactManager{constructor(){this.m_broadPhase=new b2BroadPhase;this.m_contactList=null;this.m_contactCount=0;this.m_contactFilter=b2ContactFilter.b2_defaultFilter;this.m_contactListener=b2ContactListener.b2_defaultListener;this.m_allocator=null;this.m_contactFactory=new b2ContactFactory(this.m_allocator)}AddPair(proxyA,proxyB){if(!proxyB||!proxyA){return}let fixtureA=proxyA.fixture;let fixtureB=proxyB.fixture;let indexA=proxyA.childIndex;let indexB=proxyB.childIndex;let bodyA=fixtureA.GetBody();let bodyB=fixtureB.GetBody();if(bodyA===bodyB){return}let edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){const fA=edge.contact.GetFixtureA();const fB=edge.contact.GetFixtureB();const iA=edge.contact.GetChildIndexA();const iB=edge.contact.GetChildIndexB();if(fA===fixtureA&&fB===fixtureB&&iA===indexA&&iB===indexB){return}if(fA===fixtureB&&fB===fixtureA&&iA===indexB&&iB===indexA){return}}edge=edge.next}if(this.m_contactFilter&&!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){return}const c=this.m_contactFactory.Create(fixtureA,indexA,fixtureB,indexB);if(c===null){return}fixtureA=c.GetFixtureA();fixtureB=c.GetFixtureB();indexA=c.GetChildIndexA();indexB=c.GetChildIndexB();bodyA=fixtureA.m_body;bodyB=fixtureB.m_body;c.m_prev=null;c.m_next=this.m_contactList;if(this.m_contactList!==null){this.m_contactList.m_prev=c}this.m_contactList=c;c.m_nodeA.contact=c;c.m_nodeA.other=bodyB;c.m_nodeA.prev=null;c.m_nodeA.next=bodyA.m_contactList;if(bodyA.m_contactList!==null){bodyA.m_contactList.prev=c.m_nodeA}bodyA.m_contactList=c.m_nodeA;c.m_nodeB.contact=c;c.m_nodeB.other=bodyA;c.m_nodeB.prev=null;c.m_nodeB.next=bodyB.m_contactList;if(bodyB.m_contactList!==null){bodyB.m_contactList.prev=c.m_nodeB}bodyB.m_contactList=c.m_nodeB;if(!fixtureA.IsSensor()&&!fixtureB.IsSensor()){bodyA.SetAwake(true);bodyB.SetAwake(true)}++this.m_contactCount}FindNewContacts(){this.m_broadPhase.UpdatePairs((proxyA,proxyB)=>{this.AddPair(proxyA,proxyB)})}Destroy(c){const fixtureA=c.GetFixtureA();const fixtureB=c.GetFixtureB();const bodyA=fixtureA.GetBody();const bodyB=fixtureB.GetBody();if(this.m_contactListener&&c.IsTouching()){this.m_contactListener.EndContact(c)}if(c.m_prev){c.m_prev.m_next=c.m_next}if(c.m_next){c.m_next.m_prev=c.m_prev}if(c===this.m_contactList){this.m_contactList=c.m_next}if(c.m_nodeA.prev){c.m_nodeA.prev.next=c.m_nodeA.next}if(c.m_nodeA.next){c.m_nodeA.next.prev=c.m_nodeA.prev}if(c.m_nodeA===bodyA.m_contactList){bodyA.m_contactList=c.m_nodeA.next}if(c.m_nodeB.prev){c.m_nodeB.prev.next=c.m_nodeB.next}if(c.m_nodeB.next){c.m_nodeB.next.prev=c.m_nodeB.prev}if(c.m_nodeB===bodyB.m_contactList){bodyB.m_contactList=c.m_nodeB.next}this.m_contactFactory.Destroy(c);--this.m_contactCount}Collide(){let c=this.m_contactList;while(c){const fixtureA=c.GetFixtureA();const fixtureB=c.GetFixtureB();const indexA=c.GetChildIndexA();const indexB=c.GetChildIndexB();const bodyA=fixtureA.GetBody();const bodyB=fixtureB.GetBody();if(c.m_filterFlag){if(this.m_contactFilter&&!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){const cNuke=c;c=cNuke.m_next;this.Destroy(cNuke);continue}c.m_filterFlag=false}const activeA=bodyA.IsAwake()&&bodyA.m_type!==exports.b2BodyType.b2_staticBody;const activeB=bodyB.IsAwake()&&bodyB.m_type!==exports.b2BodyType.b2_staticBody;if(!activeA&&!activeB){c=c.m_next;continue}const proxyA=fixtureA.m_proxies[indexA].treeNode;const proxyB=fixtureB.m_proxies[indexB].treeNode;const overlap=b2TestOverlapAABB(proxyA.aabb,proxyB.aabb);if(!overlap){const cNuke=c;c=cNuke.m_next;this.Destroy(cNuke);continue}c.Update(this.m_contactListener);c=c.m_next}}}class b2Profile{constructor(){this.step=0;this.collide=0;this.solve=0;this.solveInit=0;this.solveVelocity=0;this.solvePosition=0;this.broadphase=0;this.solveTOI=0}Reset(){this.step=0;this.collide=0;this.solve=0;this.solveInit=0;this.solveVelocity=0;this.solvePosition=0;this.broadphase=0;this.solveTOI=0;return this}}class b2TimeStep{constructor(){this.dt=0;this.inv_dt=0;this.dtRatio=0;this.velocityIterations=0;this.positionIterations=0;this.particleIterations=0;this.warmStarting=false}Copy(step){this.dt=step.dt;this.inv_dt=step.inv_dt;this.dtRatio=step.dtRatio;this.positionIterations=step.positionIterations;this.velocityIterations=step.velocityIterations;this.particleIterations=step.particleIterations;this.warmStarting=step.warmStarting;return this}}class b2Position{constructor(){this.c=new b2Vec2;this.a=0}static MakeArray(length){return b2MakeArray(length,i=>new b2Position)}}class b2Velocity{constructor(){this.v=new b2Vec2;this.w=0}static MakeArray(length){return b2MakeArray(length,i=>new b2Velocity)}}class b2SolverData{constructor(){this.step=new b2TimeStep}}class b2VelocityConstraintPoint{constructor(){this.rA=new b2Vec2;this.rB=new b2Vec2;this.normalImpulse=0;this.tangentImpulse=0;this.normalMass=0;this.tangentMass=0;this.velocityBias=0}static MakeArray(length){return b2MakeArray(length,i=>new b2VelocityConstraintPoint)}}class b2ContactVelocityConstraint{constructor(){this.points=b2VelocityConstraintPoint.MakeArray(b2_maxManifoldPoints);this.normal=new b2Vec2;this.tangent=new b2Vec2;this.normalMass=new b2Mat22;this.K=new b2Mat22;this.indexA=0;this.indexB=0;this.invMassA=0;this.invMassB=0;this.invIA=0;this.invIB=0;this.friction=0;this.restitution=0;this.tangentSpeed=0;this.pointCount=0;this.contactIndex=0}static MakeArray(length){return b2MakeArray(length,i=>new b2ContactVelocityConstraint)}}class b2ContactPositionConstraint{constructor(){this.localPoints=b2Vec2.MakeArray(b2_maxManifoldPoints);this.localNormal=new b2Vec2;this.localPoint=new b2Vec2;this.indexA=0;this.indexB=0;this.invMassA=0;this.invMassB=0;this.localCenterA=new b2Vec2;this.localCenterB=new b2Vec2;this.invIA=0;this.invIB=0;this.type=exports.b2ManifoldType.e_unknown;this.radiusA=0;this.radiusB=0;this.pointCount=0}static MakeArray(length){return b2MakeArray(length,i=>new b2ContactPositionConstraint)}}class b2ContactSolverDef{constructor(){this.step=new b2TimeStep;this.count=0;this.allocator=null}}class b2PositionSolverManifold{constructor(){this.normal=new b2Vec2;this.point=new b2Vec2;this.separation=0}Initialize(pc,xfA,xfB,index){const pointA=b2PositionSolverManifold.Initialize_s_pointA;const pointB=b2PositionSolverManifold.Initialize_s_pointB;const planePoint=b2PositionSolverManifold.Initialize_s_planePoint;const clipPoint=b2PositionSolverManifold.Initialize_s_clipPoint;switch(pc.type){case exports.b2ManifoldType.e_circles:{b2Transform.MulXV(xfA,pc.localPoint,pointA);b2Transform.MulXV(xfB,pc.localPoints[0],pointB);b2Vec2.SubVV(pointB,pointA,this.normal).SelfNormalize();b2Vec2.MidVV(pointA,pointB,this.point);this.separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),this.normal)-pc.radiusA-pc.radiusB;break}case exports.b2ManifoldType.e_faceA:{b2Rot.MulRV(xfA.q,pc.localNormal,this.normal);b2Transform.MulXV(xfA,pc.localPoint,planePoint);b2Transform.MulXV(xfB,pc.localPoints[index],clipPoint);this.separation=b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal)-pc.radiusA-pc.radiusB;this.point.Copy(clipPoint);break}case exports.b2ManifoldType.e_faceB:{b2Rot.MulRV(xfB.q,pc.localNormal,this.normal);b2Transform.MulXV(xfB,pc.localPoint,planePoint);b2Transform.MulXV(xfA,pc.localPoints[index],clipPoint);this.separation=b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal)-pc.radiusA-pc.radiusB;this.point.Copy(clipPoint);this.normal.SelfNeg();break}}}}b2PositionSolverManifold.Initialize_s_pointA=new b2Vec2;b2PositionSolverManifold.Initialize_s_pointB=new b2Vec2;b2PositionSolverManifold.Initialize_s_planePoint=new b2Vec2;b2PositionSolverManifold.Initialize_s_clipPoint=new b2Vec2;class b2ContactSolver{constructor(){this.m_step=new b2TimeStep;this.m_allocator=null;this.m_positionConstraints=b2ContactPositionConstraint.MakeArray(1024);this.m_velocityConstraints=b2ContactVelocityConstraint.MakeArray(1024);this.m_count=0}Initialize(def){this.m_step.Copy(def.step);this.m_allocator=def.allocator;this.m_count=def.count;if(this.m_positionConstraints.length0?1/kNormal:0;const tangent=vc.tangent;const rtA=b2Vec2.CrossVV(vcp.rA,tangent);const rtB=b2Vec2.CrossVV(vcp.rB,tangent);const kTangent=mA+mB+iA*rtA*rtA+iB*rtB*rtB;vcp.tangentMass=kTangent>0?1/kTangent:0;vcp.velocityBias=0;const vRel=b2Vec2.DotVV(vc.normal,b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,vcp.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,vcp.rA,b2Vec2.s_t1),b2Vec2.s_t0));if(vRel<-b2_velocityThreshold){vcp.velocityBias+=-vc.restitution*vRel}}if(vc.pointCount===2){const vcp1=vc.points[0];const vcp2=vc.points[1];const rn1A=b2Vec2.CrossVV(vcp1.rA,vc.normal);const rn1B=b2Vec2.CrossVV(vcp1.rB,vc.normal);const rn2A=b2Vec2.CrossVV(vcp2.rA,vc.normal);const rn2B=b2Vec2.CrossVV(vcp2.rB,vc.normal);const k11=mA+mB+iA*rn1A*rn1A+iB*rn1B*rn1B;const k22=mA+mB+iA*rn2A*rn2A+iB*rn2B*rn2B;const k12=mA+mB+iA*rn1A*rn2A+iB*rn1B*rn2B;if(k11*k11=0&&x.y>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break}x.x=-cp1.normalMass*b.x;x.y=0;vn1=0;vn2=vc.K.ex.y*x.x+b.y;if(x.x>=0&&vn2>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break}x.x=0;x.y=-cp2.normalMass*b.y;vn1=vc.K.ey.x*x.y+b.x;vn2=0;if(x.y>=0&&vn1>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break}x.x=0;x.y=0;vn1=b.x;vn2=b.y;if(vn1>=0&&vn2>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break}break}}this.m_velocities[indexA].w=wA;this.m_velocities[indexB].w=wB}}StoreImpulses(){for(let i=0;i0?-C/K:0;b2Vec2.MulSV(impulse,normal,P);cA.SelfMulSub(mA,P);aA-=iA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(mB,P);aB+=iB*b2Vec2.CrossVV(rB,P)}this.m_positions[indexA].a=aA;this.m_positions[indexB].a=aB}return minSeparation>-3*b2_linearSlop}SolveTOIPositionConstraints(toiIndexA,toiIndexB){const xfA=b2ContactSolver.SolveTOIPositionConstraints_s_xfA;const xfB=b2ContactSolver.SolveTOIPositionConstraints_s_xfB;const psm=b2ContactSolver.SolveTOIPositionConstraints_s_psm;const rA=b2ContactSolver.SolveTOIPositionConstraints_s_rA;const rB=b2ContactSolver.SolveTOIPositionConstraints_s_rB;const P=b2ContactSolver.SolveTOIPositionConstraints_s_P;let minSeparation=0;for(let i=0;i0?-C/K:0;b2Vec2.MulSV(impulse,normal,P);cA.SelfMulSub(mA,P);aA-=iA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(mB,P);aB+=iB*b2Vec2.CrossVV(rB,P)}this.m_positions[indexA].a=aA;this.m_positions[indexB].a=aB}return minSeparation>=-1.5*b2_linearSlop}}b2ContactSolver.InitializeVelocityConstraints_s_xfA=new b2Transform;b2ContactSolver.InitializeVelocityConstraints_s_xfB=new b2Transform;b2ContactSolver.InitializeVelocityConstraints_s_worldManifold=new b2WorldManifold;b2ContactSolver.WarmStart_s_P=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_dv=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_dv1=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_dv2=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_P=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_a=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_b=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_x=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_d=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_P1=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_P2=new b2Vec2;b2ContactSolver.SolveVelocityConstraints_s_P1P2=new b2Vec2;b2ContactSolver.SolvePositionConstraints_s_xfA=new b2Transform;b2ContactSolver.SolvePositionConstraints_s_xfB=new b2Transform;b2ContactSolver.SolvePositionConstraints_s_psm=new b2PositionSolverManifold;b2ContactSolver.SolvePositionConstraints_s_rA=new b2Vec2;b2ContactSolver.SolvePositionConstraints_s_rB=new b2Vec2;b2ContactSolver.SolvePositionConstraints_s_P=new b2Vec2;b2ContactSolver.SolveTOIPositionConstraints_s_xfA=new b2Transform;b2ContactSolver.SolveTOIPositionConstraints_s_xfB=new b2Transform;b2ContactSolver.SolveTOIPositionConstraints_s_psm=new b2PositionSolverManifold;b2ContactSolver.SolveTOIPositionConstraints_s_rA=new b2Vec2;b2ContactSolver.SolveTOIPositionConstraints_s_rB=new b2Vec2;b2ContactSolver.SolveTOIPositionConstraints_s_P=new b2Vec2;class b2Island{constructor(){this.m_allocator=null;this.m_bodies=[];this.m_contacts=[];this.m_joints=[];this.m_positions=b2Position.MakeArray(1024);this.m_velocities=b2Velocity.MakeArray(1024);this.m_bodyCount=0;this.m_jointCount=0;this.m_contactCount=0;this.m_bodyCapacity=0;this.m_contactCapacity=0;this.m_jointCapacity=0}Initialize(bodyCapacity,contactCapacity,jointCapacity,allocator,listener){this.m_bodyCapacity=bodyCapacity;this.m_contactCapacity=contactCapacity;this.m_jointCapacity=jointCapacity;this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;this.m_allocator=allocator;this.m_listener=listener;if(this.m_positions.lengthb2_maxTranslationSquared){const ratio=b2_maxTranslation/translation.Length();v.SelfMul(ratio)}const rotation=h*w;if(rotation*rotation>b2_maxRotationSquared){const ratio=b2_maxRotation/b2Abs(rotation);w*=ratio}c.x+=h*v.x;c.y+=h*v.y;a+=h*w;this.m_positions[i].a=a;this.m_velocities[i].w=w}timer.Reset();let positionSolved=false;for(let i=0;iangTolSqr||b2Vec2.DotVV(b.m_linearVelocity,b.m_linearVelocity)>linTolSqr){b.m_sleepTime=0;minSleepTime=0}else{b.m_sleepTime+=h;minSleepTime=b2Min(minSleepTime,b.m_sleepTime)}}if(minSleepTime>=b2_timeToSleep&&positionSolved){for(let i=0;ib2_maxTranslationSquared){const ratio=b2_maxTranslation/translation.Length();v.SelfMul(ratio)}const rotation=h*w;if(rotation*rotation>b2_maxRotationSquared){const ratio=b2_maxRotation/b2Abs(rotation);w*=ratio}c.SelfMulAdd(h,v);a+=h*w;this.m_positions[i].a=a;this.m_velocities[i].w=w;const body=this.m_bodies[i];body.m_sweep.c.Copy(c);body.m_sweep.a=a;body.m_linearVelocity.Copy(v);body.m_angularVelocity=w;body.SynchronizeTransform()}this.Report(contactSolver.m_velocityConstraints)}Report(constraints){if(this.m_listener===null){return}for(let i=0;i0){const inv_mass=1/this.m_mass;this.m_center.SelfMul(inv_mass);this.m_linearVelocity.SelfMul(inv_mass)}this.m_inertia=0;this.m_angularVelocity=0;for(let i=this.m_firstIndex;i0){this.m_angularVelocity*=1/this.m_inertia}this.m_timestamp=this.m_system.m_timestamp}}}b2ParticleGroup.GetLinearVelocityFromWorldPoint_s_t0=new b2Vec2;class b2StackQueue{constructor(capacity){this.m_front=0;this.m_back=0;this.m_capacity=0;this.m_buffer=b2MakeArray(capacity,index=>null);this.m_capacity=capacity}Push(item){if(this.m_back>=this.m_capacity){for(let i=this.m_front;i=this.m_capacity){if(this.m_capacity>0){this.m_buffer.concat(b2MakeArray(this.m_capacity,index=>null));this.m_capacity*=2}else{this.m_buffer.concat(b2MakeArray(1,index=>null));this.m_capacity=1}}}this.m_buffer[this.m_back]=item;this.m_back++}Pop(){this.m_buffer[this.m_front]=null;this.m_front++}Empty(){return this.m_front===this.m_back}Front(){const item=this.m_buffer[this.m_front];if(!item){throw new Error}return item}}class b2VoronoiDiagram{constructor(generatorCapacity){this.m_generatorCapacity=0;this.m_generatorCount=0;this.m_countX=0;this.m_countY=0;this.m_diagram=[];this.m_generatorBuffer=b2MakeArray(generatorCapacity,index=>new b2VoronoiDiagram.Generator);this.m_generatorCapacity=generatorCapacity}AddGenerator(center,tag,necessary){const g=this.m_generatorBuffer[this.m_generatorCount++];g.center.Copy(center);g.tag=tag;g.necessary=necessary}Generate(radius,margin){const inverseRadius=1/radius;const lower=new b2Vec2(+b2_maxFloat,+b2_maxFloat);const upper=new b2Vec2(-b2_maxFloat,-b2_maxFloat);let necessary_count=0;for(let k=0;k=0&&y>=0&&x0){queue.Push(new b2VoronoiDiagram.Task(x-1,y,i-1,g))}if(y>0){queue.Push(new b2VoronoiDiagram.Task(x,y-1,i-this.m_countX,g))}if(xb2){this.m_diagram[i]=b;if(x>0){queue.Push(new b2VoronoiDiagram.Task(x-1,y,i-1,b))}if(y>0){queue.Push(new b2VoronoiDiagram.Task(x,y-1,i-this.m_countX,b))}if(x=len){break}std_iter_swap(array,right,len)}}if(pos===0){break}left=len;len=stack[--pos]}return array}function std_stable_sort(array,first=0,len=array.length-first,cmp=default_compare){return std_sort(array,first,len,cmp)}function std_remove_if(array,predicate,length=array.length){let l=0;for(let c=0;c0){const step=Math.floor(count/2);let it=first+step;if(cmp(array[it],val)){first=++it;count-=step+1}else{count=step}}return first}function std_upper_bound(array,first,last,val,cmp=default_compare){let count=last-first;while(count>0){const step=Math.floor(count/2);let it=first+step;if(!cmp(val,array[it])){first=++it;count-=step+1}else{count=step}}return first}function std_rotate(array,first,n_first,last){let next=n_first;while(first!==next){std_iter_swap(array,first++,next++);if(next===last){next=n_first}else if(first===n_first){n_first=next}}}function std_unique(array,first,last,cmp){if(first===last){return last}let result=first;while(++first!==last){if(!cmp(array[result],array[first])){std_iter_swap(array,++result,first)}}return++result}class b2GrowableBuffer{constructor(allocator){this.data=[];this.count=0;this.capacity=0;this.allocator=allocator}Append(){if(this.count>=this.capacity){this.Grow()}return this.count++}Reserve(newCapacity){if(this.capacity>=newCapacity){return}for(let i=this.capacity;i=0){this.ReportFixtureAndParticle(fixture,childIndex,index)}}return true}ReportParticle(system,index){return false}ReportFixtureAndParticle(fixture,childIndex,index){}}class b2ParticleContact{constructor(){this.indexA=0;this.indexB=0;this.weight=0;this.normal=new b2Vec2;this.flags=0}SetIndices(a,b){this.indexA=a;this.indexB=b}SetWeight(w){this.weight=w}SetNormal(n){this.normal.Copy(n)}SetFlags(f){this.flags=f}GetIndexA(){return this.indexA}GetIndexB(){return this.indexB}GetWeight(){return this.weight}GetNormal(){return this.normal}GetFlags(){return this.flags}IsEqual(rhs){return this.indexA===rhs.indexA&&this.indexB===rhs.indexB&&this.flags===rhs.flags&&this.weight===rhs.weight&&this.normal.x===rhs.normal.x&&this.normal.y===rhs.normal.y}IsNotEqual(rhs){return!this.IsEqual(rhs)}ApproximatelyEqual(rhs){const MAX_WEIGHT_DIFF=0.01;const MAX_NORMAL_DIFF_SQ=0.01*0.01;return this.indexA===rhs.indexA&&this.indexB===rhs.indexB&&this.flags===rhs.flags&&b2Abs(this.weight-rhs.weight)0);this.m_proxyBuffer=new b2GrowableBuffer(()=>new b2ParticleSystem.Proxy);this.m_contactBuffer=new b2GrowableBuffer(()=>new b2ParticleContact);this.m_bodyContactBuffer=new b2GrowableBuffer(()=>new b2ParticleBodyContact);this.m_pairBuffer=new b2GrowableBuffer(()=>new b2ParticlePair);this.m_triadBuffer=new b2GrowableBuffer(()=>new b2ParticleTriad);this.m_expirationTimeBuffer=new b2ParticleSystem.UserOverridableBuffer;this.m_indexByExpirationTimeBuffer=new b2ParticleSystem.UserOverridableBuffer;this.m_timeElapsed=0;this.m_expirationTimeBufferRequiresSorting=false;this.m_groupCount=0;this.m_groupList=null;this.m_def=new b2ParticleSystemDef;this.m_prev=null;this.m_next=null;this.SetStrictContactCheck(def.strictContactCheck);this.SetDensity(def.density);this.SetGravityScale(def.gravityScale);this.SetRadius(def.radius);this.SetMaxParticleCount(def.maxCount);this.m_def=def.Clone();this.m_world=world;this.SetDestructionByAge(this.m_def.destroyByAge)}static computeTag(x,y){return(y+b2ParticleSystem.yOffset>>>0<>>0)>>>0}static computeRelativeTag(tag,x,y){return tag+(y<>>0}Drop(){while(this.m_groupList){this.DestroyParticleGroup(this.m_groupList)}this.FreeUserOverridableBuffer(this.m_handleIndexBuffer);this.FreeUserOverridableBuffer(this.m_flagsBuffer);this.FreeUserOverridableBuffer(this.m_lastBodyContactStepBuffer);this.FreeUserOverridableBuffer(this.m_bodyContactCountBuffer);this.FreeUserOverridableBuffer(this.m_consecutiveContactStepsBuffer);this.FreeUserOverridableBuffer(this.m_positionBuffer);this.FreeUserOverridableBuffer(this.m_velocityBuffer);this.FreeUserOverridableBuffer(this.m_colorBuffer);this.FreeUserOverridableBuffer(this.m_userDataBuffer);this.FreeUserOverridableBuffer(this.m_expirationTimeBuffer);this.FreeUserOverridableBuffer(this.m_indexByExpirationTimeBuffer);this.FreeBuffer(this.m_forceBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_weightBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_staticPressureBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_accumulationBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_accumulation2Buffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_depthBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_groupBuffer,this.m_internalAllocatedCapacity)}CreateParticle(def){if(this.m_world.IsLocked()){throw new Error}if(this.m_count>=this.m_internalAllocatedCapacity){const capacity=this.m_count?2*this.m_count:b2_minParticleSystemBufferCapacity;this.ReallocateInternalAllocatedBuffers(capacity)}if(this.m_count>=this.m_internalAllocatedCapacity){if(this.m_def.destroyByAge){this.DestroyOldestParticle(0,false);this.SolveZombie()}else{return b2_invalidParticleIndex}}const index=this.m_count++;if(!this.m_flagsBuffer.data){throw new Error}this.m_flagsBuffer.data[index]=0;if(this.m_lastBodyContactStepBuffer.data){this.m_lastBodyContactStepBuffer.data[index]=0}if(this.m_bodyContactCountBuffer.data){this.m_bodyContactCountBuffer.data[index]=0}if(this.m_consecutiveContactStepsBuffer.data){this.m_consecutiveContactStepsBuffer.data[index]=0}if(!this.m_positionBuffer.data){throw new Error}if(!this.m_velocityBuffer.data){throw new Error}this.m_positionBuffer.data[index]=(this.m_positionBuffer.data[index]||new b2Vec2).Copy(b2Maybe(def.position,b2Vec2.ZERO));this.m_velocityBuffer.data[index]=(this.m_velocityBuffer.data[index]||new b2Vec2).Copy(b2Maybe(def.velocity,b2Vec2.ZERO));this.m_weightBuffer[index]=0;this.m_forceBuffer[index]=(this.m_forceBuffer[index]||new b2Vec2).SetZero();if(this.m_staticPressureBuffer){this.m_staticPressureBuffer[index]=0}if(this.m_depthBuffer){this.m_depthBuffer[index]=0}const color=new b2Color().Copy(b2Maybe(def.color,b2Color.ZERO));if(this.m_colorBuffer.data||!color.IsZero()){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data);this.m_colorBuffer.data[index]=(this.m_colorBuffer.data[index]||new b2Color).Copy(color)}if(this.m_userDataBuffer.data||def.userData){this.m_userDataBuffer.data=this.RequestBuffer(this.m_userDataBuffer.data);this.m_userDataBuffer.data[index]=def.userData}if(this.m_handleIndexBuffer.data){this.m_handleIndexBuffer.data[index]=null}const proxy=this.m_proxyBuffer.data[this.m_proxyBuffer.Append()];const lifetime=b2Maybe(def.lifetime,0);const finiteLifetime=lifetime>0;if(this.m_expirationTimeBuffer.data||finiteLifetime){this.SetParticleLifetime(index,finiteLifetime?lifetime:this.ExpirationTimeToLifetime(-this.GetQuantizedTimeElapsed()));if(!this.m_indexByExpirationTimeBuffer.data){throw new Error}this.m_indexByExpirationTimeBuffer.data[index]=index}proxy.index=index;const group=b2Maybe(def.group,null);this.m_groupBuffer[index]=group;if(group){if(group.m_firstIndex0?oldestFiniteLifetimeParticle:oldestInfiniteLifetimeParticle,callDestructionListener)}DestroyParticlesInShape(shape,xf,callDestructionListener=false){const s_aabb=b2ParticleSystem.DestroyParticlesInShape_s_aabb;if(this.m_world.IsLocked()){throw new Error}const callback=new b2ParticleSystem.DestroyParticlesInShapeCallback(this,shape,xf,callDestructionListener);const aabb=s_aabb;shape.ComputeAABB(aabb,xf,0);this.m_world.QueryAABB(callback,aabb);return callback.Destroyed()}CreateParticleGroup(groupDef){const s_transform=b2ParticleSystem.CreateParticleGroup_s_transform;if(this.m_world.IsLocked()){throw new Error}const transform=s_transform;transform.SetPositionAngle(b2Maybe(groupDef.position,b2Vec2.ZERO),b2Maybe(groupDef.angle,0));const firstIndex=this.m_count;if(groupDef.shape){this.CreateParticlesWithShapeForGroup(groupDef.shape,groupDef,transform)}if(groupDef.shapes){this.CreateParticlesWithShapesForGroup(groupDef.shapes,b2Maybe(groupDef.shapeCount,groupDef.shapes.length),groupDef,transform)}if(groupDef.positionData){const count=b2Maybe(groupDef.particleCount,groupDef.positionData.length);for(let i=0;inew b2ParticleSystem.ParticleListNode);b2ParticleSystem.InitializeParticleLists(group,nodeBuffer);this.MergeParticleListsInContact(group,nodeBuffer);const survivingList=b2ParticleSystem.FindLongestParticleList(group,nodeBuffer);this.MergeZombieParticleListNodes(group,nodeBuffer,survivingList);this.CreateParticleGroupsFromParticleList(group,nodeBuffer,survivingList);this.UpdatePairsAndTriadsWithParticleList(group,nodeBuffer)}GetParticleGroupList(){return this.m_groupList}GetParticleGroupCount(){return this.m_groupCount}GetParticleCount(){return this.m_count}GetMaxParticleCount(){return this.m_def.maxCount}SetMaxParticleCount(count){this.m_def.maxCount=count}GetAllParticleFlags(){return this.m_allParticleFlags}GetAllGroupFlags(){return this.m_allGroupFlags}SetPaused(paused){this.m_paused=paused}GetPaused(){return this.m_paused}SetDensity(density){this.m_def.density=density;this.m_inverseDensity=1/this.m_def.density}GetDensity(){return this.m_def.density}SetGravityScale(gravityScale){this.m_def.gravityScale=gravityScale}GetGravityScale(){return this.m_def.gravityScale}SetDamping(damping){this.m_def.dampingStrength=damping}GetDamping(){return this.m_def.dampingStrength}SetStaticPressureIterations(iterations){this.m_def.staticPressureIterations=iterations}GetStaticPressureIterations(){return this.m_def.staticPressureIterations}SetRadius(radius){this.m_particleDiameter=2*radius;this.m_squaredDiameter=this.m_particleDiameter*this.m_particleDiameter;this.m_inverseDiameter=1/this.m_particleDiameter}GetRadius(){return this.m_particleDiameter/2}GetPositionBuffer(){if(!this.m_positionBuffer.data){throw new Error}return this.m_positionBuffer.data}GetVelocityBuffer(){if(!this.m_velocityBuffer.data){throw new Error}return this.m_velocityBuffer.data}GetColorBuffer(){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data);return this.m_colorBuffer.data}GetGroupBuffer(){return this.m_groupBuffer}GetWeightBuffer(){return this.m_weightBuffer}GetUserDataBuffer(){this.m_userDataBuffer.data=this.RequestBuffer(this.m_userDataBuffer.data);return this.m_userDataBuffer.data}GetFlagsBuffer(){if(!this.m_flagsBuffer.data){throw new Error}return this.m_flagsBuffer.data}SetParticleFlags(index,newFlags){if(!this.m_flagsBuffer.data){throw new Error}const oldFlags=this.m_flagsBuffer.data[index];if(oldFlags&~newFlags){this.m_needsUpdateAllParticleFlags=true}if(~this.m_allParticleFlags&newFlags){if(newFlags&exports.b2ParticleFlag.b2_tensileParticle){this.m_accumulation2Buffer=this.RequestBuffer(this.m_accumulation2Buffer)}if(newFlags&exports.b2ParticleFlag.b2_colorMixingParticle){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data)}this.m_allParticleFlags|=newFlags}this.m_flagsBuffer.data[index]=newFlags}GetParticleFlags(index){if(!this.m_flagsBuffer.data){throw new Error}return this.m_flagsBuffer.data[index]}SetFlagsBuffer(buffer,capacity){this.SetUserOverridableBuffer(this.m_flagsBuffer,buffer,capacity)}SetPositionBuffer(buffer,capacity){this.SetUserOverridableBuffer(this.m_positionBuffer,buffer,capacity)}SetVelocityBuffer(buffer,capacity){this.SetUserOverridableBuffer(this.m_velocityBuffer,buffer,capacity)}SetColorBuffer(buffer,capacity){this.SetUserOverridableBuffer(this.m_colorBuffer,buffer,capacity)}SetUserDataBuffer(buffer,capacity){this.SetUserOverridableBuffer(this.m_userDataBuffer,buffer,capacity)}GetContacts(){return this.m_contactBuffer.data}GetContactCount(){return this.m_contactBuffer.count}GetBodyContacts(){return this.m_bodyContactBuffer.data}GetBodyContactCount(){return this.m_bodyContactBuffer.count}GetPairs(){return this.m_pairBuffer.data}GetPairCount(){return this.m_pairBuffer.count}GetTriads(){return this.m_triadBuffer.data}GetTriadCount(){return this.m_triadBuffer.count}SetStuckThreshold(steps){this.m_stuckThreshold=steps;if(steps>0){this.m_lastBodyContactStepBuffer.data=this.RequestBuffer(this.m_lastBodyContactStepBuffer.data);this.m_bodyContactCountBuffer.data=this.RequestBuffer(this.m_bodyContactCountBuffer.data);this.m_consecutiveContactStepsBuffer.data=this.RequestBuffer(this.m_consecutiveContactStepsBuffer.data)}}GetStuckCandidates(){return this.m_stuckParticleBuffer.Data()}GetStuckCandidateCount(){return this.m_stuckParticleBuffer.GetCount()}ComputeCollisionEnergy(){if(!this.m_velocityBuffer.data){throw new Error}const s_v=b2ParticleSystem.ComputeCollisionEnergy_s_v;const vel_data=this.m_velocityBuffer.data;let sum_v2=0;for(let k=0;k0?this.GetQuantizedTimeElapsed()+quantizedLifetime:quantizedLifetime;if(newExpirationTime!==this.m_expirationTimeBuffer.data[index]){this.m_expirationTimeBuffer.data[index]=newExpirationTime;this.m_expirationTimeBufferRequiresSorting=true}}GetParticleLifetime(index){return this.ExpirationTimeToLifetime(this.GetExpirationTimeBuffer()[index])}SetDestructionByAge(enable){if(enable){this.GetExpirationTimeBuffer()}this.m_def.destroyByAge=enable}GetDestructionByAge(){return this.m_def.destroyByAge}GetExpirationTimeBuffer(){this.m_expirationTimeBuffer.data=this.RequestBuffer(this.m_expirationTimeBuffer.data);return this.m_expirationTimeBuffer.data}ExpirationTimeToLifetime(expirationTime){return(expirationTime>0?expirationTime-this.GetQuantizedTimeElapsed():expirationTime)*this.m_def.lifetimeGranularity}GetIndexByExpirationTimeBuffer(){if(this.GetParticleCount()){this.SetParticleLifetime(0,this.GetParticleLifetime(0))}else{this.m_indexByExpirationTimeBuffer.data=this.RequestBuffer(this.m_indexByExpirationTimeBuffer.data)}if(!this.m_indexByExpirationTimeBuffer.data){throw new Error}return this.m_indexByExpirationTimeBuffer.data}ParticleApplyLinearImpulse(index,impulse){this.ApplyLinearImpulse(index,index+1,impulse)}ApplyLinearImpulse(firstIndex,lastIndex,impulse){if(!this.m_velocityBuffer.data){throw new Error}const vel_data=this.m_velocityBuffer.data;const numParticles=lastIndex-firstIndex;const totalMass=numParticles*this.GetParticleMass();const velocityDelta=new b2Vec2().Copy(impulse).SelfMul(1/totalMass);for(let i=firstIndex;i=0){const p=b2Vec2.SubVV(point1,pos_data[i],s_p);const pv=b2Vec2.DotVV(p,v);const p2=b2Vec2.DotVV(p,p);const determinant=pv*pv-v2*(p2-this.m_squaredDiameter);if(determinant>=0){const sqrtDeterminant=b2Sqrt(determinant);let t=(-pv-sqrtDeterminant)/v2;if(t>fraction){continue}if(t<0){t=(-pv+sqrtDeterminant)/v2;if(t<0||t>fraction){continue}}const n=b2Vec2.AddVMulSV(p,t,v,s_n);n.Normalize();const f=callback.ReportParticle(this,i,b2Vec2.AddVMulSV(point1,t,v,s_point),n,t);fraction=b2Min(fraction,f);if(fraction<=0){break}}}}ComputeAABB(aabb){const particleCount=this.GetParticleCount();aabb.lowerBound.x=+b2_maxFloat;aabb.lowerBound.y=+b2_maxFloat;aabb.upperBound.x=-b2_maxFloat;aabb.upperBound.y=-b2_maxFloat;if(!this.m_positionBuffer.data){throw new Error}const pos_data=this.m_positionBuffer.data;for(let i=0;imaxCount?maxCount:capacity}capacity=LimitCapacity(capacity,this.m_def.maxCount);capacity=LimitCapacity(capacity,this.m_flagsBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_positionBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_velocityBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_colorBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_userDataBuffer.userSuppliedCapacity);if(this.m_internalAllocatedCapacity0;this.m_lastBodyContactStepBuffer.data=this.ReallocateBuffer4(this.m_lastBodyContactStepBuffer,this.m_internalAllocatedCapacity,capacity,stuck);this.m_bodyContactCountBuffer.data=this.ReallocateBuffer4(this.m_bodyContactCountBuffer,this.m_internalAllocatedCapacity,capacity,stuck);this.m_consecutiveContactStepsBuffer.data=this.ReallocateBuffer4(this.m_consecutiveContactStepsBuffer,this.m_internalAllocatedCapacity,capacity,stuck);this.m_positionBuffer.data=this.ReallocateBuffer4(this.m_positionBuffer,this.m_internalAllocatedCapacity,capacity,false);this.m_velocityBuffer.data=this.ReallocateBuffer4(this.m_velocityBuffer,this.m_internalAllocatedCapacity,capacity,false);this.m_forceBuffer=this.ReallocateBuffer5(this.m_forceBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_weightBuffer=this.ReallocateBuffer5(this.m_weightBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_staticPressureBuffer=this.ReallocateBuffer5(this.m_staticPressureBuffer,0,this.m_internalAllocatedCapacity,capacity,true);this.m_accumulationBuffer=this.ReallocateBuffer5(this.m_accumulationBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_accumulation2Buffer=this.ReallocateBuffer5(this.m_accumulation2Buffer,0,this.m_internalAllocatedCapacity,capacity,true);this.m_depthBuffer=this.ReallocateBuffer5(this.m_depthBuffer,0,this.m_internalAllocatedCapacity,capacity,true);this.m_colorBuffer.data=this.ReallocateBuffer4(this.m_colorBuffer,this.m_internalAllocatedCapacity,capacity,true);this.m_groupBuffer=this.ReallocateBuffer5(this.m_groupBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_userDataBuffer.data=this.ReallocateBuffer4(this.m_userDataBuffer,this.m_internalAllocatedCapacity,capacity,true);this.m_expirationTimeBuffer.data=this.ReallocateBuffer4(this.m_expirationTimeBuffer,this.m_internalAllocatedCapacity,capacity,true);this.m_indexByExpirationTimeBuffer.data=this.ReallocateBuffer4(this.m_indexByExpirationTimeBuffer,this.m_internalAllocatedCapacity,capacity,false);this.m_internalAllocatedCapacity=capacity}}CreateParticleForGroup(groupDef,xf,p){const particleDef=new b2ParticleDef;particleDef.flags=b2Maybe(groupDef.flags,0);b2Transform.MulXV(xf,p,particleDef.position);b2Vec2.AddVV(b2Maybe(groupDef.linearVelocity,b2Vec2.ZERO),b2Vec2.CrossSV(b2Maybe(groupDef.angularVelocity,0),b2Vec2.SubVV(particleDef.position,b2Maybe(groupDef.position,b2Vec2.ZERO),b2Vec2.s_t0),b2Vec2.s_t0),particleDef.velocity);particleDef.color.Copy(b2Maybe(groupDef.color,b2Color.ZERO));particleDef.lifetime=b2Maybe(groupDef.lifetime,0);particleDef.userData=groupDef.userData;this.CreateParticle(particleDef)}CreateParticlesStrokeShapeForGroup(shape,groupDef,xf){const s_edge=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_edge;const s_d=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_d;const s_p=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_p;let stride=b2Maybe(groupDef.stride,0);if(stride===0){stride=this.GetParticleStride()}let positionOnEdge=0;const childCount=shape.GetChildCount();for(let childIndex=0;childIndex=firstIndex&&a=firstIndex&&b{if(!system.m_flagsBuffer.data){throw new Error}const af=system.m_flagsBuffer.data[a];const bf=system.m_flagsBuffer.data[b];const cf=system.m_flagsBuffer.data[c];if((af|bf|cf)&b2ParticleSystem.k_triadFlags&&filter.ShouldCreateTriad(a,b,c)){const pa=pos_data[a];const pb=pos_data[b];const pc=pos_data[c];const dab=b2Vec2.SubVV(pa,pb,s_dab);const dbc=b2Vec2.SubVV(pb,pc,s_dbc);const dca=b2Vec2.SubVV(pc,pa,s_dca);const maxDistanceSquared=b2_maxTriadDistanceSquared*system.m_squaredDiameter;if(b2Vec2.DotVV(dab,dab)>maxDistanceSquared||b2Vec2.DotVV(dbc,dbc)>maxDistanceSquared||b2Vec2.DotVV(dca,dca)>maxDistanceSquared){return}const groupA=system.m_groupBuffer[a];const groupB=system.m_groupBuffer[b];const groupC=system.m_groupBuffer[c];const triad=system.m_triadBuffer.data[system.m_triadBuffer.Append()];triad.indexA=a;triad.indexB=b;triad.indexC=c;triad.flags=af|bf|cf;triad.strength=b2Min(b2Min(groupA?groupA.m_strength:1,groupB?groupB.m_strength:1),groupC?groupC.m_strength:1);const midPoint_x=(pa.x+pb.x+pc.x)/3;const midPoint_y=(pa.y+pb.y+pc.y)/3;triad.pa.x=pa.x-midPoint_x;triad.pa.y=pa.y-midPoint_y;triad.pb.x=pb.x-midPoint_x;triad.pb.y=pb.y-midPoint_y;triad.pc.x=pc.x-midPoint_x;triad.pc.y=pc.y-midPoint_y;triad.ka=-b2Vec2.DotVV(dca,dab);triad.kb=-b2Vec2.DotVV(dab,dbc);triad.kc=-b2Vec2.DotVV(dbc,dca);triad.s=b2Vec2.CrossVV(pa,pb)+b2Vec2.CrossVV(pb,pc)+b2Vec2.CrossVV(pc,pa)}};diagram.GetNodes(callback);std_stable_sort(this.m_triadBuffer.data,0,this.m_triadBuffer.count,b2ParticleSystem.CompareTriadIndices);this.m_triadBuffer.Unique(b2ParticleSystem.MatchTriadIndices)}}UpdatePairsAndTriadsWithReactiveParticles(){const filter=new b2ParticleSystem.ReactiveFilter(this.m_flagsBuffer);this.UpdatePairsAndTriads(0,this.m_count,filter);if(!this.m_flagsBuffer.data){throw new Error}for(let i=0;i>0;for(let t=0;tap1){this.m_depthBuffer[a]=ap1;updated=true}if(bp0>bp1){this.m_depthBuffer[b]=bp1;updated=true}}if(!updated){break}}for(let i=0;i{return(contact.flags&exports.b2ParticleFlag.b2_particleContactFilterParticle)!==0&&!contactFilter.ShouldCollideParticleParticle(system,contact.indexA,contact.indexB)};this.m_contactBuffer.RemoveIf(predicate)}NotifyContactListenerPreContact(particlePairs){const contactListener=this.GetParticleContactListener();if(contactListener===null){return}particlePairs.Initialize(this.m_contactBuffer,this.m_flagsBuffer);throw new Error}NotifyContactListenerPostContact(particlePairs){const contactListener=this.GetParticleContactListener();if(contactListener===null){return}for(let k=0;k0){if(!this.m_bodyContactCountBuffer.data){throw new Error}if(!this.m_lastBodyContactStepBuffer.data){throw new Error}if(!this.m_consecutiveContactStepsBuffer.data){throw new Error}const particleCount=this.GetParticleCount();for(let i=0;ithis.m_lastBodyContactStepBuffer.data[i]+1){this.m_consecutiveContactStepsBuffer.data[i]=0}}}this.m_bodyContactBuffer.SetCount(0);this.m_stuckParticleBuffer.SetCount(0);const aabb=s_aabb;this.ComputeAABB(aabb);const callback=new b2ParticleSystem.UpdateBodyContactsCallback(this,this.GetFixtureContactFilter());this.m_world.QueryAABB(callback,aabb);if(this.m_def.strictContactCheck){this.RemoveSpuriousBodyContacts()}this.NotifyBodyContactListenerPostContact(fixtureSet)}Solve(step){const s_subStep=b2ParticleSystem.Solve_s_subStep;if(this.m_count===0){return}if(this.m_expirationTimeBuffer.data){this.SolveLifetimes(step)}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_zombieParticle){this.SolveZombie()}if(this.m_needsUpdateAllParticleFlags){this.UpdateAllParticleFlags()}if(this.m_needsUpdateAllGroupFlags){this.UpdateAllGroupFlags()}if(this.m_paused){return}for(this.m_iterationIndex=0;this.m_iterationIndexcriticalVelocitySquared){v.SelfMul(b2Sqrt(criticalVelocitySquared/v2))}}}SolveGravity(step){if(!this.m_velocityBuffer.data){throw new Error}const s_gravity=b2ParticleSystem.SolveGravity_s_gravity;const vel_data=this.m_velocityBuffer.data;const gravity=b2Vec2.MulSV(step.dt*this.m_def.gravityScale,this.m_world.GetGravity(),s_gravity);for(let i=0;i=0){const pc=pos_data[c];const cGroup=this.m_groupBuffer[c];if(aGroup!==cGroup&&bGroup!==cGroup){const vc=this.GetLinearVelocity(cGroup,c,pc,s_vc);const pca=b2Vec2.SubVV(pc,pa,s_pca);const vca=b2Vec2.SubVV(vc,va,s_vca);const e2=b2Vec2.CrossVV(vba,vca);const e1=b2Vec2.CrossVV(pba,vca)-b2Vec2.CrossVV(pca,vba);const e0=b2Vec2.CrossVV(pba,pca);let s,t;const qba=s_qba;const qca=s_qca;if(e2===0){if(e1===0){continue}t=-e0/e1;if(!(t>=0&&t=0&&s<=1)){continue}}else{const det=e1*e1-4*e0*e2;if(det<0){continue}const sqrtDet=b2Sqrt(det);let t1=(-e1-sqrtDet)/(2*e2);let t2=(-e1+sqrtDet)/(2*e2);if(t1>t2){const tmp=t1;t1=t2;t2=tmp}t=t1;b2Vec2.AddVMulSV(pba,t,vba,qba);b2Vec2.AddVMulSV(pca,t,vca,qca);s=b2Vec2.DotVV(qba,qca)/b2Vec2.DotVV(qba,qba);if(!(t>=0&&t=0&&s<=1)){t=t2;if(!(t>=0&&t=0&&s<=1)){continue}}}const dv=s_dv;dv.x=va.x+s*vba.x-vc.x;dv.y=va.y+s*vba.y-vc.y;const f=b2Vec2.MulSV(mass,dv,s_f);if(cGroup&&this.IsRigidGroup(cGroup)){const mass=cGroup.GetMass();const inertia=cGroup.GetInertia();if(mass>0){cGroup.m_linearVelocity.SelfMulAdd(1/mass,f)}if(inertia>0){cGroup.m_angularVelocity+=b2Vec2.CrossVV(b2Vec2.SubVV(pc,cGroup.GetCenter(),b2Vec2.s_t0),f)/inertia}}else{vel_data[c].SelfAdd(dv)}this.ParticleApplyForce(c,f.SelfMul(-step.inv_dt))}}}}}SolveStaticPressure(step){if(!this.m_flagsBuffer.data){throw new Error}this.m_staticPressureBuffer=this.RequestBuffer(this.m_staticPressureBuffer);const criticalPressure=this.GetCriticalPressure(step);const pressurePerWeight=this.m_def.staticPressureStrength*criticalPressure;const maxPressure=b2_maxParticlePressure*criticalPressure;const relaxation=this.m_def.staticPressureRelaxation;for(let t=0;tminWeight){const b=contact.body;const m=contact.mass;const p=pos_data[a];const n=contact.normal;const f=b2Vec2.MulSV(powderStrength*m*(w-minWeight),n,s_f);vel_data[a].SelfMulSub(inv_mass,f);b.ApplyLinearImpulse(f,p,true)}}}for(let k=0;kminWeight){const a=contact.indexA;const b=contact.indexB;const n=contact.normal;const f=b2Vec2.MulSV(powderStrength*(w-minWeight),n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f)}}}}SolveSolid(step){const s_f=b2ParticleSystem.SolveSolid_s_f;if(!this.m_velocityBuffer.data){throw new Error}const vel_data=this.m_velocityBuffer.data;this.m_depthBuffer=this.RequestBuffer(this.m_depthBuffer);const ejectionStrength=step.inv_dt*this.m_def.ejectionStrength;for(let k=0;k{return proxy.index<0},IsContactInvalid:contact=>{return contact.indexA<0||contact.indexB<0},IsBodyContactInvalid:contact=>{return contact.index<0},IsPairInvalid:pair=>{return pair.indexA<0||pair.indexB<0},IsTriadInvalid:triad=>{return triad.indexA<0||triad.indexB<0||triad.indexC<0}};for(let k=0;k=0){firstIndex=b2Min(firstIndex,j);lastIndex=b2Max(lastIndex,j+1)}else{modified=true}}if(firstIndex{const expirationTimeA=expirationTimes[particleIndexA];const expirationTimeB=expirationTimes[particleIndexB];const infiniteExpirationTimeA=expirationTimeA<=0;const infiniteExpirationTimeB=expirationTimeB<=0;return infiniteExpirationTimeA===infiniteExpirationTimeB?expirationTimeA>expirationTimeB:infiniteExpirationTimeA};std_sort(expirationTimeIndices,0,particleCount,ExpirationTimeComparator);this.m_expirationTimeBufferRequiresSorting=false}for(let i=particleCount-1;i>=0;--i){const particleIndex=expirationTimeIndices[i];const expirationTime=expirationTimes[particleIndex];if(quantizedTimeElapsedrhs.weight}return lhs.index{if(contact.index!==lastIndex){currentContacts=0;lastIndex=contact.index}if(currentContacts++>k_maxContactsPerPoint){return true}const n=s_n.Copy(contact.normal);n.SelfMul(system.m_particleDiameter*(1-contact.weight));if(!system.m_positionBuffer.data){throw new Error}const pos=b2Vec2.AddVV(system.m_positionBuffer.data[contact.index],n,s_pos);if(!contact.fixture.TestPoint(pos)){const childCount=contact.fixture.GetShape().GetChildCount();for(let childIndex=0;childIndexthis.m_stuckThreshold){this.m_stuckParticleBuffer.data[this.m_stuckParticleBuffer.Append()]=particle}}this.m_lastBodyContactStepBuffer.data[particle]=this.m_timestamp}ValidateParticleIndex(index){return index>=0&&index0?1/mass:0;invInertia[0]=inertia>0?1/inertia:0;tangentDistance[0]=b2Vec2.CrossVV(b2Vec2.SubVV(point,center,b2Vec2.s_t0),normal)}InitDampingParameterWithRigidGroupOrParticle(invMass,invInertia,tangentDistance,isRigidGroup,group,particleIndex,point,normal){if(group&&isRigidGroup){this.InitDampingParameter(invMass,invInertia,tangentDistance,group.GetMass(),group.GetInertia(),group.GetCenter(),point,normal)}else{if(!this.m_flagsBuffer.data){throw new Error}const flags=this.m_flagsBuffer.data[particleIndex];this.InitDampingParameter(invMass,invInertia,tangentDistance,flags&exports.b2ParticleFlag.b2_wallParticle?0:this.GetParticleMass(),0,point,point,normal)}}ComputeDampingImpulse(invMassA,invInertiaA,tangentDistanceA,invMassB,invInertiaB,tangentDistanceB,normalVelocity){const invMass=invMassA+invInertiaA*tangentDistanceA*tangentDistanceA+invMassB+invInertiaB*tangentDistanceB*tangentDistanceB;return invMass>0?normalVelocity/invMass:0}ApplyDamping(invMass,invInertia,tangentDistance,isRigidGroup,group,particleIndex,impulse,normal){if(group&&isRigidGroup){group.m_linearVelocity.SelfMulAdd(impulse*invMass,normal);group.m_angularVelocity+=impulse*tangentDistance*invInertia}else{if(!this.m_velocityBuffer.data){throw new Error}this.m_velocityBuffer.data[particleIndex].SelfMulAdd(impulse*invMass,normal)}}}b2ParticleSystem.xTruncBits=12;b2ParticleSystem.yTruncBits=12;b2ParticleSystem.tagBits=8*4;b2ParticleSystem.yOffset=1<>>0;this.m_xUpper=(upper&b2ParticleSystem.xMask)>>>0;this.m_yLower=(lower&b2ParticleSystem.yMask)>>>0;this.m_yUpper=(upper&b2ParticleSystem.yMask)>>>0;this.m_first=first;this.m_last=last}GetNext(){while(this.m_first>>0;if(xTag>=this.m_xLower&&xTag<=this.m_xUpper){return this.m_system.m_proxyBuffer.data[this.m_first++].index}this.m_first++}return b2_invalidParticleIndex}}b2ParticleSystem.InsideBoundsEnumerator=InsideBoundsEnumerator;class ParticleListNode{constructor(){this.next=null;this.count=0;this.index=0}}b2ParticleSystem.ParticleListNode=ParticleListNode;class FixedSetAllocator{Allocate(itemSize,count){return count}Clear(){}GetCount(){return 0}Invalidate(itemIndex){}GetValidBuffer(){return[]}GetBuffer(){return[]}SetCount(count){}}b2ParticleSystem.FixedSetAllocator=FixedSetAllocator;class FixtureParticle{constructor(fixture,particle){this.second=b2_invalidParticleIndex;this.first=fixture;this.second=particle}}b2ParticleSystem.FixtureParticle=FixtureParticle;class FixtureParticleSet extends b2ParticleSystem.FixedSetAllocator{Initialize(bodyContactBuffer,flagsBuffer){}Find(pair){return b2_invalidParticleIndex}}b2ParticleSystem.FixtureParticleSet=FixtureParticleSet;class ParticlePair{constructor(particleA,particleB){this.first=b2_invalidParticleIndex;this.second=b2_invalidParticleIndex;this.first=particleA;this.second=particleB}}b2ParticleSystem.ParticlePair=ParticlePair;class b2ParticlePairSet extends b2ParticleSystem.FixedSetAllocator{Initialize(contactBuffer,flagsBuffer){}Find(pair){return b2_invalidParticleIndex}}b2ParticleSystem.b2ParticlePairSet=b2ParticlePairSet;class ConnectionFilter{IsNecessary(index){return true}ShouldCreatePair(a,b){return true}ShouldCreateTriad(a,b,c){return true}}b2ParticleSystem.ConnectionFilter=ConnectionFilter;class DestroyParticlesInShapeCallback extends b2QueryCallback{constructor(system,shape,xf,callDestructionListener){super();this.m_callDestructionListener=false;this.m_destroyed=0;this.m_system=system;this.m_shape=shape;this.m_xf=xf;this.m_callDestructionListener=callDestructionListener;this.m_destroyed=0}ReportFixture(fixture){return false}ReportParticle(particleSystem,index){if(particleSystem!==this.m_system){return false}if(!this.m_system.m_positionBuffer.data){throw new Error}if(this.m_shape.TestPoint(this.m_xf,this.m_system.m_positionBuffer.data[index])){this.m_system.DestroyParticle(index,this.m_callDestructionListener);this.m_destroyed++}return true}Destroyed(){return this.m_destroyed}}b2ParticleSystem.DestroyParticlesInShapeCallback=DestroyParticlesInShapeCallback;class JoinParticleGroupsFilter extends b2ParticleSystem.ConnectionFilter{constructor(threshold){super();this.m_threshold=0;this.m_threshold=threshold}ShouldCreatePair(a,b){return a0?1/bm:0;const invBI=bI>0?1/bI:0;const invAm=this.m_system.m_flagsBuffer.data[a]&exports.b2ParticleFlag.b2_wallParticle?0:this.m_system.GetParticleInvMass();const rp=b2Vec2.SubVV(ap,bp,s_rp);const rpn=b2Vec2.CrossVV(rp,n);const invM=invAm+invBm+invBI*rpn*rpn;const contact=this.m_system.m_bodyContactBuffer.data[this.m_system.m_bodyContactBuffer.Append()];contact.index=a;contact.body=b;contact.fixture=fixture;contact.weight=1-d*this.m_system.m_inverseDiameter;contact.normal.Copy(n.SelfNeg());contact.mass=invM>0?1/invM:0;this.m_system.DetectStuckParticle(a)}}}UpdateBodyContactsCallback.ReportFixtureAndParticle_s_n=new b2Vec2;UpdateBodyContactsCallback.ReportFixtureAndParticle_s_rp=new b2Vec2;b2ParticleSystem.UpdateBodyContactsCallback=UpdateBodyContactsCallback;class SolveCollisionCallback extends b2FixtureParticleQueryCallback{constructor(system,step){super(system);this.m_step=step}ReportFixtureAndParticle(fixture,childIndex,a){const s_p1=b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_p1;const s_output=b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_output;const s_input=b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_input;const s_p=b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_p;const s_v=b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_v;const s_f=b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_f;const body=fixture.GetBody();if(!this.m_system.m_positionBuffer.data){throw new Error}if(!this.m_system.m_velocityBuffer.data){throw new Error}const ap=this.m_system.m_positionBuffer.data[a];const av=this.m_system.m_velocityBuffer.data[a];const output=s_output;const input=s_input;if(this.m_system.m_iterationIndex===0){const p1=b2Transform.MulTXV(body.m_xf0,ap,s_p1);if(fixture.GetShape().GetType()===exports.b2ShapeType.e_circleShape){p1.SelfSub(body.GetLocalCenter());b2Rot.MulRV(body.m_xf0.q,p1,p1);b2Rot.MulTRV(body.m_xf.q,p1,p1);p1.SelfAdd(body.GetLocalCenter())}b2Transform.MulXV(body.m_xf,p1,input.p1)}else{input.p1.Copy(ap)}b2Vec2.AddVMulSV(ap,this.m_step.dt,av,input.p2);input.maxFraction=1;if(fixture.RayCast(output,input,childIndex)){const n=output.normal;const p=s_p;p.x=(1-output.fraction)*input.p1.x+output.fraction*input.p2.x+b2_linearSlop*n.x;p.y=(1-output.fraction)*input.p1.y+output.fraction*input.p2.y+b2_linearSlop*n.y;const v=s_v;v.x=this.m_step.inv_dt*(p.x-ap.x);v.y=this.m_step.inv_dt*(p.y-ap.y);this.m_system.m_velocityBuffer.data[a].Copy(v);const f=s_f;f.x=this.m_step.inv_dt*this.m_system.GetParticleMass()*(av.x-v.x);f.y=this.m_step.inv_dt*this.m_system.GetParticleMass()*(av.y-v.y);this.m_system.ParticleApplyForce(a,f)}}ReportParticle(system,index){return false}}SolveCollisionCallback.ReportFixtureAndParticle_s_p1=new b2Vec2;SolveCollisionCallback.ReportFixtureAndParticle_s_output=new b2RayCastOutput;SolveCollisionCallback.ReportFixtureAndParticle_s_input=new b2RayCastInput;SolveCollisionCallback.ReportFixtureAndParticle_s_p=new b2Vec2;SolveCollisionCallback.ReportFixtureAndParticle_s_v=new b2Vec2;SolveCollisionCallback.ReportFixtureAndParticle_s_f=new b2Vec2;b2ParticleSystem.SolveCollisionCallback=SolveCollisionCallback})(b2ParticleSystem||(b2ParticleSystem={}));class b2World{constructor(gravity){this.m_newFixture=false;this.m_locked=false;this.m_clearForces=true;this.m_contactManager=new b2ContactManager;this.m_bodyList=null;this.m_jointList=null;this.m_particleSystemList=null;this.m_bodyCount=0;this.m_jointCount=0;this.m_gravity=new b2Vec2;this.m_allowSleep=true;this.m_destructionListener=null;this.m_debugDraw=null;this.m_inv_dt0=0;this.m_warmStarting=true;this.m_continuousPhysics=true;this.m_subStepping=false;this.m_stepComplete=true;this.m_profile=new b2Profile;this.m_island=new b2Island;this.s_stack=[];this.m_controllerList=null;this.m_controllerCount=0;this.m_gravity.Copy(gravity)}SetDestructionListener(listener){this.m_destructionListener=listener}SetContactFilter(filter){this.m_contactManager.m_contactFilter=filter}SetContactListener(listener){this.m_contactManager.m_contactListener=listener}SetDebugDraw(debugDraw){this.m_debugDraw=debugDraw}CreateBody(def={}){if(this.IsLocked()){throw new Error}const b=new b2Body(def,this);b.m_prev=null;b.m_next=this.m_bodyList;if(this.m_bodyList){this.m_bodyList.m_prev=b}this.m_bodyList=b;++this.m_bodyCount;return b}DestroyBody(b){if(this.IsLocked()){throw new Error}let je=b.m_jointList;while(je){const je0=je;je=je.next;if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeJoint(je0.joint)}this.DestroyJoint(je0.joint);b.m_jointList=je}b.m_jointList=null;let coe=b.m_controllerList;while(coe){const coe0=coe;coe=coe.nextController;coe0.controller.RemoveBody(b)}let ce=b.m_contactList;while(ce){const ce0=ce;ce=ce.next;this.m_contactManager.Destroy(ce0.contact)}b.m_contactList=null;let f=b.m_fixtureList;while(f){const f0=f;f=f.m_next;if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeFixture(f0)}f0.DestroyProxies();f0.Destroy();b.m_fixtureList=f;b.m_fixtureCount-=1}b.m_fixtureList=null;b.m_fixtureCount=0;if(b.m_prev){b.m_prev.m_next=b.m_next}if(b.m_next){b.m_next.m_prev=b.m_prev}if(b===this.m_bodyList){this.m_bodyList=b.m_next}--this.m_bodyCount;b.Destroy()}CreateJoint(def){if(this.IsLocked()){throw new Error}const j=b2JointFactory.Create(def,null);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.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.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;const bodyA=def.bodyA;const bodyB=def.bodyB;if(!def.collideConnected){let edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){edge.contact.FlagForFiltering()}edge=edge.next}}return j}DestroyJoint(j){if(this.IsLocked()){throw new Error}const 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}const bodyA=j.m_bodyA;const 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;b2JointFactory.Destroy(j,null);--this.m_jointCount;if(!collideConnected){let edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){edge.contact.FlagForFiltering()}edge=edge.next}}}CreateParticleSystem(def){if(this.IsLocked()){throw new Error}const p=new b2ParticleSystem(def,this);p.m_prev=null;p.m_next=this.m_particleSystemList;if(this.m_particleSystemList){this.m_particleSystemList.m_prev=p}this.m_particleSystemList=p;return p}DestroyParticleSystem(p){if(this.IsLocked()){throw new Error}if(p.m_prev){p.m_prev.m_next=p.m_next}if(p.m_next){p.m_next.m_prev=p.m_prev}if(p===this.m_particleSystemList){this.m_particleSystemList=p.m_next}}CalculateReasonableParticleIterations(timeStep){if(this.m_particleSystemList===null){return 1}function GetSmallestRadius(world){let smallestRadius=b2_maxFloat;for(let system=world.GetParticleSystemList();system!==null;system=system.m_next){smallestRadius=b2Min(smallestRadius,system.GetRadius())}return smallestRadius}return b2CalculateParticleIterations(this.m_gravity.Length(),GetSmallestRadius(this),timeStep)}Step(dt,velocityIterations,positionIterations,particleIterations=this.CalculateReasonableParticleIterations(dt)){const stepTimer=b2World.Step_s_stepTimer.Reset();if(this.m_newFixture){this.m_contactManager.FindNewContacts();this.m_newFixture=false}this.m_locked=true;const step=b2World.Step_s_step;step.dt=dt;step.velocityIterations=velocityIterations;step.positionIterations=positionIterations;step.particleIterations=particleIterations;if(dt>0){step.inv_dt=1/dt}else{step.inv_dt=0}step.dtRatio=this.m_inv_dt0*dt;step.warmStarting=this.m_warmStarting;const timer=b2World.Step_s_timer.Reset();this.m_contactManager.Collide();this.m_profile.collide=timer.GetMilliseconds();if(this.m_stepComplete&&step.dt>0){const timer=b2World.Step_s_timer.Reset();for(let p=this.m_particleSystemList;p;p=p.m_next){p.Solve(step)}this.Solve(step);this.m_profile.solve=timer.GetMilliseconds()}if(this.m_continuousPhysics&&step.dt>0){const timer=b2World.Step_s_timer.Reset();this.SolveTOI(step);this.m_profile.solveTOI=timer.GetMilliseconds()}if(step.dt>0){this.m_inv_dt0=step.inv_dt}if(this.m_clearForces){this.ClearForces()}this.m_locked=false;this.m_profile.step=stepTimer.GetMilliseconds()}ClearForces(){for(let body=this.m_bodyList;body;body=body.m_next){body.m_force.SetZero();body.m_torque=0}}DrawParticleSystem(system){if(this.m_debugDraw===null){return}const particleCount=system.GetParticleCount();if(particleCount){const radius=system.GetRadius();const positionBuffer=system.GetPositionBuffer();if(system.m_colorBuffer.data){const colorBuffer=system.GetColorBuffer();this.m_debugDraw.DrawParticles(positionBuffer,radius,colorBuffer,particleCount)}else{this.m_debugDraw.DrawParticles(positionBuffer,radius,null,particleCount)}}}DrawDebugData(){if(this.m_debugDraw===null){return}const flags=this.m_debugDraw.GetFlags();const color=b2World.DrawDebugData_s_color.SetRGB(0,0,0);if(flags&exports.b2DrawFlags.e_shapeBit){for(let b=this.m_bodyList;b;b=b.m_next){const xf=b.m_xf;this.m_debugDraw.PushTransform(xf);for(let f=b.GetFixtureList();f;f=f.m_next){if(!b.IsActive()){color.SetRGB(0.5,0.5,0.3);this.DrawShape(f,color)}else if(b.GetType()===exports.b2BodyType.b2_staticBody){color.SetRGB(0.5,0.9,0.5);this.DrawShape(f,color)}else if(b.GetType()===exports.b2BodyType.b2_kinematicBody){color.SetRGB(0.5,0.5,0.9);this.DrawShape(f,color)}else if(!b.IsAwake()){color.SetRGB(0.6,0.6,0.6);this.DrawShape(f,color)}else{color.SetRGB(0.9,0.7,0.7);this.DrawShape(f,color)}}this.m_debugDraw.PopTransform(xf)}}if(flags&exports.b2DrawFlags.e_particleBit){for(let p=this.m_particleSystemList;p;p=p.m_next){this.DrawParticleSystem(p)}}if(flags&exports.b2DrawFlags.e_jointBit){for(let j=this.m_jointList;j;j=j.m_next){this.DrawJoint(j)}}if(flags&exports.b2DrawFlags.e_aabbBit){color.SetRGB(0.9,0.3,0.9);const vs=b2World.DrawDebugData_s_vs;for(let b=this.m_bodyList;b;b=b.m_next){if(!b.IsActive()){continue}for(let f=b.GetFixtureList();f;f=f.m_next){for(let i=0;i{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;if(callback){return callback.ReportFixture(fixture)}else if(fn){return fn(fixture)}return true});if(callback instanceof b2QueryCallback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryAABB(callback,aabb)}}}}QueryAllAABB(aabb,out=[]){this.QueryAABB(null,aabb,fixture=>{out.push(fixture);return true});return out}QueryPointAABB(callback,point,fn){this.m_contactManager.m_broadPhase.QueryPoint(point,proxy=>{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;if(callback){return callback.ReportFixture(fixture)}else if(fn){return fn(fixture)}return true});if(callback instanceof b2QueryCallback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryPointAABB(callback,point)}}}}QueryAllPointAABB(point,out=[]){this.QueryPointAABB(null,point,fixture=>{out.push(fixture);return true});return out}QueryFixtureShape(callback,shape,index,transform,fn){const aabb=b2World.QueryFixtureShape_s_aabb;shape.ComputeAABB(aabb,transform,index);this.m_contactManager.m_broadPhase.Query(aabb,proxy=>{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;if(b2TestOverlapShape(shape,index,fixture.GetShape(),fixture_proxy.childIndex,transform,fixture.GetBody().GetTransform())){if(callback){return callback.ReportFixture(fixture)}else if(fn){return fn(fixture)}}return true});if(callback instanceof b2QueryCallback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryAABB(callback,aabb)}}}}QueryAllFixtureShape(shape,index,transform,out=[]){this.QueryFixtureShape(null,shape,index,transform,fixture=>{out.push(fixture);return true});return out}QueryFixturePoint(callback,point,fn){this.m_contactManager.m_broadPhase.QueryPoint(point,proxy=>{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;if(fixture.TestPoint(point)){if(callback){return callback.ReportFixture(fixture)}else if(fn){return fn(fixture)}}return true});if(callback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryPointAABB(callback,point)}}}}QueryAllFixturePoint(point,out=[]){this.QueryFixturePoint(null,point,fixture=>{out.push(fixture);return true});return out}RayCast(callback,point1,point2,fn){const input=b2World.RayCast_s_input;input.maxFraction=1;input.p1.Copy(point1);input.p2.Copy(point2);this.m_contactManager.m_broadPhase.RayCast(input,(input,proxy)=>{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;const index=fixture_proxy.childIndex;const output=b2World.RayCast_s_output;const hit=fixture.RayCast(output,input,index);if(hit){const fraction=output.fraction;const point=b2World.RayCast_s_point;point.Set((1-fraction)*point1.x+fraction*point2.x,(1-fraction)*point1.y+fraction*point2.y);if(callback){return callback.ReportFixture(fixture,point,output.normal,fraction)}else if(fn){return fn(fixture,point,output.normal,fraction)}}return input.maxFraction});if(callback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.RayCast(callback,point1,point2)}}}}RayCastOne(point1,point2){let result=null;let min_fraction=1;this.RayCast(null,point1,point2,(fixture,point,normal,fraction)=>{if(fraction{out.push(fixture);return 1});return out}GetBodyList(){return this.m_bodyList}GetJointList(){return this.m_jointList}GetParticleSystemList(){return this.m_particleSystemList}GetContactList(){return this.m_contactManager.m_contactList}SetAllowSleeping(flag){if(flag===this.m_allowSleep){return}this.m_allowSleep=flag;if(!this.m_allowSleep){for(let b=this.m_bodyList;b;b=b.m_next){b.SetAwake(true)}}}GetAllowSleeping(){return this.m_allowSleep}SetWarmStarting(flag){this.m_warmStarting=flag}GetWarmStarting(){return this.m_warmStarting}SetContinuousPhysics(flag){this.m_continuousPhysics=flag}GetContinuousPhysics(){return this.m_continuousPhysics}SetSubStepping(flag){this.m_subStepping=flag}GetSubStepping(){return this.m_subStepping}GetProxyCount(){return this.m_contactManager.m_broadPhase.GetProxyCount()}GetBodyCount(){return this.m_bodyCount}GetJointCount(){return this.m_jointCount}GetContactCount(){return this.m_contactManager.m_contactCount}GetTreeHeight(){return this.m_contactManager.m_broadPhase.GetTreeHeight()}GetTreeBalance(){return this.m_contactManager.m_broadPhase.GetTreeBalance()}GetTreeQuality(){return this.m_contactManager.m_broadPhase.GetTreeQuality()}SetGravity(gravity,wake=true){if(!b2Vec2.IsEqualToV(this.m_gravity,gravity)){this.m_gravity.Copy(gravity);if(wake){for(let b=this.m_bodyList;b;b=b.m_next){b.SetAwake(true)}}}}GetGravity(){return this.m_gravity}IsLocked(){return this.m_locked}SetAutoClearForces(flag){this.m_clearForces=flag}GetAutoClearForces(){return this.m_clearForces}ShiftOrigin(newOrigin){if(this.IsLocked()){throw new Error}for(let b=this.m_bodyList;b;b=b.m_next){b.m_xf.p.SelfSub(newOrigin);b.m_sweep.c0.SelfSub(newOrigin);b.m_sweep.c.SelfSub(newOrigin)}for(let j=this.m_jointList;j;j=j.m_next){j.ShiftOrigin(newOrigin)}this.m_contactManager.m_broadPhase.ShiftOrigin(newOrigin)}GetContactManager(){return this.m_contactManager}GetProfile(){return this.m_profile}Dump(log){if(this.m_locked){return}log("const g: b2Vec2 = new b2Vec2(%.15f, %.15f);\n",this.m_gravity.x,this.m_gravity.y);log("this.m_world.SetGravity(g);\n");log("const bodies: b2Body[] = [];\n");log("const joints: b2Joint[] = [];\n");let i=0;for(let b=this.m_bodyList;b;b=b.m_next){b.m_islandIndex=i;b.Dump(log);++i}i=0;for(let j=this.m_jointList;j;j=j.m_next){j.m_index=i;++i}for(let j=this.m_jointList;j;j=j.m_next){if(j.m_type===exports.b2JointType.e_gearJoint){continue}log("{\n");j.Dump(log);log("}\n")}for(let j=this.m_jointList;j;j=j.m_next){if(j.m_type!==exports.b2JointType.e_gearJoint){continue}log("{\n");j.Dump(log);log("}\n")}}DrawJoint(joint){if(this.m_debugDraw===null){return}const bodyA=joint.GetBodyA();const bodyB=joint.GetBodyB();const xf1=bodyA.m_xf;const xf2=bodyB.m_xf;const x1=xf1.p;const x2=xf2.p;const p1=joint.GetAnchorA(b2World.DrawJoint_s_p1);const p2=joint.GetAnchorB(b2World.DrawJoint_s_p2);const color=b2World.DrawJoint_s_color.SetRGB(0.5,0.8,0.8);switch(joint.m_type){case exports.b2JointType.e_distanceJoint:this.m_debugDraw.DrawSegment(p1,p2,color);break;case exports.b2JointType.e_pulleyJoint:{const pulley=joint;const s1=pulley.GetGroundAnchorA();const s2=pulley.GetGroundAnchorB();this.m_debugDraw.DrawSegment(s1,p1,color);this.m_debugDraw.DrawSegment(s2,p2,color);this.m_debugDraw.DrawSegment(s1,s2,color)}break;case exports.b2JointType.e_mouseJoint:this.m_debugDraw.DrawSegment(p1,p2,color);break;default:this.m_debugDraw.DrawSegment(x1,p1,color);this.m_debugDraw.DrawSegment(p1,p2,color);this.m_debugDraw.DrawSegment(x2,p2,color);}}DrawShape(fixture,color){if(this.m_debugDraw===null){return}const shape=fixture.GetShape();switch(shape.m_type){case exports.b2ShapeType.e_circleShape:{const circle=shape;const center=circle.m_p;const radius=circle.m_radius;const axis=b2Vec2.UNITX;this.m_debugDraw.DrawSolidCircle(center,radius,axis,color)}break;case exports.b2ShapeType.e_edgeShape:{const edge=shape;const v1=edge.m_vertex1;const v2=edge.m_vertex2;this.m_debugDraw.DrawSegment(v1,v2,color)}break;case exports.b2ShapeType.e_chainShape:{const chain=shape;const count=chain.m_count;const vertices=chain.m_vertices;let v1=vertices[0];this.m_debugDraw.DrawCircle(v1,0.05,color);for(let i=1;i0){const b=stack[--stackCount];if(!b){throw new Error}island.AddBody(b);b.SetAwake(true);if(b.GetType()===exports.b2BodyType.b2_staticBody){continue}for(let ce=b.m_contactList;ce;ce=ce.next){const contact=ce.contact;if(contact.m_islandFlag){continue}if(!contact.IsEnabled()||!contact.IsTouching()){continue}const sensorA=contact.m_fixtureA.m_isSensor;const sensorB=contact.m_fixtureB.m_isSensor;if(sensorA||sensorB){continue}island.AddContact(contact);contact.m_islandFlag=true;const other=ce.other;if(!other){throw new Error}if(other.m_islandFlag){continue}stack[stackCount++]=other;other.m_islandFlag=true}for(let je=b.m_jointList;je;je=je.next){if(je.joint.m_islandFlag){continue}const other=je.other;if(!other.IsActive()){continue}island.AddJoint(je.joint);je.joint.m_islandFlag=true;if(other.m_islandFlag){continue}stack[stackCount++]=other;other.m_islandFlag=true}}const profile=new b2Profile;island.Solve(profile,step,this.m_gravity,this.m_allowSleep);this.m_profile.solveInit+=profile.solveInit;this.m_profile.solveVelocity+=profile.solveVelocity;this.m_profile.solvePosition+=profile.solvePosition;for(let i=0;ib2_maxSubSteps){continue}let alpha=1;if(c.m_toiFlag){alpha=c.m_toi}else{const fA=c.GetFixtureA();const fB=c.GetFixtureB();if(fA.IsSensor()||fB.IsSensor()){continue}const bA=fA.GetBody();const bB=fB.GetBody();const typeA=bA.m_type;const typeB=bB.m_type;const activeA=bA.IsAwake()&&typeA!==exports.b2BodyType.b2_staticBody;const activeB=bB.IsAwake()&&typeB!==exports.b2BodyType.b2_staticBody;if(!activeA&&!activeB){continue}const collideA=bA.IsBullet()||typeA!==exports.b2BodyType.b2_dynamicBody;const collideB=bB.IsBullet()||typeB!==exports.b2BodyType.b2_dynamicBody;if(!collideA&&!collideB){continue}let alpha0=bA.m_sweep.alpha0;if(bA.m_sweep.alpha0this.maxTimestep&&this.maxTimestep>0){timestep=this.maxTimestep}for(let i=this.m_bodyList;i;i=i.nextBody){const body=i.body;if(!body.IsAwake()){continue}const damping=body.GetWorldVector(b2Mat22.MulMV(this.T,body.GetLocalVector(body.GetLinearVelocity(),b2Vec2.s_t0),b2Vec2.s_t1),b2TensorDampingController.Step_s_damping);body.SetLinearVelocity(b2Vec2.AddVV(body.GetLinearVelocity(),b2Vec2.MulSV(timestep,damping,b2Vec2.s_t0),b2Vec2.s_t1))}}Draw(draw){}SetAxisAligned(xDamping,yDamping){this.T.ex.x=-xDamping;this.T.ex.y=0;this.T.ey.x=0;this.T.ey.y=-yDamping;if(xDamping>0||yDamping>0){this.maxTimestep=1/b2Max(xDamping,yDamping)}else{this.maxTimestep=0}}}b2TensorDampingController.Step_s_damping=new b2Vec2;class b2RopeDef{constructor(){this.vertices=[];this.count=0;this.masses=[];this.gravity=new b2Vec2(0,0);this.damping=0.1;this.k2=0.9;this.k3=0.1}}class b2Rope{constructor(){this.m_count=0;this.m_ps=[];this.m_p0s=[];this.m_vs=[];this.m_ims=[];this.m_Ls=[];this.m_as=[];this.m_gravity=new b2Vec2;this.m_damping=0;this.m_k2=1;this.m_k3=0.1}GetVertexCount(){return this.m_count}GetVertices(){return this.m_ps}Initialize(def){this.m_count=def.count;this.m_ps=b2Vec2.MakeArray(this.m_count);this.m_p0s=b2Vec2.MakeArray(this.m_count);this.m_vs=b2Vec2.MakeArray(this.m_count);this.m_ims=b2MakeNumberArray(this.m_count);for(let i=0;i0){this.m_ims[i]=1/m}else{this.m_ims[i]=0}}const count2=this.m_count-1;const count3=this.m_count-2;this.m_Ls=b2MakeNumberArray(count2);this.m_as=b2MakeNumberArray(count3);for(let i=0;i0){this.m_vs[i].SelfMulAdd(h,this.m_gravity)}this.m_vs[i].SelfMul(d);this.m_ps[i].SelfMulAdd(h,this.m_vs[i])}for(let i=0;ib2_pi){angle-=2*b2_pi;C=angle-this.m_as[i]}while(C<-b2_pi){angle+=2*b2_pi;C=angle-this.m_as[i]}const impulse=-this.m_k3*mass*C;p1.SelfMulAdd(m1*impulse,J1);p2.SelfMulAdd(m2*impulse,J2);p3.SelfMulAdd(m3*impulse,J3)}}Draw(draw){const c=new b2Color(0.4,0.5,0.7);for(let i=0;iprevTime+1000){fpsPanel.update(frames*1000/(time-prevTime),100);prevTime=time;frames=0;if(memPanel){var memory=performance.memory;memPanel.update(memory.usedJSHeapSize/1048576,memory.jsHeapSizeLimit/1048576)}}return time},update:function(){beginTime=this.end()},domElement:container,setMode:showPanel}};Stats.Panel=function(name,fg,bg){var min=Infinity,max=0,round=Math.round;var PR=round(window.devicePixelRatio||1);var WIDTH=80*PR,HEIGHT=48*PR,TEXT_X=3*PR,TEXT_Y=2*PR,GRAPH_X=3*PR,GRAPH_Y=15*PR,GRAPH_WIDTH=74*PR,GRAPH_HEIGHT=30*PR;var canvas=document.createElement("canvas");canvas.width=WIDTH;canvas.height=HEIGHT;canvas.style.cssText="width:80px;height:48px";var context=canvas.getContext("2d");context.font="bold "+9*PR+"px Helvetica,Arial,sans-serif";context.textBaseline="top";context.fillStyle=bg;context.fillRect(0,0,WIDTH,HEIGHT);context.fillStyle=fg;context.fillText(name,TEXT_X,TEXT_Y);context.fillRect(GRAPH_X,GRAPH_Y,GRAPH_WIDTH,GRAPH_HEIGHT);context.fillStyle=bg;context.globalAlpha=0.9;context.fillRect(GRAPH_X,GRAPH_Y,GRAPH_WIDTH,GRAPH_HEIGHT);return{dom:canvas,update:function(value,maxValue){min=Math.min(min,value);max=Math.max(max,value);context.fillStyle=bg;context.globalAlpha=1;context.fillRect(0,0,WIDTH,GRAPH_Y);context.fillStyle=fg;context.fillText(round(value)+" "+name+" ("+round(min)+"-"+round(max)+")",TEXT_X,TEXT_Y);context.drawImage(canvas,GRAPH_X+PR,GRAPH_Y,GRAPH_WIDTH-PR,GRAPH_HEIGHT,GRAPH_X,GRAPH_Y,GRAPH_WIDTH-PR,GRAPH_HEIGHT);context.fillRect(GRAPH_X+GRAPH_WIDTH-PR,GRAPH_Y,PR,GRAPH_HEIGHT);context.fillStyle=bg;context.globalAlpha=0.9;context.fillRect(GRAPH_X+GRAPH_WIDTH-PR,GRAPH_Y,PR,round((1-value/maxValue)*GRAPH_HEIGHT))}}};return Stats});!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.dat=t()}(this,function(){"use strict";function e(e,t){var n=e.__state.conversionName.toString(),o=Math.round(e.r),i=Math.round(e.g),r=Math.round(e.b),s=e.a,a=Math.round(e.h),l=e.s.toFixed(1),d=e.v.toFixed(1);if(t||"THREE_CHAR_HEX"===n||"SIX_CHAR_HEX"===n){for(var c=e.hex.toString(16);c.length<6;)c="0"+c;return"#"+c}return"CSS_RGB"===n?"rgb("+o+","+i+","+r+")":"CSS_RGBA"===n?"rgba("+o+","+i+","+r+","+s+")":"HEX"===n?"0x"+e.hex.toString(16):"RGB_ARRAY"===n?"["+o+","+i+","+r+"]":"RGBA_ARRAY"===n?"["+o+","+i+","+r+","+s+"]":"RGB_OBJ"===n?"{r:"+o+",g:"+i+",b:"+r+"}":"RGBA_OBJ"===n?"{r:"+o+",g:"+i+",b:"+r+",a:"+s+"}":"HSV_OBJ"===n?"{h:"+a+",s:"+l+",v:"+d+"}":"HSVA_OBJ"===n?"{h:"+a+",s:"+l+",v:"+d+",a:"+s+"}":"unknown format"}function t(e,t,n){Object.defineProperty(e,t,{get:function(){return"RGB"===this.__state.space?this.__state[t]:(V.recalculateRGB(this,t,n),this.__state[t])},set:function(e){"RGB"!==this.__state.space&&(V.recalculateRGB(this,t,n),this.__state.space="RGB"),this.__state[t]=e}})}function n(e,t){Object.defineProperty(e,t,{get:function(){return"HSV"===this.__state.space?this.__state[t]:(V.recalculateHSV(this),this.__state[t])},set:function(e){"HSV"!==this.__state.space&&(V.recalculateHSV(this),this.__state.space="HSV"),this.__state[t]=e}})}function o(e){if("0"===e||k.isUndefined(e))return 0;var t=e.match(G);return k.isNull(t)?0:parseFloat(t[1])}function i(e){var t=e.toString();return t.indexOf(".")>-1?t.length-t.indexOf(".")-1:0}function r(e,t){var n=Math.pow(10,t);return Math.round(e*n)/n}function s(e,t,n,o,i){return o+(e-t)/(n-t)*(i-o)}function a(e,t,n,o){e.style.background="",k.each($,function(i){e.style.cssText+="background: "+i+"linear-gradient("+t+", "+n+" 0%, "+o+" 100%); "})}function l(e){e.style.background="",e.style.cssText+="background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);",e.style.cssText+="background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",e.style.cssText+="background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",e.style.cssText+="background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",e.style.cssText+="background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);"}function d(e,t,n){var o=document.createElement("li");return t&&o.appendChild(t),n?e.__ul.insertBefore(o,n):e.__ul.appendChild(o),e.onResize(),o}function c(e){U.unbind(window,"resize",e.__resizeHandler),e.saveToLocalStorageIfPossible&&U.unbind(window,"unload",e.saveToLocalStorageIfPossible)}function u(e,t){var n=e.__preset_select[e.__preset_select.selectedIndex];n.innerHTML=t?n.value+"*":n.value}function _(e,t,n){if(n.__li=t,n.__gui=e,k.extend(n,{options:function(t){if(arguments.length>1){var o=n.__li.nextElementSibling;return n.remove(),p(e,n.object,n.property,{before:o,factoryArgs:[k.toArray(arguments)]})}if(k.isArray(t)||k.isObject(t)){var i=n.__li.nextElementSibling;return n.remove(),p(e,n.object,n.property,{before:i,factoryArgs:[t]})}},name:function(e){return n.__li.firstElementChild.firstElementChild.innerHTML=e,n},listen:function(){return n.__gui.listen(n),n},remove:function(){return n.__gui.remove(n),n}}),n instanceof Q){var o=new W(n.object,n.property,{min:n.__min,max:n.__max,step:n.__step});k.each(["updateDisplay","onChange","onFinishChange","step"],function(e){var t=n[e],i=o[e];n[e]=o[e]=function(){var e=Array.prototype.slice.call(arguments);return i.apply(o,e),t.apply(n,e)}}),U.addClass(t,"has-slider"),n.domElement.insertBefore(o.domElement,n.domElement.firstElementChild)}else if(n instanceof W){var i=function(t){if(k.isNumber(n.__min)&&k.isNumber(n.__max)){var o=n.__li.firstElementChild.firstElementChild.innerHTML,i=n.__gui.__listening.indexOf(n)>-1;n.remove();var r=p(e,n.object,n.property,{before:n.__li.nextElementSibling,factoryArgs:[n.__min,n.__max,n.__step]});return r.name(o),i&&r.listen(),r}return t};n.min=k.compose(i,n.min),n.max=k.compose(i,n.max)}else n instanceof X?(U.bind(t,"click",function(){U.fakeEvent(n.__checkbox,"click")}),U.bind(n.__checkbox,"click",function(e){e.stopPropagation()})):n instanceof q?(U.bind(t,"click",function(){U.fakeEvent(n.__button,"click")}),U.bind(t,"mouseover",function(){U.addClass(n.__button,"hover")}),U.bind(t,"mouseout",function(){U.removeClass(n.__button,"hover")})):n instanceof Z&&(U.addClass(t,"color"),n.updateDisplay=k.compose(function(e){return t.style.borderLeftColor=n.__color.toString(),e},n.updateDisplay),n.updateDisplay());n.setValue=k.compose(function(t){return e.getRoot().__preset_select&&n.isModified()&&u(e.getRoot(),!0),t},n.setValue)}function h(e,t){var n=e.getRoot(),o=n.__rememberedObjects.indexOf(t.object);if(-1!==o){var i=n.__rememberedObjectIndecesToControllers[o];if(void 0===i&&(i={},n.__rememberedObjectIndecesToControllers[o]=i),i[t.property]=t,n.load&&n.load.remembered){var r=n.load.remembered,s=void 0;if(r[e.preset])s=r[e.preset];else{if(!r[re])return;s=r[re]}if(s[o]&&void 0!==s[o][t.property]){var a=s[o][t.property];t.initialValue=a,t.setValue(a)}}}}function p(e,t,n,o){if(void 0===t[n])throw new Error("Object \""+t+"\" has no property \""+n+"\"");var i=void 0;if(o.color)i=new Z(t,n);else{var r=[t,n].concat(o.factoryArgs);i=te.apply(e,r)}o.before instanceof I&&(o.before=o.before.__li),h(e,i),U.addClass(i.domElement,"c");var s=document.createElement("span");U.addClass(s,"property-name"),s.innerHTML=i.property;var a=document.createElement("div");a.appendChild(s),a.appendChild(i.domElement);var l=d(e,a,o.before);return U.addClass(l,_e.CLASS_CONTROLLER_ROW),i instanceof Z?U.addClass(l,"color"):U.addClass(l,N(i.getValue())),_(e,l,i),e.__controllers.push(i),i}function f(e,t){return document.location.href+"."+t}function m(e,t,n){var o=document.createElement("option");o.innerHTML=t,o.value=t,e.__preset_select.appendChild(o),n&&(e.__preset_select.selectedIndex=e.__preset_select.length-1)}function g(e,t){t.style.display=e.useLocalStorage?"block":"none"}function b(e){var t=e.__save_row=document.createElement("li");U.addClass(e.domElement,"has-save"),e.__ul.insertBefore(t,e.__ul.firstChild),U.addClass(t,"save-row");var n=document.createElement("span");n.innerHTML=" ",U.addClass(n,"button gears");var o=document.createElement("span");o.innerHTML="Save",U.addClass(o,"button"),U.addClass(o,"save");var i=document.createElement("span");i.innerHTML="New",U.addClass(i,"button"),U.addClass(i,"save-as");var r=document.createElement("span");r.innerHTML="Revert",U.addClass(r,"button"),U.addClass(r,"revert");var s=e.__preset_select=document.createElement("select");if(e.load&&e.load.remembered?k.each(e.load.remembered,function(t,n){m(e,n,n===e.preset)}):m(e,re,!1),U.bind(s,"change",function(){for(var t=0;t=0;n--)t=[e[n].apply(this,t)];return t[0]}},each:function(e,t,n){if(e)if(C&&e.forEach&&e.forEach===C)e.forEach(t,n);else if(e.length===e.length+0){var o=void 0,i=void 0;for(o=0,i=e.length;o1?k.toArray(arguments):arguments[0];return k.each(S,function(t){if(t.litmus(e))return k.each(t.conversions,function(t,n){if(O=t.read(e),!1===T&&!1!==O)return T=O,O.conversionName=n,O.conversion=t,k.BREAK}),k.BREAK}),T},L=void 0,B={hsv_to_rgb:function(e,t,n){var o=Math.floor(e/60)%6,i=e/60-Math.floor(e/60),r=n*(1-t),s=n*(1-i*t),a=n*(1-(1-i)*t),l=[[n,a,r],[s,n,r],[r,n,a],[r,s,n],[a,r,n],[n,r,s]][o];return{r:255*l[0],g:255*l[1],b:255*l[2]}},rgb_to_hsv:function(e,t,n){var o=Math.min(e,t,n),i=Math.max(e,t,n),r=i-o,s=void 0,a=void 0;return 0===i?{h:NaN,s:0,v:0}:(a=r/i,s=e===i?(t-n)/r:t===i?2+(n-e)/r:4+(e-t)/r,(s/=6)<0&&(s+=1),{h:360*s,s:a,v:i/255})},rgb_to_hex:function(e,t,n){var o=this.hex_with_component(0,2,e);return o=this.hex_with_component(o,1,t),o=this.hex_with_component(o,0,n)},component_from_hex:function(e,t){return e>>8*t&255},hex_with_component:function(e,t,n){return n<<(L=8*t)|e&~(255<this.__max&&(n=this.__max),void 0!==this.__step&&n%this.__step!=0&&(n=Math.round(n/this.__step)*this.__step),P(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"setValue",this).call(this,n)}},{key:"min",value:function(e){return this.__min=e,this}},{key:"max",value:function(e){return this.__max=e,this}},{key:"step",value:function(e){return this.__step=e,this.__impliedStep=e,this.__precision=i(e),this}}]),t}(),W=function(e){function t(e,n,o){function i(){l.__onFinishChange&&l.__onFinishChange.call(l,l.getValue())}function r(e){var t=d-e.clientY;l.setValue(l.getValue()+t*l.__impliedStep),d=e.clientY}function s(){U.unbind(window,"mousemove",r),U.unbind(window,"mouseup",s),i()}H(this,t);var a=D(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n,o));a.__truncationSuspended=!1;var l=a,d=void 0;return a.__input=document.createElement("input"),a.__input.setAttribute("type","text"),U.bind(a.__input,"change",function(){var e=parseFloat(l.__input.value);k.isNaN(e)||l.setValue(e)}),U.bind(a.__input,"blur",function(){i()}),U.bind(a.__input,"mousedown",function(e){U.bind(window,"mousemove",r),U.bind(window,"mouseup",s),d=e.clientY}),U.bind(a.__input,"keydown",function(e){13===e.keyCode&&(l.__truncationSuspended=!0,this.blur(),l.__truncationSuspended=!1,i())}),a.updateDisplay(),a.domElement.appendChild(a.__input),a}return j(t,J),F(t,[{key:"updateDisplay",value:function(){return this.__input.value=this.__truncationSuspended?this.getValue():r(this.getValue(),this.__precision),P(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"updateDisplay",this).call(this)}}]),t}(),Q=function(e){function t(e,n,o,i,r){function a(e){e.preventDefault();var t=_.__background.getBoundingClientRect();return _.setValue(s(e.clientX,t.left,t.right,_.__min,_.__max)),!1}function l(){U.unbind(window,"mousemove",a),U.unbind(window,"mouseup",l),_.__onFinishChange&&_.__onFinishChange.call(_,_.getValue())}function d(e){var t=e.touches[0].clientX,n=_.__background.getBoundingClientRect();_.setValue(s(t,n.left,n.right,_.__min,_.__max))}function c(){U.unbind(window,"touchmove",d),U.unbind(window,"touchend",c),_.__onFinishChange&&_.__onFinishChange.call(_,_.getValue())}H(this,t);var u=D(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n,{min:o,max:i,step:r})),_=u;return u.__background=document.createElement("div"),u.__foreground=document.createElement("div"),U.bind(u.__background,"mousedown",function(e){document.activeElement.blur(),U.bind(window,"mousemove",a),U.bind(window,"mouseup",l),a(e)}),U.bind(u.__background,"touchstart",function(e){1===e.touches.length&&(U.bind(window,"touchmove",d),U.bind(window,"touchend",c),d(e))}),U.addClass(u.__background,"slider"),U.addClass(u.__foreground,"slider-fg"),u.updateDisplay(),u.__background.appendChild(u.__foreground),u.domElement.appendChild(u.__background),u}return j(t,J),F(t,[{key:"updateDisplay",value:function(){var e=(this.getValue()-this.__min)/(this.__max-this.__min);return this.__foreground.style.width=100*e+"%",P(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"updateDisplay",this).call(this)}}]),t}(),q=function(e){function t(e,n,o){H(this,t);var i=D(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),r=i;return i.__button=document.createElement("div"),i.__button.innerHTML=void 0===o?"Fire":o,U.bind(i.__button,"click",function(e){return e.preventDefault(),r.fire(),!1}),U.addClass(i.__button,"button"),i.domElement.appendChild(i.__button),i}return j(t,I),F(t,[{key:"fire",value:function(){this.__onChange&&this.__onChange.call(this),this.getValue().call(this.object),this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue())}}]),t}(),Z=function(e){function t(e,n){function o(e){u(e),U.bind(window,"mousemove",u),U.bind(window,"touchmove",u),U.bind(window,"mouseup",r),U.bind(window,"touchend",r)}function i(e){_(e),U.bind(window,"mousemove",_),U.bind(window,"touchmove",_),U.bind(window,"mouseup",s),U.bind(window,"touchend",s)}function r(){U.unbind(window,"mousemove",u),U.unbind(window,"touchmove",u),U.unbind(window,"mouseup",r),U.unbind(window,"touchend",r),c()}function s(){U.unbind(window,"mousemove",_),U.unbind(window,"touchmove",_),U.unbind(window,"mouseup",s),U.unbind(window,"touchend",s),c()}function d(){var e=R(this.value);!1!==e?(p.__color.__state=e,p.setValue(p.__color.toOriginal())):this.value=p.__color.toString()}function c(){p.__onFinishChange&&p.__onFinishChange.call(p,p.__color.toOriginal())}function u(e){-1===e.type.indexOf("touch")&&e.preventDefault();var t=p.__saturation_field.getBoundingClientRect(),n=e.touches&&e.touches[0]||e,o=n.clientX,i=n.clientY,r=(o-t.left)/(t.right-t.left),s=1-(i-t.top)/(t.bottom-t.top);return s>1?s=1:s<0&&(s=0),r>1?r=1:r<0&&(r=0),p.__color.v=s,p.__color.s=r,p.setValue(p.__color.toOriginal()),!1}function _(e){-1===e.type.indexOf("touch")&&e.preventDefault();var t=p.__hue_field.getBoundingClientRect(),n=1-((e.touches&&e.touches[0]||e).clientY-t.top)/(t.bottom-t.top);return n>1?n=1:n<0&&(n=0),p.__color.h=360*n,p.setValue(p.__color.toOriginal()),!1}H(this,t);var h=D(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));h.__color=new V(h.getValue()),h.__temp=new V(0);var p=h;h.domElement=document.createElement("div"),U.makeSelectable(h.domElement,!1),h.__selector=document.createElement("div"),h.__selector.className="selector",h.__saturation_field=document.createElement("div"),h.__saturation_field.className="saturation-field",h.__field_knob=document.createElement("div"),h.__field_knob.className="field-knob",h.__field_knob_border="2px solid ",h.__hue_knob=document.createElement("div"),h.__hue_knob.className="hue-knob",h.__hue_field=document.createElement("div"),h.__hue_field.className="hue-field",h.__input=document.createElement("input"),h.__input.type="text",h.__input_textShadow="0 1px 1px ",U.bind(h.__input,"keydown",function(e){13===e.keyCode&&d.call(this)}),U.bind(h.__input,"blur",d),U.bind(h.__selector,"mousedown",function(){U.addClass(this,"drag").bind(window,"mouseup",function(){U.removeClass(p.__selector,"drag")})}),U.bind(h.__selector,"touchstart",function(){U.addClass(this,"drag").bind(window,"touchend",function(){U.removeClass(p.__selector,"drag")})});var f=document.createElement("div");return k.extend(h.__selector.style,{width:"122px",height:"102px",padding:"3px",backgroundColor:"#222",boxShadow:"0px 1px 3px rgba(0,0,0,0.3)"}),k.extend(h.__field_knob.style,{position:"absolute",width:"12px",height:"12px",border:h.__field_knob_border+(h.__color.v<.5?"#fff":"#000"),boxShadow:"0px 1px 3px rgba(0,0,0,0.5)",borderRadius:"12px",zIndex:1}),k.extend(h.__hue_knob.style,{position:"absolute",width:"15px",height:"2px",borderRight:"4px solid #fff",zIndex:1}),k.extend(h.__saturation_field.style,{width:"100px",height:"100px",border:"1px solid #555",marginRight:"3px",display:"inline-block",cursor:"pointer"}),k.extend(f.style,{width:"100%",height:"100%",background:"none"}),a(f,"top","rgba(0,0,0,0)","#000"),k.extend(h.__hue_field.style,{width:"15px",height:"100px",border:"1px solid #555",cursor:"ns-resize",position:"absolute",top:"3px",right:"3px"}),l(h.__hue_field),k.extend(h.__input.style,{outline:"none",textAlign:"center",color:"#fff",border:0,fontWeight:"bold",textShadow:h.__input_textShadow+"rgba(0,0,0,0.7)"}),U.bind(h.__saturation_field,"mousedown",o),U.bind(h.__saturation_field,"touchstart",o),U.bind(h.__field_knob,"mousedown",o),U.bind(h.__field_knob,"touchstart",o),U.bind(h.__hue_field,"mousedown",i),U.bind(h.__hue_field,"touchstart",i),h.__saturation_field.appendChild(f),h.__selector.appendChild(h.__field_knob),h.__selector.appendChild(h.__saturation_field),h.__selector.appendChild(h.__hue_field),h.__hue_field.appendChild(h.__hue_knob),h.domElement.appendChild(h.__input),h.domElement.appendChild(h.__selector),h.updateDisplay(),h}return j(t,I),F(t,[{key:"updateDisplay",value:function(){var e=R(this.getValue());if(!1!==e){var t=!1;k.each(V.COMPONENTS,function(n){if(!k.isUndefined(e[n])&&!k.isUndefined(this.__color.__state[n])&&e[n]!==this.__color.__state[n])return t=!0,{}},this),t&&k.extend(this.__color.__state,e)}k.extend(this.__temp.__state,this.__color.__state),this.__temp.a=1;var n=this.__color.v<.5||this.__color.s>.5?255:0,o=255-n;k.extend(this.__field_knob.style,{marginLeft:100*this.__color.s-7+"px",marginTop:100*(1-this.__color.v)-7+"px",backgroundColor:this.__temp.toHexString(),border:this.__field_knob_border+"rgb("+n+","+n+","+n+")"}),this.__hue_knob.style.marginTop=100*(1-this.__color.h/360)+"px",this.__temp.s=1,this.__temp.v=1,a(this.__saturation_field,"left","#fff",this.__temp.toHexString()),this.__input.value=this.__color.toString(),k.extend(this.__input.style,{backgroundColor:this.__color.toHexString(),color:"rgb("+n+","+n+","+n+")",textShadow:this.__input_textShadow+"rgba("+o+","+o+","+o+",.7)"})}}]),t}(),$=["-moz-","-o-","-webkit-","-ms-",""],ee={load:function(e,t){var n=t||document,o=n.createElement("link");o.type="text/css",o.rel="stylesheet",o.href=e,n.getElementsByTagName("head")[0].appendChild(o)},inject:function(e,t){var n=t||document,o=document.createElement("style");o.type="text/css",o.innerHTML=e;var i=n.getElementsByTagName("head")[0];try{i.appendChild(o)}catch(e){}}},te=function(e,t){var n=e[t];return k.isArray(arguments[2])||k.isObject(arguments[2])?new K(e,t,arguments[2]):k.isNumber(n)?k.isNumber(arguments[2])&&k.isNumber(arguments[3])?k.isNumber(arguments[4])?new Q(e,t,arguments[2],arguments[3],arguments[4]):new Q(e,t,arguments[2],arguments[3]):k.isNumber(arguments[4])?new W(e,t,{min:arguments[2],max:arguments[3],step:arguments[4]}):new W(e,t,{min:arguments[2],max:arguments[3]}):k.isString(n)?new Y(e,t):k.isFunction(n)?new q(e,t,""):k.isBoolean(n)?new X(e,t):null},ne=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)},oe=function(){function e(){H(this,e),this.backgroundElement=document.createElement("div"),k.extend(this.backgroundElement.style,{backgroundColor:"rgba(0,0,0,0.8)",top:0,left:0,display:"none",zIndex:"1000",opacity:0,WebkitTransition:"opacity 0.2s linear",transition:"opacity 0.2s linear"}),U.makeFullscreen(this.backgroundElement),this.backgroundElement.style.position="fixed",this.domElement=document.createElement("div"),k.extend(this.domElement.style,{position:"fixed",display:"none",zIndex:"1001",opacity:0,WebkitTransition:"-webkit-transform 0.2s ease-out, opacity 0.2s linear",transition:"transform 0.2s ease-out, opacity 0.2s linear"}),document.body.appendChild(this.backgroundElement),document.body.appendChild(this.domElement);var t=this;U.bind(this.backgroundElement,"click",function(){t.hide()})}return F(e,[{key:"show",value:function(){var e=this;this.backgroundElement.style.display="block",this.domElement.style.display="block",this.domElement.style.opacity=0,this.domElement.style.webkitTransform="scale(1.1)",this.layout(),k.defer(function(){e.backgroundElement.style.opacity=1,e.domElement.style.opacity=1,e.domElement.style.webkitTransform="scale(1)"})}},{key:"hide",value:function(){var e=this,t=function t(){e.domElement.style.display="none",e.backgroundElement.style.display="none",U.unbind(e.domElement,"webkitTransitionEnd",t),U.unbind(e.domElement,"transitionend",t),U.unbind(e.domElement,"oTransitionEnd",t)};U.bind(this.domElement,"webkitTransitionEnd",t),U.bind(this.domElement,"transitionend",t),U.bind(this.domElement,"oTransitionEnd",t),this.backgroundElement.style.opacity=0,this.domElement.style.opacity=0,this.domElement.style.webkitTransform="scale(1.1)"}},{key:"layout",value:function(){this.domElement.style.left=window.innerWidth/2-U.getWidth(this.domElement)/2+"px",this.domElement.style.top=window.innerHeight/2-U.getHeight(this.domElement)/2+"px"}}]),e}(),ie=function(e){if(e&&"undefined"!=typeof window){var t=document.createElement("style");return t.setAttribute("type","text/css"),t.innerHTML=e,document.head.appendChild(t),e}}(".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid transparent}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n");ee.inject(ie);var re="Default",se=function(){try{return"localStorage"in window&&null!==window.localStorage}catch(e){return!1}}(),ae=void 0,le=!0,de=void 0,ce=!1,ue=[],_e=function e(t){var n=this,o=t||{};this.domElement=document.createElement("div"),this.__ul=document.createElement("ul"),this.domElement.appendChild(this.__ul),U.addClass(this.domElement,"dg"),this.__folders={},this.__controllers=[],this.__rememberedObjects=[],this.__rememberedObjectIndecesToControllers=[],this.__listening=[],o=k.defaults(o,{closeOnTop:!1,autoPlace:!0,width:e.DEFAULT_WIDTH}),o=k.defaults(o,{resizable:o.autoPlace,hideable:o.autoPlace}),k.isUndefined(o.load)?o.load={preset:re}:o.preset&&(o.load.preset=o.preset),k.isUndefined(o.parent)&&o.hideable&&ue.push(this),o.resizable=k.isUndefined(o.parent)&&o.resizable,o.autoPlace&&k.isUndefined(o.scrollable)&&(o.scrollable=!0);var i=se&&"true"===localStorage.getItem(f(this,"isLocal")),r=void 0;if(Object.defineProperties(this,{parent:{get:function(){return o.parent}},scrollable:{get:function(){return o.scrollable}},autoPlace:{get:function(){return o.autoPlace}},closeOnTop:{get:function(){return o.closeOnTop}},preset:{get:function(){return n.parent?n.getRoot().preset:o.load.preset},set:function(e){n.parent?n.getRoot().preset=e:o.load.preset=e,x(this),n.revert()}},width:{get:function(){return o.width},set:function(e){o.width=e,y(n,e)}},name:{get:function(){return o.name},set:function(e){o.name=e,titleRowName&&(titleRowName.innerHTML=o.name)}},closed:{get:function(){return o.closed},set:function(t){o.closed=t,o.closed?U.addClass(n.__ul,e.CLASS_CLOSED):U.removeClass(n.__ul,e.CLASS_CLOSED),this.onResize(),n.__closeButton&&(n.__closeButton.innerHTML=t?e.TEXT_OPEN:e.TEXT_CLOSED)}},load:{get:function(){return o.load}},useLocalStorage:{get:function(){return i},set:function(e){se&&(i=e,e?U.bind(window,"unload",r):U.unbind(window,"unload",r),localStorage.setItem(f(n,"isLocal"),e))}}}),k.isUndefined(o.parent)){if(o.closed=!1,U.addClass(this.domElement,e.CLASS_MAIN),U.makeSelectable(this.domElement,!1),se&&i){n.useLocalStorage=!0;var s=localStorage.getItem(f(this,"gui"));s&&(o.load=JSON.parse(s))}this.__closeButton=document.createElement("div"),this.__closeButton.innerHTML=e.TEXT_CLOSED,U.addClass(this.__closeButton,e.CLASS_CLOSE_BUTTON),o.closeOnTop?(U.addClass(this.__closeButton,e.CLASS_CLOSE_TOP),this.domElement.insertBefore(this.__closeButton,this.domElement.childNodes[0])):(U.addClass(this.__closeButton,e.CLASS_CLOSE_BOTTOM),this.domElement.appendChild(this.__closeButton)),U.bind(this.__closeButton,"click",function(){n.closed=!n.closed})}else{void 0===o.closed&&(o.closed=!0);var a=document.createTextNode(o.name);U.addClass(a,"controller-name");var l=d(n,a);U.addClass(this.__ul,e.CLASS_CLOSED),U.addClass(l,"title"),U.bind(l,"click",function(e){return e.preventDefault(),n.closed=!n.closed,!1}),o.closed||(this.closed=!1)}o.autoPlace&&(k.isUndefined(o.parent)&&(le&&(de=document.createElement("div"),U.addClass(de,"dg"),U.addClass(de,e.CLASS_AUTO_PLACE_CONTAINER),document.body.appendChild(de),le=!1),de.appendChild(this.domElement),U.addClass(this.domElement,e.CLASS_AUTO_PLACE)),this.parent||y(n,o.width)),this.__resizeHandler=function(){n.onResizeDebounced()},U.bind(window,"resize",this.__resizeHandler),U.bind(this.__ul,"webkitTransitionEnd",this.__resizeHandler),U.bind(this.__ul,"transitionend",this.__resizeHandler),U.bind(this.__ul,"oTransitionEnd",this.__resizeHandler),this.onResize(),o.resizable&&v(this),r=function(){se&&"true"===localStorage.getItem(f(n,"isLocal"))&&localStorage.setItem(f(n,"gui"),JSON.stringify(n.getSaveObject()))},this.saveToLocalStorageIfPossible=r,o.parent||function(){var e=n.getRoot();e.width+=1,k.defer(function(){e.width-=1})}()};return _e.toggleHide=function(){ce=!ce,k.each(ue,function(e){e.domElement.style.display=ce?"none":""})},_e.CLASS_AUTO_PLACE="a",_e.CLASS_AUTO_PLACE_CONTAINER="ac",_e.CLASS_MAIN="main",_e.CLASS_CONTROLLER_ROW="cr",_e.CLASS_TOO_TALL="taller-than-window",_e.CLASS_CLOSED="closed",_e.CLASS_CLOSE_BUTTON="close-button",_e.CLASS_CLOSE_TOP="close-top",_e.CLASS_CLOSE_BOTTOM="close-bottom",_e.CLASS_DRAG="drag",_e.DEFAULT_WIDTH=245,_e.TEXT_CLOSED="Close Controls",_e.TEXT_OPEN="Open Controls",_e._keydownHandler=function(e){"text"===document.activeElement.type||72!==e.which&&72!==e.keyCode||_e.toggleHide()},U.bind(window,"keydown",_e._keydownHandler,!1),k.extend(_e.prototype,{add:function(e,t){return p(this,e,t,{factoryArgs:Array.prototype.slice.call(arguments,2)})},addColor:function(e,t){return p(this,e,t,{color:!0})},remove:function(e){this.__ul.removeChild(e.__li),this.__controllers.splice(this.__controllers.indexOf(e),1);var t=this;k.defer(function(){t.onResize()})},destroy:function(){if(this.parent)throw new Error("Only the root GUI should be removed with .destroy(). For subfolders, use gui.removeFolder(folder) instead.");this.autoPlace&&de.removeChild(this.domElement);var e=this;k.each(this.__folders,function(t){e.removeFolder(t)}),U.unbind(window,"keydown",_e._keydownHandler,!1),c(this)},addFolder:function(e){if(void 0!==this.__folders[e])throw new Error("You already have a folder in this GUI by the name \""+e+"\"");var t={name:e,parent:this};t.autoPlace=this.autoPlace,this.load&&this.load.folders&&this.load.folders[e]&&(t.closed=this.load.folders[e].closed,t.load=this.load.folders[e]);var n=new _e(t);this.__folders[e]=n;var o=d(this,n.domElement);return U.addClass(o,"folder"),n},removeFolder:function(e){this.__ul.removeChild(e.domElement.parentElement),delete this.__folders[e.name],this.load&&this.load.folders&&this.load.folders[e.name]&&delete this.load.folders[e.name],c(e);var t=this;k.each(e.__folders,function(t){e.removeFolder(t)}),k.defer(function(){t.onResize()})},open:function(){this.closed=!1},close:function(){this.closed=!0},onResize:function(){var e=this.getRoot();if(e.scrollable){var t=U.getOffset(e.__ul).top,n=0;k.each(e.__ul.childNodes,function(t){e.autoPlace&&t===e.__save_row||(n+=U.getHeight(t))}),window.innerHeight-t-20\n\n Here's the new load parameter for your GUI's constructor:\n\n \n\n
\n\n Automatically save\n values to localStorage on exit.\n\n
The values saved to localStorage will\n override those passed to dat.GUI's constructor. This makes it\n easier to work incrementally, but localStorage is fragile,\n and your friends may not see the same values you do.\n\n
\n\n
\n\n
"),this.parent)throw new Error("You can only call remember on a top level GUI.");var e=this;k.each(Array.prototype.slice.call(arguments),function(t){0===e.__rememberedObjects.length&&b(e),-1===e.__rememberedObjects.indexOf(t)&&e.__rememberedObjects.push(t)}),this.autoPlace&&y(this,this.width)},getRoot:function(){for(var e=this;e.parent;)e=e.parent;return e},getSaveObject:function(){var e=this.load;return e.closed=this.closed,this.__rememberedObjects.length>0&&(e.preset=this.preset,e.remembered||(e.remembered={}),e.remembered[this.preset]=w(this)),e.folders={},k.each(this.__folders,function(t,n){e.folders[n]=t.getSaveObject()}),e},save:function(){this.load.remembered||(this.load.remembered={}),this.load.remembered[this.preset]=w(this),u(this,!1),this.saveToLocalStorageIfPossible()},saveAs:function(e){this.load.remembered||(this.load.remembered={},this.load.remembered[re]=w(this,!0)),this.load.remembered[e]=w(this),this.preset=e,m(this,e,!0),this.saveToLocalStorageIfPossible()},revert:function(e){k.each(this.__controllers,function(t){this.getRoot().load.remembered?h(e||this.getRoot(),t):t.setValue(t.initialValue),t.__onFinishChange&&t.__onFinishChange.call(t,t.getValue())},this),k.each(this.__folders,function(e){e.revert(e)}),e||u(this.getRoot(),!1)},listen:function(e){var t=0===this.__listening.length;this.__listening.push(e),t&&E(this.__listening)},updateDisplay:function(){k.each(this.__controllers,function(e){e.updateDisplay()}),k.each(this.__folders,function(e){e.updateDisplay()})}}),{color:{Color:V,math:B,interpret:R},controllers:{Controller:I,BooleanController:X,OptionController:K,StringController:Y,NumberController:J,NumberControllerBox:W,NumberControllerSlider:Q,FunctionController:q,ColorController:Z},dom:{dom:U},gui:{GUI:_e},GUI:_e}});!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r;r="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,r.msgpack=t()}}(function(){return function t(r,e,n){function i(f,u){if(!e[f]){if(!r[f]){var a="function"==typeof require&&require;if(!u&&a)return a(f,!0);if(o)return o(f,!0);var s=new Error("Cannot find module '"+f+"'");throw s.code="MODULE_NOT_FOUND",s}var c=e[f]={exports:{}};r[f][0].call(c.exports,function(t){var e=r[f][1][t];return i(e?e:t)},c,c.exports,t,r,e,n)}return e[f].exports}for(var o="function"==typeof require&&require,f=0;f>>6,e[n++]=128|63&o):o<55296||o>57343?(e[n++]=224|o>>>12,e[n++]=128|o>>>6&63,e[n++]=128|63&o):(o=(o-55296<<10|t.charCodeAt(f++)-56320)+65536,e[n++]=240|o>>>18,e[n++]=128|o>>>12&63,e[n++]=128|o>>>6&63,e[n++]=128|63&o);return n-r}function i(t,r,e){var n=this,i=0|r;e||(e=n.length);for(var o="",f=0;i=65536?(f-=65536,o+=String.fromCharCode((f>>>10)+55296,(1023&f)+56320)):o+=String.fromCharCode(f));return o}function o(t,r,e,n){var i;e||(e=0),n||0===n||(n=this.length),r||(r=0);var o=n-e;if(t===this&&e=0;i--)t[i+r]=this[i+e];else for(i=0;ithis.buffer.length)throw new Error(v);return this.offset=e,r}return{bufferish:p,write:t,fetch:a,flush:r,push:c,pull:h,read:s,reserve:e,offset:0}}function f(){function t(){var t=this.start;if(t1?this.bufferish.concat(t):t[0];return t.length=0,r}function n(t){var r=0|t;if(this.buffer){var e=this.buffer.length,n=0|this.offset,i=n+r;if(ithis.minBufferSize)this.flush(),this.push(t);else{var e=this.reserve(r);p.prototype.copy.call(t,this.buffer,e)}}return{bufferish:p,write:u,fetch:t,flush:r,push:c,pull:e,read:s,reserve:n,send:i,maxBufferSize:y,minBufferSize:d,offset:0,start:0}}function u(){throw new Error("method not implemented: write()")}function a(){throw new Error("method not implemented: fetch()")}function s(){var t=this.buffers&&this.buffers.length;return t?(this.flush(),this.pull()):this.fetch()}function c(t){var r=this.buffers||(this.buffers=[]);r.push(t)}function h(){var t=this.buffers||(this.buffers=[]);return t.shift()}function l(t){function r(r){for(var e in t)r[e]=t[e];return r}return r}e.FlexDecoder=n,e.FlexEncoder=i;var p=t("./bufferish"),d=2048,y=65536,v="BUFFER_SHORTAGE";n.mixin=l(o()),n.mixin(n.prototype),i.mixin=l(f()),i.mixin(i.prototype)},{"./bufferish":8}],22:[function(t,r,e){function n(t){function r(t){var r=s(t),n=e[r];if(!n)throw new Error("Invalid type: "+(r?"0x"+r.toString(16):r));return n(t)}var e=c.getReadToken(t);return r}function i(){var t=this.options;return this.decode=n(t),t&&t.preset&&a.setExtUnpackers(this),this}function o(t,r){var e=this.extUnpackers||(this.extUnpackers=[]);e[t]=h.filter(r)}function f(t){function r(r){return new u(r,t)}var e=this.extUnpackers||(this.extUnpackers=[]);return e[t]||r}var u=t("./ext-buffer").ExtBuffer,a=t("./ext-unpacker"),s=t("./read-format").readUint8,c=t("./read-token"),h=t("./codec-base");h.install({addExtUnpacker:o,getExtUnpacker:f,init:i}),e.preset=i.call(h.preset)},{"./codec-base":9,"./ext-buffer":17,"./ext-unpacker":19,"./read-format":23,"./read-token":24}],23:[function(t,r,e){function n(t){var r=k.hasArrayBuffer&&t&&t.binarraybuffer,e=t&&t.int64,n=T&&t&&t.usemap,B={map:n?o:i,array:f,str:u,bin:r?s:a,ext:c,uint8:h,uint16:p,uint32:y,uint64:g(8,e?E:b),int8:l,int16:d,int32:v,int64:g(8,e?A:w),float32:g(4,m),float64:g(8,x)};return B}function i(t,r){var e,n={},i=new Array(r),o=new Array(r),f=t.codec.decode;for(e=0;e>>8,i[n]=e}}function s(t){return function(r,e){var n=r.reserve(5),i=r.buffer;i[n++]=t,i[n++]=e>>>24,i[n++]=e>>>16,i[n++]=e>>>8,i[n]=e}}function c(t,r,e,n){return function(i,o){var f=i.reserve(r+1);i.buffer[f++]=t,e.call(i.buffer,o,f,n)}}function h(t,r){new g(this,r,t)}function l(t,r){new b(this,r,t)}function p(t,r){y.write(this,t,r,!1,23,4)}function d(t,r){y.write(this,t,r,!1,52,8)}var y=t("ieee754"),v=t("int64-buffer"),g=v.Uint64BE,b=v.Int64BE,w=t("./write-uint8").uint8,E=t("./bufferish"),Buffer=E.global,A=E.hasBuffer&&"TYPED_ARRAY_SUPPORT"in Buffer,m=A&&!Buffer.TYPED_ARRAY_SUPPORT,x=E.hasBuffer&&Buffer.prototype||{};e.getWriteToken=n},{"./bufferish":8,"./write-uint8":28,ieee754:32,"int64-buffer":33}],27:[function(t,r,e){function n(t){function r(t,r){var e=r?195:194;_[e](t,r)}function e(t,r){var e,n=0|r;return r!==n?(e=203,void _[e](t,r)):(e=-32<=n&&n<=127?255&n:0<=n?n<=255?204:n<=65535?205:206:-128<=n?208:-32768<=n?209:210,void _[e](t,n))}function n(t,r){var e=207;_[e](t,r.toArray())}function o(t,r){var e=211;_[e](t,r.toArray())}function v(t){return t<32?1:t<=255?2:t<=65535?3:5}function g(t){return t<32?1:t<=65535?3:5}function b(t){function r(r,e){var n=e.length,i=5+3*n;r.offset=r.reserve(i);var o=r.buffer,f=t(n),u=r.offset+f;n=s.write.call(o,e,u);var a=t(n);if(f!==a){var c=u+a-f,h=u+n;s.copy.call(o,o,c,u,h)}var l=1===a?160+n:a<=3?215+a:219;_[l](r,n),r.offset+=n}return r}function w(t,r){if(null===r)return A(t,r);if(I(r))return Y(t,r);if(i(r))return m(t,r);if(f.isUint64BE(r))return n(t,r);if(u.isInt64BE(r))return o(t,r);var e=t.codec.getExtPacker(r);return e&&(r=e(r)),r instanceof l?U(t,r):void D(t,r)}function E(t,r){return I(r)?k(t,r):void w(t,r)}function A(t,r){var e=192;_[e](t,r)}function m(t,r){var e=r.length,n=e<16?144+e:e<=65535?220:221;_[n](t,e);for(var i=t.codec.encode,o=0;o=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|t}function y(t){return+t!=t&&(t=0),Buffer.alloc(+t)}function v(t,r){if(Buffer.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var e=t.length;if(0===e)return 0;for(var n=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return q(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return X(t).length;default:if(n)return q(t).length;r=(""+r).toLowerCase(),n=!0;}}function g(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if(e>>>=0,r>>>=0,e<=r)return"";for(t||(t="utf8");;)switch(t){case"hex":return I(this,r,e);case"utf8":case"utf-8":return k(this,r,e);case"ascii":return T(this,r,e);case"latin1":case"binary":return S(this,r,e);case"base64":return R(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Y(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0;}}function b(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function w(t,r,e,n,i){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=i?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(i)return-1;e=t.length-1}else if(e<0){if(!i)return-1;e=0}if("string"==typeof r&&(r=Buffer.from(r,n)),Buffer.isBuffer(r))return 0===r.length?-1:E(t,r,e,n,i);if("number"==typeof r)return r=255&r,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):E(t,[r],e,n,i);throw new TypeError("val must be string, number or Buffer")}function E(t,r,e,n,i){function o(t,r){return 1===f?t[r]:t.readUInt16BE(r*f)}var f=1,u=t.length,a=r.length;if(void 0!==n&&(n=String(n).toLowerCase(),"ucs2"===n||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;f=2,u/=2,a/=2,e/=2}var s;if(i){var c=-1;for(s=e;su&&(e=u-a),s=e;s>=0;s--){for(var h=!0,l=0;li&&(n=i)):n=i;var o=r.length;if(o%2!==0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var f=0;f239?4:o>223?3:o>191?2:1;if(i+u<=e){var a,s,c,h;switch(u){case 1:o<128&&(f=o);break;case 2:a=t[i+1],128===(192&a)&&(h=(31&o)<<6|63&a,h>127&&(f=h));break;case 3:a=t[i+1],s=t[i+2],128===(192&a)&&128===(192&s)&&(h=(15&o)<<12|(63&a)<<6|63&s,h>2047&&(h<55296||h>57343)&&(f=h));break;case 4:a=t[i+1],s=t[i+2],c=t[i+3],128===(192&a)&&128===(192&s)&&128===(192&c)&&(h=(15&o)<<18|(63&a)<<12|(63&s)<<6|63&c,h>65535&&h<1114112&&(f=h));}}null===f?(f=65533,u=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=u}return _(n)}function _(t){var r=t.length;if(r<=$)return String.fromCharCode.apply(String,t);for(var e="",n=0;nn)&&(e=n);for(var i="",o=r;oe)throw new RangeError("Trying to access beyond buffer length")}function D(t,r,e,n,i,o){if(!Buffer.isBuffer(t))throw new TypeError("\"buffer\" argument must be a Buffer instance");if(r>i||rt.length)throw new RangeError("Index out of range")}function O(t,r,e,n){r<0&&(r=65535+r+1);for(var i=0,o=Math.min(t.length-e,2);i>>8*(n?i:1-i)}function L(t,r,e,n){r<0&&(r=4294967295+r+1);for(var i=0,o=Math.min(t.length-e,4);i>>8*(n?i:3-i)&255}function M(t,r,e,n,i,o){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function N(t,r,e,n,i){return i||M(t,r,e,4,3.4028234663852886e38,-3.4028234663852886e38),K.write(t,r,e,n,23,4),e+4}function F(t,r,e,n,i){return i||M(t,r,e,8,1.7976931348623157e308,-1.7976931348623157e308),K.write(t,r,e,n,52,8),e+8}function j(t){if(t=z(t).replace(tt,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function z(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function V(t){return t<16?"0"+t.toString(16):t.toString(16)}function q(t,r){r=r||1/0;for(var e,n=t.length,i=null,o=[],f=0;f55295&&e<57344){if(!i){if(e>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(f+1===n){(r-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(r-=3)>-1&&o.push(239,191,189),i=e;continue}e=(i-55296<<10|e-56320)+65536}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((r-=1)<0)break;o.push(e)}else if(e<2048){if((r-=2)<0)break;o.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;o.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return o}function W(t){for(var r=[],e=0;e>8,i=e%256,o.push(i),o.push(n);return o}function X(t){return Z.toByteArray(j(t))}function G(t,r,e,n){for(var i=0;i=r.length||i>=t.length);++i)r[i+e]=t[i];return i}function H(t){return t!==t}var Z=t("base64-js"),K=t("ieee754"),Q=t("isarray");e.Buffer=Buffer,e.SlowBuffer=y,e.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==r.TYPED_ARRAY_SUPPORT?r.TYPED_ARRAY_SUPPORT:n(),e.kMaxLength=i(),Buffer.poolSize=8192,Buffer._augment=function(t){return t.__proto__=Buffer.prototype,t},Buffer.from=function(t,r,e){return f(null,t,r,e)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(t,r,e){return a(null,t,r,e)},Buffer.allocUnsafe=function(t){return s(null,t)},Buffer.allocUnsafeSlow=function(t){return s(null,t)},Buffer.isBuffer=function(t){return!(null==t||!t._isBuffer)},Buffer.compare=function(t,r){if(!Buffer.isBuffer(t)||!Buffer.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(t===r)return 0;for(var e=t.length,n=r.length,i=0,o=Math.min(e,n);i0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),""},Buffer.prototype.compare=function(t,r,e,n,i){if(!Buffer.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),r<0||e>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&r>=e)return 0;if(n>=i)return-1;if(r>=e)return 1;if(r>>>=0,e>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var o=i-n,f=e-r,u=Math.min(o,f),a=this.slice(n,i),s=t.slice(r,e),c=0;ci)&&(e=i),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return A(this,t,r,e);case"utf8":case"utf-8":return m(this,t,r,e);case"ascii":return x(this,t,r,e);case"latin1":case"binary":return B(this,t,r,e);case"base64":return U(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,r,e);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0;}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var $=4096;Buffer.prototype.slice=function(t,r){var e=this.length;t=~~t,r=void 0===r?e:~~r,t<0?(t+=e,t<0&&(t=0)):t>e&&(t=e),r<0?(r+=e,r<0&&(r=0)):r>e&&(r=e),r0&&(i*=256);)n+=this[t+--r]*i;return n},Buffer.prototype.readUInt8=function(t,r){return r||C(t,1,this.length),this[t]},Buffer.prototype.readUInt16LE=function(t,r){return r||C(t,2,this.length),this[t]|this[t+1]<<8},Buffer.prototype.readUInt16BE=function(t,r){return r||C(t,2,this.length),this[t]<<8|this[t+1]},Buffer.prototype.readUInt32LE=function(t,r){return r||C(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Buffer.prototype.readUInt32BE=function(t,r){return r||C(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Buffer.prototype.readIntLE=function(t,r,e){t=0|t,r=0|r,e||C(t,r,this.length);for(var n=this[t],i=1,o=0;++o=i&&(n-=Math.pow(2,8*r)),n},Buffer.prototype.readIntBE=function(t,r,e){t=0|t,r=0|r,e||C(t,r,this.length);for(var n=r,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*r)),o},Buffer.prototype.readInt8=function(t,r){return r||C(t,1,this.length),128&this[t]?(255-this[t]+1)*-1:this[t]},Buffer.prototype.readInt16LE=function(t,r){r||C(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},Buffer.prototype.readInt16BE=function(t,r){r||C(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},Buffer.prototype.readInt32LE=function(t,r){return r||C(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Buffer.prototype.readInt32BE=function(t,r){return r||C(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Buffer.prototype.readFloatLE=function(t,r){return r||C(t,4,this.length),K.read(this,t,!0,23,4)},Buffer.prototype.readFloatBE=function(t,r){return r||C(t,4,this.length),K.read(this,t,!1,23,4)},Buffer.prototype.readDoubleLE=function(t,r){return r||C(t,8,this.length),K.read(this,t,!0,52,8)},Buffer.prototype.readDoubleBE=function(t,r){return r||C(t,8,this.length),K.read(this,t,!1,52,8)},Buffer.prototype.writeUIntLE=function(t,r,e,n){if(t=+t,r=0|r,e=0|e,!n){var i=Math.pow(2,8*e)-1;D(this,t,r,e,i,0)}var o=1,f=0;for(this[r]=255&t;++f=0&&(f*=256);)this[r+o]=t/f&255;return r+e},Buffer.prototype.writeUInt8=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=255&t,r+1},Buffer.prototype.writeUInt16LE=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):O(this,t,r,!0),r+2},Buffer.prototype.writeUInt16BE=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):O(this,t,r,!1),r+2},Buffer.prototype.writeUInt32LE=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t):L(this,t,r,!0),r+4},Buffer.prototype.writeUInt32BE=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):L(this,t,r,!1),r+4},Buffer.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r=0|r,!n){var i=Math.pow(2,8*e-1);D(this,t,r,e,i-1,-i)}var o=0,f=1,u=0;for(this[r]=255&t;++o>0)-u&255;return r+e},Buffer.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r=0|r,!n){var i=Math.pow(2,8*e-1);D(this,t,r,e,i-1,-i)}var o=e-1,f=1,u=0;for(this[r+o]=255&t;--o>=0&&(f*=256);)t<0&&0===u&&0!==this[r+o+1]&&(u=1),this[r+o]=(t/f>>0)-u&255;return r+e},Buffer.prototype.writeInt8=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=255&t,r+1},Buffer.prototype.writeInt16LE=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):O(this,t,r,!0),r+2},Buffer.prototype.writeInt16BE=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):O(this,t,r,!1),r+2},Buffer.prototype.writeInt32LE=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):L(this,t,r,!0),r+4},Buffer.prototype.writeInt32BE=function(t,r,e){return t=+t,r=0|r,e||D(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Buffer.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):L(this,t,r,!1),r+4},Buffer.prototype.writeFloatLE=function(t,r,e){return N(this,t,r,!0,e)},Buffer.prototype.writeFloatBE=function(t,r,e){return N(this,t,r,!1,e)},Buffer.prototype.writeDoubleLE=function(t,r,e){return F(this,t,r,!0,e)},Buffer.prototype.writeDoubleBE=function(t,r,e){return F(this,t,r,!1,e)},Buffer.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r=0;--i)t[i+r]=this[i+e];else if(o<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,e=void 0===e?this.length:e>>>0,t||(t=0);var o;if("number"==typeof t)for(o=r;o0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[r-2]?2:"="===t[r-1]?1:0}function i(t){return 3*t.length/4-n(t)}function o(t){var r,e,i,o,f,u,a=t.length;f=n(t),u=new h(3*a/4-f),i=f>0?a-4:a;var s=0;for(r=0,e=0;r>16&255,u[s++]=o>>8&255,u[s++]=255&o;return 2===f?(o=c[t.charCodeAt(r)]<<2|c[t.charCodeAt(r+1)]>>4,u[s++]=255&o):1===f&&(o=c[t.charCodeAt(r)]<<10|c[t.charCodeAt(r+1)]<<4|c[t.charCodeAt(r+2)]>>2,u[s++]=o>>8&255,u[s++]=255&o),u}function f(t){return s[t>>18&63]+s[t>>12&63]+s[t>>6&63]+s[63&t]}function u(t,r,e){for(var n,i=[],o=r;oc?c:a+f));return 1===n?(r=t[e-1],i+=s[r>>2],i+=s[r<<4&63],i+="=="):2===n&&(r=(t[e-2]<<8)+t[e-1],i+=s[r>>10],i+=s[r>>4&63],i+=s[r<<2&63],i+="="),o.push(i),o.join("")}e.byteLength=i,e.toByteArray=o,e.fromByteArray=a;for(var s=[],c=[],h="undefined"!=typeof Uint8Array?Uint8Array:Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,d=l.length;p>1,c=-7,h=e?i-1:0,l=e?-1:1,p=t[r+h];for(h+=l,o=p&(1<<-c)-1,p>>=-c,c+=u;c>0;o=256*o+t[r+h],h+=l,c-=8);for(f=o&(1<<-c)-1,o>>=-c,c+=n;c>0;f=256*f+t[r+h],h+=l,c-=8);if(0===o)o=1-s;else{if(o===a)return f?NaN:(p?-1:1)*(1/0);f+=Math.pow(2,n),o-=s}return(p?-1:1)*f*Math.pow(2,o-n)},e.write=function(t,r,e,n,i,o){var f,u,a,s=8*o-i-1,c=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,y=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,f=c):(f=Math.floor(Math.log(r)/Math.LN2),r*(a=Math.pow(2,-f))<1&&(f--,a*=2),r+=f+h>=1?l/a:l*Math.pow(2,1-h),r*a>=2&&(f++,a/=2),f+h>=c?(u=0,f=c):f+h>=1?(u=(r*a-1)*Math.pow(2,i),f+=h):(u=r*Math.pow(2,h-1)*Math.pow(2,i),f=0));i>=8;t[e+p]=255&u,p+=d,u/=256,i-=8);for(f=f<0;t[e+p]=255&f,p+=d,f/=256,s-=8);t[e+p-d]|=128*y}},{}],33:[function(t,r,e){(function(Buffer){var t,r,n,i;!function(e){function o(t,r,n){function i(t,r,e,n){return this instanceof i?v(this,t,r,e,n):new i(t,r,e,n)}function o(t){return!(!t||!t[F])}function v(t,r,e,n,i){if(E&&A&&(r instanceof A&&(r=new E(r)),n instanceof A&&(n=new E(n))),!(r||e||n||g))return void(t.buffer=h(m,0));if(!s(r,e)){var o=g||Array;i=e,n=r,e=0,r=new o(8)}t.buffer=r,t.offset=e|=0,b!==typeof n&&("string"==typeof n?x(r,e,n,i||10):s(n,i)?c(r,e,n,i):"number"==typeof i?(k(r,e+T,n),k(r,e+S,i)):n>0?O(r,e,n):n<0?L(r,e,n):c(r,e,m,0))}function x(t,r,e,n){var i=0,o=e.length,f=0,u=0;"-"===e[0]&&i++;for(var a=i;i=0))break;u=u*n+s,f=f*n+Math.floor(u/B),u%=B}a&&(f=~f,u?u=B-u:f++),k(t,r+T,f),k(t,r+S,u)}function P(){var t=this.buffer,r=this.offset,e=_(t,r+T),i=_(t,r+S);return n||(e|=0),e?e*B+i:i}function R(t){var r=this.buffer,e=this.offset,i=_(r,e+T),o=_(r,e+S),f="",u=!n&&2147483648&i;for(u&&(i=~i,o=B-o),t=t||10;;){var a=i%t*B+o;if(i=Math.floor(i/t),o=Math.floor(a/t),f=(a%t).toString(t)+f,!i&&!o)break}return u&&(f="-"+f),f}function k(t,r,e){t[r+D]=255&e,e>>=8,t[r+C]=255&e,e>>=8,t[r+Y]=255&e,e>>=8,t[r+I]=255&e}function _(t,r){return t[r+I]*U+(t[r+Y]<<16)+(t[r+C]<<8)+t[r+D]}var T=r?0:4,S=r?4:0,I=r?0:3,Y=r?1:2,C=r?2:1,D=r?3:0,O=r?l:d,L=r?p:y,M=i.prototype,N="is"+t,F="_"+N;return M.buffer=void 0,M.offset=0,M[F]=!0,M.toNumber=P,M.toString=R,M.toJSON=P,M.toArray=f,w&&(M.toBuffer=u),E&&(M.toArrayBuffer=a),i[N]=o,e[t]=i,i}function f(t){var r=this.buffer,e=this.offset;return g=null,t!==!1&&0===e&&8===r.length&&x(r)?r:h(r,e)}function u(t){var r=this.buffer,e=this.offset;if(g=w,t!==!1&&0===e&&8===r.length&&Buffer.isBuffer(r))return r;var n=new w(8);return c(n,0,r,e),n}function a(t){var r=this.buffer,e=this.offset,n=r.buffer;if(g=E,t!==!1&&0===e&&n instanceof A&&8===n.byteLength)return n;var i=new E(8);return c(i,0,r,e),i.buffer}function s(t,r){var e=t&&t.length;return r|=0,e&&r+8<=e&&"string"!=typeof t[r]}function c(t,r,e,n){r|=0,n|=0;for(var i=0;i<8;i++)t[r++]=255&e[n++]}function h(t,r){return Array.prototype.slice.call(t,r,r+8)}function l(t,r,e){for(var n=r+8;n>r;)t[--n]=255&e,e/=256}function p(t,r,e){var n=r+8;for(e++;n>r;)t[--n]=255&-e^255,e/=256}function d(t,r,e){for(var n=r+8;r7000){$.post("/api/log",{event:"rollbar",text:`${Date.now()}:- JoinGame took ${window.joinGameSent.completed}ms to join player`+`, client to gs: ${self._stats.receivedJoinGame-window.joinGameSent.start}ms`+`, gs loading player data: ${self._stats.totalTime}ms`+`, gs processed request for: ${self._stats.processedJoinGame}ms`+`, gs to client: ${streamingDiff}, client sent on: ${window.joinGameSent.start}, server sent back on: ${data.streamedOn}`})}if(self._stats.processedJoinGame>7000){$.post("/api/log",{event:"rollbar",text:`${Date.now()}JoinGame took ${window.joinGameSent.completed}ms to create player`+`, client to gs: ${self._stats.receivedJoinGame-window.joinGameSent.start}ms`+`, gs loading player data: ${self._stats.totalTime}ms`+`, gs processed request for: ${self._stats.processedJoinGame}ms`+`, gs to client: ${streamingDiff}, client sent on: ${window.joinGameSent.start}, server sent back on: ${data.streamedOn}`})}self.hideMenu();clearTimeout(window.errorLogTimer)}}if(attrName==="banChat"&&(ige.game.data.isDeveloper||ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod)){ige.menuUi.kickPlayerFromGame()}}}}},setChatMute:function(value){if(ige.env=="local")return;if(value){$("#message").attr("disabled",true);$("#message").attr("placeholder","You are muted")}else{$("#message").attr("disabled",false);$("#message").attr("placeholder","message")}},redrawUnits:function(filterFn,properties){if(filterFn instanceof Array){properties=filterFn;filterFn=null}ige.$$("unit").filter(function(unit){return filterFn?filterFn(unit):true}).forEach(function(unit){properties.forEach(function(property){switch(property){case"nameLabel":{unit.updateNameLabel();break}case"texture":{unit.updateTexture();break}case"attributeBars":{unit.redrawAttributeBars();break}}})})},updatePlayerHighscore:function(){var self=this;var scoreId=ige.game.data.settings.scoreAttributeId;try{if(scoreId&&self._stats&&self._stats.attributes&&self._stats.attributes[scoreId]&&(self._stats.highscoreself._stats.highscore){ige.clusterClient&&ige.clusterClient.updatePlayerHighscore({userId:self._stats.userId,gameId:ige.game.data.defaultData._id,highscore:score})}}}catch(e){Player.prototype.log(e)}},tick:function(ctx){if(ige.isServer){if(this.attribute){this.attribute.regenerate()}}$i_56.prototype.tick.call(this,ctx)},loadPersistentData:function(){var self=this;var persistData=_.cloneDeep(self.persistedData);if(persistData&&persistData.data&&persistData.data.player){$i_56.prototype.loadPersistentData.call(this,persistData.data.player)}console.log("load persisted data is now true");self.persistentDataLoaded=true},loadDataFromString:function(data){var self=this;var persistData=data;if(persistData){$i_56.prototype.loadPersistentData.call(this,persistData)}self.persistentDataLoaded=true},hideMenu:function(){if(ige.isClient){$("#play-game-button").removeAttr("disabled");var html="Continue";$("#play-game-button .content").html(html);$("#modd-shop-div").addClass("d-flex");ige.client.eventLog.push([ige._currentTime-ige.client.eventLogStartTime,"hide menu called"]);ige.menuUi.hideMenu();if(!ige.client.guestmode){$(".open-menu-button").show()}if(typeof userId!=="undefined"&&typeof sessionId!=="undefined"){if(ige.game.data.isDeveloper){$("#toggle-dev-panels").show();$("#kick-player").show()}if(ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod){$("#kick-player").show()}}}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=Player}var Unit=$i_56Physics.extend({classId:"Unit",init:function(data,entityIdFromServer){$i_56Physics.prototype.init.call(this,data.defaultData);this.id(entityIdFromServer);if(ige.isClient){this._pixiContainer=new PIXI.Container}var self=this;self.dob=Date.now();self.force={x:0,y:0};self.direction={x:0,y:0};self.isMoving=false;self.angleToTarget=undefined;this.category("unit");var unitData={};if(!data.hasOwnProperty("equipmentAllowed")){data.equipmentAllowed=9}unitData=ige.game.getAsset("unitTypes",data.type);if(ige.isClient){unitData=_.pick(unitData,ige.client.keysToAddBeforeRender)}self._stats=Object.assign(data,unitData,{bonusSpeed:0,flip:data.flip==undefined?0:data.flip});self.entityId=entityIdFromServer;if(self._stats.variables){self.variables=self._stats.variables;delete self._stats.variables}self.parseEntityObject(self._stats);self.addComponent(InventoryComponent).addComponent(AbilityComponent).addComponent(AttributeComponent);Unit.prototype.log(`initializing new unit ${this.id()}`);self.changeUnitType(data.type,data.defaultData);if(this._stats.states){var currentState=this._stats.states[this._stats.stateId];var defaultAnimation=this._stats.animations[currentState.animation]}if(ige.isClient){this.createTexture(defaultAnimation&&defaultAnimation.frames[0]-1);self.mount(ige.pixi.world);this.transformTexture(this._translate.x,this._translate.y)}if(self._stats.scale){}if(self._stats.scaleBody){self._stats.scale=parseFloat(self._stats.scaleBody)}else{if(!self._stats.scale){self._stats.scale=self._stats.currentBody.spriteScale>0?self._stats.currentBody.spriteScale:1}}self._stats.fadingTextQueue=[];self.particleEmitters={};self._stats.buffs=[];if(ige.isServer){self._stats.minimapUnitVisibleToClients={};self.mount(ige.$("baseScene"));self.streamMode(1);ige.server.totalUnitsCreated++;self.addComponent(AIComponent)}else if(ige.isClient){var networkId=ige.network.id();self.addComponent(UnitUiComponent);if(!self.gluedEntities){self.gluedEntities=[]}if(networkId==self._stats.clientId){for(i in self.attr){ige.playerUi.updateAttrBar(i,self.attr[i],self.max[i])}self.showMinimapUnit();if(window.adBlockEnabled){}}if(self._stats.minimapUnitVisibleToClients&&self._stats.minimapUnitVisibleToClients[networkId]){self.showMinimapUnit(self._stats.minimapUnitVisibleToClients[networkId])}self._scaleTexture();var polygon=new $i_6;self.triggerPolygon(polygon);self.redrawAttributeBars();self.flip(self._stats.flip);self.mouseEvents()}self.playEffect("create");self.addBehaviour("unitBehaviour",self._behaviour);self.scaleDimensions(self._stats.width,self._stats.height);self._stats.isStunned=false},shouldRenderAttribute:function(attribute){var self=this;if(attribute.isVisible==undefined){return false}var ownerPlayer=self.getOwner();if(!ownerPlayer){return false}var shouldRender=Array.isArray(attribute.isVisible)&&(ownerPlayer.isHostileTo(ige.client.myPlayer)&&attribute.isVisible.indexOf("unitBarHostile")>-1||ownerPlayer.isFriendlyTo(ige.client.myPlayer)&&attribute.isVisible.indexOf("unitBarFriendly")>-1||ownerPlayer.isNeutralTo(ige.client.myPlayer)&&attribute.isVisible.indexOf("unitBarNeutral")>-1);if(shouldRender){var showOnlyWhenIsGreaterThanMin=attribute.showWhen=="whenIsGreaterThanMin";shouldRender=showOnlyWhenIsGreaterThanMin?attribute.value>attribute.min:true}if(shouldRender){var showOnlyWhenIsLessThanMax=attribute.showWhen=="whenIsLessThanMax";shouldRender=showOnlyWhenIsLessThanMax?attribute.valueplayerAttrValue){return false}}}var requiredItemTypeIds=Object.keys(shopData.price.requiredItemTypes||{});for(var j=0;j=0){itemData.quantity=parseFloat(shopData.quantity)}var requirementsSatisfied=true;var requiredItemTypeIds=Object.keys(shopData.requirement.requiredItemTypes||{});if(typeof shopData.requirement==="object"){for(var priceAttr in shopData.requirement.playerAttributes){if(ownerPlayer&&ownerPlayer._stats.attributes[priceAttr]){var req=shopData.requirement.playerAttributes[priceAttr];switch(req.type){case"atmost":if(ownerPlayer._stats.attributes[priceAttr].value>req.value){requirementsSatisfied=false}break;case"exactly":if(ownerPlayer._stats.attributes[priceAttr].value!=req.value){requirementsSatisfied=false}break;case"atleast":default:if(ownerPlayer._stats.attributes[priceAttr].value-1||shopData.replaceItemInTargetSlot){var attrData={attributes:{}};for(var attributeTypeId in shopData.price.playerAttributes){var newValue=ownerPlayer.attribute.getValue(attributeTypeId)-shopData.price.playerAttributes[attributeTypeId];attrData.attributes[attributeTypeId]=ownerPlayer.attribute.update(attributeTypeId,newValue,true);ownerPlayer.attribute.update(attributeTypeId,attrData.attributes[attributeTypeId],true)}var requiredItemTypeIds=Object.keys(shopData.price.requiredItemTypes||{});var totalInventorySize=self.inventory.getTotalInventorySize();for(var i=0;i0&&j=balanceOwed){itemToBeConsumed._stats.quantity-=balanceOwed;balanceOwed=0;itemToBeConsumed.streamUpdateData([{quantity:itemToBeConsumed._stats.quantity}])}else if(itemToBeConsumed._stats.quantity>0){var lowerQty=Math.min(itemToBeConsumed._stats.quantity,balanceOwed);balanceOwed-=lowerQty;itemToBeConsumed.updateQuantity(itemToBeConsumed._stats.quantity-lowerQty)}if(itemToBeConsumed._stats.quantity==undefined){balanceOwed=0}if(itemToBeConsumed._stats.quantity==0&&itemToBeConsumed._stats.removeWhenEmpty===true){self.dropItem(itemToBeConsumed._stats.slotIndex);itemToBeConsumed.remove()}}j++}}else if(itemToBeConsumed&&!itemToBeConsumed._stats.quantity&&itemToBeConsumed._stats.quantity!==0&&!balanceOwed&&balanceOwed!==0){self.dropItem(itemToBeConsumed._stats.slotIndex);itemToBeConsumed.remove()}}if(shopData.price.coins&&ownerPlayer._stats.coins>=shopData.price.coins){return}var targetSlots=itemData.controls&&Array.isArray(itemData.controls.permittedInventorySlots)?itemData.controls.permittedInventorySlots:undefined;if(targetSlots!=undefined&&targetSlots[0]>0){var existingItem=self.inventory.getItemBySlotNumber(targetSlots[0]);if(existingItem&&shopData.replaceItemInTargetSlot){existingItem.remove()}}itemData.itemTypeId=itemTypeId;ige.network.send("ui",{command:"shopResponse",type:"purchase"},self._stats.clientId);self.pickUpItem(itemData,shopData.replaceItemInTargetSlot)}else{ige.network.send("ui",{command:"shopResponse",type:"inventory_full"},self._stats.clientId)}}},buyUnit:function(unitTypeId){var self=this;if(ige.isServer){var ownerPlayer=self.getOwner();var lastOpenedShop=ownerPlayer._stats.lastOpenedShop;var shopUnits=ige.game.data.shops[lastOpenedShop]?ige.game.data.shops[lastOpenedShop].unitTypes:[];var selectedUnitShop=shopUnits[unitTypeId];var unitData=ige.shop.getUnitById(unitTypeId);if(selectedUnitShop&&selectedUnitShop.isPurchasable){var isAffordable=true;var requirementsSatisfied=true;if(typeof selectedUnitShop.requirement==="object"){for(var attributeTypeId in selectedUnitShop.requirement.playerAttributes){var unitPrice=selectedUnitShop.requirement.playerAttributes[attributeTypeId];var playerAttrValue=ownerPlayer._stats.attributes[attributeTypeId].value;if(unitPrice>playerAttrValue){requirementsSatisfied=false;break}}}if(requirementsSatisfied&&typeof selectedUnitShop.price==="object"){for(var attributeTypeId in selectedUnitShop.price.playerAttributes){var req=selectedUnitShop.price.playerAttributes[attributeTypeId];switch(req.type){case"atmost":if(ownerPlayer._stats.attributes[attributeTypeId].value>req.value){requirementsSatisfied=false}break;case"exactly":if(ownerPlayer._stats.attributes[attributeTypeId].value!=req.value){requirementsSatisfied=false}break;case"atleast":default:if(ownerPlayer._stats.attributes[attributeTypeId].value0){for(var attributeTypeId in selectedUnitShop.price.playerAttributes){var unitPrice=selectedUnitShop.price.playerAttributes[attributeTypeId];attributes[attributeTypeId]=ownerPlayer._stats.attributes[attributeTypeId].value-unitPrice;ownerPlayer.attribute.update(attributeTypeId,attributes[attributeTypeId],true)}}ige.game.lastPurchasedUniTypetId=unitData.unitTypeId;ige.trigger&&ige.trigger.fire("playerPurchasesUnit",{unitId:self.id(),playerId:ownerPlayer.id()})}}}}},refillAllItemsAmmo:function(){var self=this;for(var i=0;i<12;i++){var item=self.inventory.getItemBySlotNumber(i+1);if(item&&item._stats.isGun){item._stats.ammo=item._stats.ammoSize;item._stats.ammoTotal=item._stats.ammoSize*3}}},getBaseDamage:function(){return this._stats.attributes.damage&&this._stats.attributes.damage.value||0},changeItem:function(itemIndex){var self=this;if(itemIndex==undefined){itemIndex=self._stats.currentItemIndex}var newItem=self.inventory.getItemBySlotNumber(itemIndex+1);var oldItem=ige.$(self._stats.currentItemId);if(newItem&&newItem.id()==self._stats.currentItemId){return}if(oldItem){oldItem.stopUsing()}if(newItem){newItem.setState("selected");self._stats.currentItemId=newItem.id();var triggeredBy={itemId:newItem.id(),unitId:this.id()};ige.trigger&&ige.trigger.fire("unitSelectsItem",triggeredBy);if(ige.isClient){newItem.applyAnimationForState("selected");let customTween={type:"swing",keyFrames:[[0,[0,0,-1.57]],[100,[0,0,0]]]};newItem.tween.start(null,this._rotate.z,customTween)}}else{self._stats.currentItemId=undefined}if(oldItem){oldItem.setState("unselected");if(ige.isClient){oldItem.applyAnimationForState("selected")}}self._stats.currentItemIndex=itemIndex;if(ige.isClient&&this==ige.client.selectedUnit){this.inventory.highlightSlot(itemIndex+1);var item=this.inventory.getItemBySlotNumber(itemIndex+1);ige.itemUi.updateItemInfo(item)}},changeUnitType:function(type,defaultData){var self=this;self.previousState=null;var data=ige.game.getAsset("unitTypes",type);if(data==undefined){ige.script.errorLog("changeUnitType: invalid data");return}self._stats.type=type;var oldAttributes=self._stats.attributes;for(var i in data){if(i=="name"){continue}self._stats[i]=data[i]}if(!this._stats.itemIds){this._stats.itemIds=new Array(self._stats.inventorySize)}var variables={};if(data.variables){for(var key in data.variables){if(self.variables&&self.variables[key]){variables[key]=self.variables[key]==undefined?data.variables[key]:self.variables[key]}else{variables[key]=data.variables[key]}}self.variables=variables}if(self._stats.variables){delete self._stats.variables}if(data.attributes){for(var attrId in data.attributes){if(data.attributes[attrId]){var attributeValue=data.attributes[attrId].value;if(oldAttributes&&oldAttributes[attrId]){attributeValue=oldAttributes[attrId].value}if(this._stats.attributes[attrId]){this._stats.attributes[attrId].value=Math.max(data.attributes[attrId].min,Math.min(data.attributes[attrId].max,parseFloat(attributeValue)))}}}}self.setState(this._stats.stateId,defaultData);if(ige.isClient){self.updateTexture();self._scaleTexture()}for(let i=0;i0&&matchingItem._stats.maxQuantity-matchingItem._stats.quantity>0){if(matchingItem._stats.maxQuantity!=undefined){var quantityToBeTakenFromItem=Math.min(itemData.quantity,matchingItem._stats.maxQuantity-matchingItem._stats.quantity)}else{var quantityToBeTakenFromItem=0}matchingItem.streamUpdateData([{quantity:matchingItem._stats.quantity+quantityToBeTakenFromItem}]);itemData.quantity-=quantityToBeTakenFromItem}}if(itemData.maxQuantity!=0&&itemData.quantity==0){if(isItemInstance){item.remove()}return true}}}}if(availableSlot!=undefined){if(!isItemInstance){item=new Item(itemData)}self.inventory.insertItem(item,availableSlot-1);self.streamUpdateData([{itemIds:self._stats.itemIds}]);var slotIndex=availableSlot-1;item.streamUpdateData([{ownerUnitId:self.id()},{quantity:itemData.quantity},{slotIndex:slotIndex}]);if(item._stats.bonus&&item._stats.bonus.passive){if(item._stats.slotIndex-1)},canUseItem:function(itemData){return itemData&&(!itemData.canBeUsedBy||itemData.canBeUsedBy.length==0||itemData.canBeUsedBy&&itemData.canBeUsedBy.indexOf(this._stats.type)>-1)},updateNameLabel:function(){var self=this;var ownerPlayer=self.getOwner();var playerTypeData=ownerPlayer&&ige.game.getAsset("playerTypes",ownerPlayer._stats.playerTypeId);if(self.unitNameLabel){self.unitNameLabel.destroy();delete self.unitNameLabel}var hideLabel=ownerPlayer&&ownerPlayer.isHostileTo(ige.client.myPlayer)&&self._stats.isNameLabelHidden||ownerPlayer&&ownerPlayer.isFriendlyTo(ige.client.myPlayer)&&self._stats.isNameLabelHiddenToFriendly||ownerPlayer&&ownerPlayer.isNeutralTo(ige.client.myPlayer)&&self._stats.isNameLabelHiddenToNeutral||(playerTypeData?playerTypeData.showNameLabel===false:true)||!ige.client.myPlayer||ige.client.myPlayer._stats.playerJoined===false;if(hideLabel){return}var color="#FFFFFF";var isMyUnit=ige.network.id()==self._stats.clientId;if(ownerPlayer){color=playerTypeData&&playerTypeData.color}self.unitNameLabel=new IgePixiFloatingText(self._stats.name,{shouldBeBold:isMyUnit,parentUnit:self.id(),gluedIndex:0,color:color});self.unitNameLabel._pixiText._style._fontWeight=599;this._pixiContainer.addChild(self.unitNameLabel._pixiText)},updateFadingText:function(text,color){var self=this;var ownerPlayer=self.getOwner();var playerTypeData=ownerPlayer&&ige.game.getAsset("playerTypes",ownerPlayer._stats.playerTypeId);var hideLabel=ownerPlayer&&ownerPlayer.isHostileTo(ige.client.myPlayer)&&self._stats.isNameLabelHidden||ownerPlayer&&ownerPlayer.isFriendlyTo(ige.client.myPlayer)&&self._stats.isNameLabelHiddenToFriendly||ownerPlayer&&ownerPlayer.isNeutralTo(ige.client.myPlayer)&&self._stats.isNameLabelHiddenToNeutral||!ige.client.myPlayer||ige.client.myPlayer._stats.playerJoined===false;if(hideLabel){return}var DEFAULT_COLOR="white";var shouldBeBold=ige.network.id()==self._stats.clientId;var isQueueProcessorRunning=!!self._stats.fadingTextQueue.length;self._stats.fadingTextQueue.push({text:text,color:color});if(!isQueueProcessorRunning){var queueProcessor=setInterval(function(){if(!self._stats.fadingTextQueue.length){return clearInterval(queueProcessor)}var highestDepth=6;for(var i=0;i0){owner._stats.purchasables.forEach(function(purchasable){if(purchasable&&purchasable.target&&purchasable.target.entityType==="unit"&&purchasable.target.key===self._stats.type){var defaultUnit=ige.game.getAsset("unitTypes",self._stats.type);if(self._stats.clientId===ige.network.id()&&window.adBlockEnabled&&defaultUnit.cellSheet.url!==purchasable.image){notifyAboutAdblocker(2);$("#modd-shop-modal").modal("hide")}else{if(purchasable.image&&purchasable.image.indexOf("cdn.discordapp.com")===-1){self._stats.cellSheet.url=purchasable.image}}}})}self.updateTexture()}else if(ige.isServer){self._stats.cellSheet.url=equipPurchasable.image;if(!owner._stats.purchasables||!(owner._stats.purchasables instanceof Array))owner._stats.purchasables=[];var index=owner._stats.purchasables.findIndex(function(purchasable){if(purchasable.type===equipPurchasable.type)return true});if(index>-1){owner._stats.purchasables.splice(index,1)}var purchasables=_.cloneDeep(owner._stats.purchasables);purchasables.push(equipPurchasable);owner.streamUpdateData([{purchasables:purchasables},{equiped:true}])}},unEquipSkin:function(unEquipedId,forceFullyUnequip,cellSheetUrl){var self=this;var defaultUnit=ige.game.getAsset("unitTypes",self._stats.type);var owner=this.getOwner();if(ige.isServer){if(owner&&owner._stats&&owner._stats.purchasables&&owner._stats.purchasables.length>0){var index=owner._stats.purchasables.findIndex(function(purchasable){if(unEquipedId===purchasable._id){cellSheetUrl=purchasable.image;return true}});var purchasables=_.cloneDeep(owner._stats.purchasables);if(index>-1){purchasables.splice(index,1);owner.streamUpdateData([{purchasables:purchasables},{unEquiped:cellSheetUrl}])}}}else if(ige.isClient){if(cellSheetUrl===self._stats.cellSheet.url||forceFullyUnequip){self._stats.cellSheet.url=defaultUnit.cellSheet.url}self.updateTexture()}},hideMinimapUnit:function(){var self=this;if(self.minimapUnit){self.minimapUnit.destroy()}},loadPersistentData:function(){var self=this;var owner=self.getOwner();var persistedData=_.cloneDeep(owner.persistedData);if(persistedData&&persistedData.data&&persistedData.data.unit){$i_56.prototype.loadPersistentData.call(this,persistedData.data.unit);var persistedInventoryItems=persistedData.data.unit.inventoryItems;for(var i=0;ithis.width()){if(self.angleToTarget!=undefined&&!isNaN(self.angleToTarget)){vector={x:speed*Math.sin(self.angleToTarget),y:-(speed*Math.cos(self.angleToTarget))}}}else if(ownerPlayer._stats.controlledBy=="human"){if(self.direction.x!=0&&self.direction.y!=0){speed=speed/1.41421356237}vector={x:self.direction.x*speed,y:self.direction.y*speed}}}if(!self._stats.ai||!self._stats.ai.enabled||ownerPlayer&&ownerPlayer._stats.controlledBy=="human"){if(self._stats.controls&&self._stats.controls.movementControlScheme=="followCursor"){if(!this.isMoving&&self.distanceToTarget>this.width()){this.startMoving()}else if(this.isMoving&&self.distanceToTarget<=this.width()){this.stopMoving()}}else{if(!this.isMoving&&(self.direction.x!=0||self.direction.y!=0)){this.startMoving()}else if(this.isMoving&&self.direction.x==0&&self.direction.y==0){this.stopMoving()}}}ige.unitBehaviourCount++;if(self.body&&vector&&(vector.x!=0||vector.y!=0)){if(self._stats.controls)switch(self._stats.controls.movementMethod){case"velocity":self.setLinearVelocity(vector.x,vector.y);break;case"force":self.applyForce(vector.x,vector.y);break;case"impulse":self.applyImpulse(vector.x,vector.y);break;}}}if(this._stats.controls&&this._stats.controls.mouseBehaviour.flipSpriteHorizontallyWRTMouse&&self.angleToTarget!=undefined){if(self.angleToTarget>0&&self.angleToTarget0){for(let i=0;i=self.quantityCost||self._stats.quantity==undefined||isNaN(self._stats.quantity)){return true}return false},use:function(){var self=this;var now=ige.now;var owner=self.getOwnerUnit();var player=owner&&owner.getOwner();var isUsed=false;if(!owner||self._stats.canBeUsedBy&&self._stats.canBeUsedBy.length>0&&self._stats.canBeUsedBy.indexOf(owner._stats.type)==-1||self._stats.type==="unusable"){return}if(self.hasQuantityRemaining()){ige.game.lastUsedItemId=self.id();if(self._stats.lastUsed+self._stats.fireRate0){var entity=entities.shift();if(entity&&entity._category=="unit"){entity.inflictDamage(damageData)}}}}}else if(self._stats.type=="consumable"){if(!self.quantityCost){self.quantityCost=1}attrData={attributes:{}};if(self._stats.bonus&&self._stats.bonus.consume){var unitAttributeBonuses=self._stats.bonus.consume.unitAttribute;if(unitAttributeBonuses){for(var attrId in unitAttributeBonuses){if(attrData.attributes){var newValue=owner.attribute.getValue(attrId)+parseFloat(unitAttributeBonuses[attrId]);attrData.attributes[attrId]=owner.attribute.update(attrId,newValue,true)}}}if(player&&player.attribute){var playerAttributeBonuses=self._stats.bonus.consume.playerAttribute;if(playerAttributeBonuses){for(attrId in playerAttributeBonuses){var newValue=player.attribute.getValue(attrId)+parseFloat(playerAttributeBonuses[attrId]);attrData.attributes[attrId]=player.attribute.update(attrId,newValue,true)}}if(ige.isServer&&self._stats&&self._stats.bonus&&self._stats.bonus.consume&&self._stats.bonus.consume.coin){}}if(ige.isServer){owner.streamUpdateData(attrData)}}self.stopUsing()}}}else{self.stopUsing()}if(isUsed&&ige.isClient){this.playEffect("use")}if(self._stats.quantity!=null||self._stats.quantity!=undefined){if(isUsed&&self._stats.quantity>0){self.updateQuantity(self._stats.quantity-self.quantityCost)}}},updateQuantity:function(qty){this._stats.quantity=qty;if(ige.isServer){if(this._stats.quantity==0&&this._stats.removeWhenEmpty===true){var ownerUnit=this.getOwnerUnit();this.remove();if(ownerUnit){ownerUnit.streamUpdateData([{itemIds:ownerUnit._stats.itemIds}])}}}else if(ige.isClient&&ige.client.selectedUnit==this.getOwnerUnit()){ige.itemUi.updateItemQuantity(this)}},canAffordItemCost:function(){var self=this;var ability=self._stats;var owner=self.getOwnerUnit();var canAffordCost=true;var player=owner&&owner.getOwner();if(ability.cost==undefined){return true}if(player&&owner&&ability.cost){for(var attrName in ability.cost.unitAttributes){var cost=ability.cost.unitAttributes[attrName];if(owner._stats.attributes[attrName]==undefined||owner._stats.attributes[attrName].value=owner._stats.inventorySize){self.unMount()}}break;case"scale":case"scaleBody":if(ige.isClient){self._stats.scale=newValue;self._scaleTexture()}break;case"hidden":if(ige.isClient){if(newValue){self.hide()}else{self.show()}}break;case"scaleBody":if(ige.isServer){if(self.jointsAttached){var attachedEntities={};for(var entityId in self.jointsAttached){var entity=self.jointsAttached[entityId];if(entityId!=self.id()){attachedEntities[entityId]=true}}}self._scaleBox2dBody(newValue)}break;case"quantity":self.updateQuantity(newValue);var owner=self.getOwnerUnit();if(ige.isClient&&ige.client.selectedUnit==owner){ige.itemUi.updateItemQuantity(self)}break;case"description":var owner=self.getOwnerUnit();if(ige.isClient&&ige.client.selectedUnit==owner){ige.itemUi.updateItemDescription(this)}break;case"name":var owner=self.getOwnerUnit();if(ige.isClient&&ige.client.selectedUnit==owner){ige.itemUi.updateItemInfo(this);ige.itemUi.updateItemDescription(this)}break;case"inventoryImage":var owner=self.getOwnerUnit();if(ige.isClient&&ige.client.selectedUnit==owner){ige.itemUi.updateItemSlot(this,this._stats.slotIndex)}break;case"inventorySlotColor":var owner=self.getOwnerUnit();if(ige.isClient&&ige.client.selectedUnit==owner){owner.inventory.update()}break;case"slotIndex":var owner=self.getOwnerUnit();if(ige.isClient&&owner){if(newValue>=owner._stats.inventorySize){self.unMount()}else{self.mount(ige.pixi.world)}}break;}}}},_behaviour:function(ctx){var self=this;var ownerUnit=this.getOwnerUnit();if(ownerUnit&&this._stats.stateId!="dropped"){rotate=ownerUnit.angleToTarget;if(self._stats.currentBody){if(self._stats.currentBody.jointType=="weldJoint"){rotate=ownerUnit._rotate.z}}self.anchoredOffset=self.getAnchoredOffset(rotate);var x=ownerUnit._translate.x+self.anchoredOffset.x;var y=ownerUnit._translate.y+self.anchoredOffset.y;self.translateTo(x,y);if(ige.isClient&&ige.client.selectedUnit==ownerUnit){if(self._stats.controls&&self._stats.controls.mouseBehaviour){if(self._stats.controls.mouseBehaviour.flipSpriteHorizontallyWRTMouse){if(rotate>0&&rotate0){if(this.textTimer){clearTimeout(this.textTimer)}var that=this;this.textTimerData={target:data.target};this.textTimer=setTimeout(function(){$(`.ui-text-${that.textTimerData.target}`).hide()},data.time)}},_onUpdateUiText:function(data){if(data.action=="show"){$(`.ui-text-${data.target}`).show()}else if(data.action=="hide"){$(`.ui-text-${data.target}`).hide()}else{$(`.ui-text-${data.target}`).html(data.value)}},_onAlertHighscore:function(data){},_onItem:function(data){var item=ige.$(data.id);if(item){if(item._category=="item"){var ownerUnit=item.getOwnerUnit();if(data.type=="use"&&ownerUnit&&ownerUnit!=ige.client.selectedUnit){item.use()}else if(data.type=="stop"){item.stopUsing()}else if(data.type=="reload"){item.reload()}}else{if(data.type=="hit"){item.effect.start("bulletHit")}}}},_onUi:function(data){switch(data.command){case"openItemShop":ige.shop.openModdShop("item");break;case"openUnitShop":ige.shop.openModdShop("unit");break;case"closeShop":ige.shop.closeShop();break;case"showMenuAndSelectCurrentServer":case"showMenu":ige.menuUi.showMenu();break;case"showMenuAndSelectBestServer":ige.menuUi.showMenu(true);break;case"showInputModal":ige.playerUi.showInputModal(data);break;case"showCustomModal":ige.playerUi.showCustomModal(data);break;case"openWebsite":ige.playerUi.openWebsite(data);break;case"showWebsiteModal":ige.playerUi.showWebsiteModal(data);break;case"showSocialShareModal":ige.playerUi.showSocialShareModal(data);break;case"showFriendsModal":ige.playerUi.showFriendsModal(data);break;case"shopResponse":ige.shop.purchaseWarning(data.type);break;}},_onPlayAd:function(data){var player=ige.client.myPlayer;if(typeof countAdImpression==="function"&&player&&!player._stats.isAdBlockEnabled){countAdImpression(gameId,"video")}ige.ad.play(data)},_onVideoChat:function(data){if(data.command){switch(data.command){case"joinGroup":switchRoom(data.groupId);break;case"leaveGroup":switchRoom(myID);break;}}console.log("videoChat",data)},_onUserJoinedGame:function(data){var user=data.user;var server=data.server;var game=data.game;var gameName=data.gameName;var gameSlug=data.gameSlug;var friend=null;if(typeof allFriends!="undefined"){for(var i in allFriends){var friendObj=allFriends[i];if(friendObj._id===user){friend=friendObj;break}}if(friend&&friend.local){var gameLink=$(`.${friend._id}-game-list`);var url=`/play/${gameSlug}?server=${server}&joinGame=true`;if(server){var friendName=friend.local.username;var message=`${friendName} is now playing ${gameName}Join`;ige.chat.postMessage({text:message,isHtml:true});if(gameLink){friend.currentServers=[{id:server,gameSlug:gameSlug,gameName:gameName}]}}else{friend.currentServers=[]}allFriends.sort(function(a,b){return b.currentServers.length-a.currentServers.length});renderAllFriendsPanel();renderFriendTabInGame()}}},_onBuySkin:function(skinHandle){$(`.btn-buy-skin[name='${skinHandle}']`).html("Purchased")},_onDevLogs:function(data){ige.variable.updateDevConsole(data)},_onTrade:function(msg,clientId){switch(msg.type){case"init":{var player=ige.$(msg.from);if(player&&player._category==="player"){ige.tradeUi.initiateTradeRequest(player)}break}case"start":{var playerA=ige.$(msg.between.playerA);var playerB=ige.$(msg.between.playerB);if(playerA&&playerA._category==="player"&&playerB&&playerB._category==="player"){ige.tradeUi.startTrading(playerA,playerB)}break}case"offer":{var from=ige.$(msg.from);var to=ige.$(msg.to);if(from&&to&&from.tradingWith===to.id()){ige.tradeUi.receiveOfferingItems(msg.tradeItems)}break}case"success":{var playerA=ige.$(msg.between.playerA);var playerB=ige.$(msg.between.playerB);delete playerA.tradingWith;delete playerB.tradingWith;delete playerA.isTrading;delete playerB.isTrading;$("#trade-div").hide();break}case"cancel":{var playerA=ige.$(msg.between.playerA);var playerB=ige.$(msg.between.playerB);delete playerA.tradingWith;delete playerB.tradingWith;delete playerA.isTrading;delete playerB.isTrading;$("#trade-div").hide();break}}},_onErrorLogs:function(logs){var element=document.getElementById("error-log-content");for(actionName in logs){var log=logs[actionName];element.innerHTML+=`
  • ${log}
  • `;ige.client.errorLogs.push(log);$("#dev-error-button").text(`Errors (${ige.client.errorLogs.length})`)}},_onSound:function(data){switch(data.cmd){case"playMusic":var music=ige.game.data.music[data.id];if(music){ige.sound.playMusic(music,undefined,undefined,data.id)}break;case"stopMusicForPlayer":case"stopMusic":ige.sound.stopMusic();break;case"playMusicForPlayer":var music=ige.game.data.music[data.music];if(music){ige.sound.playMusic(music,undefined,undefined,data.music)}break;case"playMusicForPlayerRepeatedly":var music=ige.game.data.music[data.music];if(music){ige.sound.playMusic(music,undefined,true,data.music)}break;case"playSoundForPlayer":var sound=ige.game.data.sound[data.sound];if(sound){var unit=ige.client.myPlayer&&ige.client.myPlayer.getSelectedUnit();ige.sound.playSound(sound,unit&&unit._translate||null,data.sound)}break;case"stopSoundForPlayer":ige.sound.stopSound(sound,data.sound);break;default:var soundData=ige.game.data.sound[data.id];ige.sound.playSound(soundData,data.position,data.id);}},_onParticle:function(data){if(data.eid&&data.pid){var entity=ige.$(data.eid);if(entity&&entity.particleEmitters[data.pid]&&entity._translate.x>ige.client.vp1.camera._translate.x-1000&&entity._translate.xige.client.vp1.camera._translate.y-1000&&entity._translate.yige.client.vp1.camera._translate.x-1000&&entity._translate.xige.client.vp1.camera._translate.y-1000&&entity._translate.y0){var method=all?"filter":"find";return ige.$$("player")[method](player=>{return player._stats&&clientIds.includes(player._stats.clientId)&&(all||currentUserId&&player._stats.userId!=currentUserId)})}},getUnitsByClientId:function(clientId){return ige.$$("unit").filter(function(unit){return unit._stats&&unit._stats.clientId==clientId}).reduce(function(partialUnits,unit){partialUnits[unit._id]=unit;return partialUnits},{})},getPlayerByUserId:function(userId){return ige.$$("player").find(function(player){return player._stats&&player._stats.userId==userId})},getPlayerByClientId:function(clientId){return ige.$$("player").find(function(player){return player._stats&&player._stats.clientId==clientId})},getAsset:function(assetType,assetId){try{var asset=this.data[assetType][assetId];return JSON.parse(JSON.stringify(asset))}catch(e){GameComponent.prototype.log(`getAsset ${assetType} ${assetId} ${e}`)}},secondsToHms:function(seconds){seconds=Number(seconds);var h=Math.floor(seconds/3600);var m=Math.floor(seconds%3600/60);var s=Math.floor(seconds%3600%60);var hDisplay=h>0?`${h}h `:"";var mDisplay=m>0?`${m}m `:"";var sDisplay=s>0?`${s}s`:"";return hDisplay+mDisplay+sDisplay}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=GameComponent}var MapComponent=$i_56.extend({classId:"MapComponent",componentId:"map",init:function(entity,options){var self=this;self.minimapLayers=[];self.debrisProperty=["x","y","height","width","rotation","visible","type","id","name","gid","type","density","friction","restitution"];self.layersZIndex={floor:0,floor2:1,walls:3,trees:4};if(ige.isClient){if(mode==="sandbox"){$("#debris-form").on("submit",function(e){e.preventDefault();self.onSubmit()});$("#debris-form").on("keypress",function(e){if(e.charCode===13){e.preventDefault();self.onSubmit()}});$("#debris-delete").on("click",function(e){e.preventDefault();var updatedDebris={deleteId:$("#debris-id").val()};self.updateDebrisToDb(updatedDebris)})}}},load:function(data){var self=this;if(data.layers){for(var i=0;i{region.deleteRegion()});for(var regionName in regions){if(!ige.regionManager.getRegionById(regionName)){var data=regions[regionName];if(data){data.id=regionName;new Region(data)}}}},createDebris:function(debrisLayer){var self=this;if(!debrisLayer)return;var cellSheets=[];for(var i=0;i",{id:`item-${i}`,name:i,class:`btn inventory-item-button p-0 ${mobileClass}`,role:"button"}).on("click",function(){var slotIndex=parseInt($(this).attr("name"))+1;if(ige.client.myPlayer){ige.client.myPlayer.control.keyDown("key",slotIndex)}}));$("#inventory-slots-key-stroke").append($("
    ",{id:`item-key-stroke-${i}`,name:`key-${i}`,class:"item-key-stroke"}));var item=this.getItemBySlotNumber(i+1);if(item){this.insertItem(item,i)}}this.createBackpack();this.createTradingSlots()}this.update()},createBackpack(){var entity=this._entity;var backpackSize=entity._stats.backpackSize;var mobileClass=ige.isMobile?"inventory-slot-mobile ":"inventory-slot ";if(backpackSize>0){this.updateBackpackButton(true);$("#backpack-items-div").html("");var inventorySize=this._entity._stats.inventorySize;for(var i=inventorySize;i",{class:"col-sm-4 margin-top-4"}).append($("
    ",{id:`item-${i}`,name:i,class:`btn inventory-item-button p-0 ${mobileClass}`,role:"button"})));var item=this.getItemBySlotNumber(i+1);if(item){this.insertItem(item,i)}}}else{this.updateBackpackButton(false)}},createTradingSlots:function(){var mobileClass=ige.isMobile?"inventory-slot-mobile ":"inventory-slot ";if(this._entity._stats.inventorySize){var totalInventorySize=this.getTotalInventorySize();var tradingSlots=$("#user-trading-slots");tradingSlots.html("");var html="";for(var i=totalInventorySize;i",{id:`item-${i}`,name:i,class:`btn btn-light inventory-item-button ${mobileClass}`,role:"button"}));ige.itemUi.updateItemSlot(undefined,i)}}},updateBackpackButton:function(show){var inventoryBtn=$("#open-inventory-button");if(show){inventoryBtn.show();setTimeout(function(){$("#backpack-wrapper").css({bottom:$("#my-score-div").height()+40})},1000)}else{inventoryBtn.hide()}},getSameItemsFromInventory:function(itemTypeId){var items=this._entity._stats.itemIds;return items&&items.filter(id=>{var item=ige.$(id);if(item&&item._stats&&item._stats.itemTypeId===itemTypeId){return true}})||[]},hasItem:function(itemTypeId){var sameItemTypesInInventory=this._entity.inventory.getSameItemsFromInventory(itemTypeId);return sameItemTypesInInventory.length>0},getQuantity:function(itemTypeId){var quantity=0;var sameItemTypesInInventory=this._entity.inventory.getSameItemsFromInventory(itemTypeId);if(sameItemTypesInInventory.length>0){if(sameItemTypesInInventory.length){for(var i=0;i=requiredQty},getFirstAvailableSlotForItem:function(itemData){var self=this;var itemTypeId=itemData.itemTypeId;var mappedSlots=itemData.controls&&Array.isArray(itemData.controls.permittedInventorySlots)?itemData.controls.permittedInventorySlots:undefined;var mappedSlot=undefined;if(mappedSlots!=undefined&&mappedSlots.length>0){for(var i=0;iquantity){return i+1}else{if(item._stats.quantity!=undefined){quantity-=item._stats.maxQuantity-item._stats.quantity}}}}}}for(var i=0;i=this._entity._stats.inventorySize&&(itemData.controls==undefined||itemData.controls.backpackAllowed==true||itemData.controls.backpackAllowed==undefined)){var itemId=self._entity._stats.itemIds[i];if(!(itemId&&ige.$(itemId))){return i+1}}}if(mappedSlot&&mappedSlots.length==1){self._entity.reasonForFailingToPickUpItem=`slot ${mappedSlot} is occupied`}return undefined},insertItem:function(item,slotIndex){var self=this;var unit=this._entity;if(slotIndex==undefined)slotIndex=self.getFirstAvailableSlotForItem();if(slotIndex!=undefined&&item&&unit.canCarryItem(item._stats)){if(ige.isServer){self._entity._stats.itemIds[slotIndex]=item.id();if(slotIndex!=self._entity.currentItemIndex){item._stats.slotIndex=slotIndex;item.hide()}}else if(ige.isClient&&self._entity._stats.clientId===ige.network.id()){var ownerPlayer=self._entity.getOwner();if(ownerPlayer){if(ownerPlayer._stats.selectedUnitId==self._entity.id()){item._stats.slotIndex=slotIndex;ige.itemUi.updateItemSlot(item,slotIndex)}}}ige.trigger&&ige.trigger.fire("unitPickedAnItem",{unitId:unit.id(),itemId:item.id()})}return slotIndex},getItemFromInventory:function(itemTypeId){var self=this;for(var k=0;k0&&slotIndex-1==i){$(`#item-${i}`).addClass("active")}else{$(`#item-${i}`).removeClass("active")}}},getTotalInventorySize:function(){this._entity._stats.backpackSize=this._entity._stats.backpackSize>0?this._entity._stats.backpackSize:0;return this._entity._stats.inventorySize+this._entity._stats.backpackSize}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=InventoryComponent}var SoundComponent=$i_56.extend({classId:"SoundComponent",componentId:"sound",init:function(){var self=this;self.musicFiles=[];self.preLoadedSounds={};self.preLoadedMusic={};if(ige.isClient){var soundSetting=localStorage.getItem("sound");var musicSetting=localStorage.getItem("music");if(soundSetting==undefined||soundSetting=="on"){localStorage.setItem("sound","on");self.toggleButton("sound","on")}else if(soundSetting=="off"){self.toggleButton("sound","off")}if(musicSetting==undefined||musicSetting=="on"){localStorage.setItem("music","on");self.toggleButton("music","on")}else if(musicSetting=="off"){self.toggleButton("music","off");if(self.musicCurrentlyPlaying){self.stopMusic()}}$("#sound-on").on("click",function(){self.toggleButton("sound","on");localStorage.setItem("sound","on")});$("#sound-off").on("click",function(){self.toggleButton("sound","off");localStorage.setItem("sound","off")});$("#music-on").on("click",function(){self.toggleButton("music","on");localStorage.setItem("music","on");if(self.musicCurrentlyPlaying){self.startMusic()}});$("#music-off").on("click",function(){self.toggleButton("music","off");localStorage.setItem("music","off");if(self.musicCurrentlyPlaying){self.stopMusic()}})}},toggleButton:function(type,mode){if(mode=="on"){$(`#${type}-on`).removeClass("btn-light").addClass("btn-success");$(`#${type}-off`).removeClass("btn-success").addClass("btn-light")}else{$(`#${type}-off`).removeClass("btn-light").addClass("btn-success");$(`#${type}-on`).removeClass("btn-success").addClass("btn-light")}},preLoadSound:function(){var self=this;for(var soundKey in ige.game.data.sound){var sound=ige.game.data.sound[soundKey];self.preLoadedSounds[soundKey]=document.createElement("audio");self.preLoadedSounds[soundKey].src=sound.file;if(sound.volume){self.preLoadedSounds[soundKey].volume=sound.volume/100}self.preLoadedSounds[soundKey].load()}},preLoadMusic:function(){var self=this;for(var musicKey in ige.game.data.music){var music=ige.game.data.music[musicKey];self.preLoadedMusic[musicKey]=document.createElement("audio");self.preLoadedMusic[musicKey].src=music.file;if(music.volume){self.preLoadedMusic[musicKey].volume=music.volume/100}self.preLoadedMusic[musicKey].load()}},getVolume:function(position,volume=0){var settingsVolume=parseFloat(localStorage.getItem("sound-volume"));settingsVolume=isNaN(settingsVolume)?1:settingsVolume/100;var distanceSoundShouldHeard=500;if(ige.game.data.settings&&ige.game.data.settings.camera&&ige.game.data.settings.camera.zoom&&ige.game.data.settings.camera.zoom.default){distanceSoundShouldHeard=ige.game.data.settings.camera.zoom.default*1.5}var vpBound=ige.pixi.viewport.getVisibleBounds();var myPosition={x:vpBound.x+vpBound.width/2,y:vpBound.y+vpBound.height/2};var xDistance=position.x-myPosition.x;var yDistance=position.y-myPosition.y;var distance=Math.sqrt(xDistance*xDistance+yDistance*yDistance);if(distance0){setTimeout(function(){unit.ability.cast(unitAbility.keyDown)},ige.client.inputDelay)}else{unit.ability.cast(unitAbility.keyDown)}}else if(key=="1"||key=="2"||key=="3"||key=="4"||key=="5"||key=="6"||key=="7"||key=="8"||key=="9"){var index=parseInt(key)-1;if(index0){setTimeout(function(){unit.ability.cast(unitAbility.keyUp)},ige.client.inputDelay)}else{unit.ability.cast(unitAbility.keyUp)}}}}if(ige.isClient){if(this.input[device][key]){ige.network.send("playerKeyUp",{device:device,key:key})}}if(this.input[device])this.input[device][key]=false},mouseMove:function(){var player=ige.client.myPlayer;if(player){if(ige.pixi&&ige.pixi.viewport){var vpTransform=[-ige.pixi.viewport.x/ige.pixi.viewport.scale.x,-ige.pixi.viewport.y/ige.pixi.viewport.scale.y];var mouseX=ige.client.mouseMove&&ige.client.mouseMove.clientX||0;var mouseY=ige.client.mouseMove&&ige.client.mouseMove.clientY||0;var currentMouseTransform=[vpTransform[0]+mouseX/ige.pixi.viewport.scale.x,vpTransform[1]+mouseY/ige.pixi.viewport.scale.y];this.newMousePosition=currentMouseTransform}else{this.newMousePosition=[0,0]}}},_behaviour:function(ctx){var self=this;if(ige.isClient){for(device in self.input){for(key in self.input[device]){if(ige.input.actionState(key)){if(self.input[device][key]==false){if(ige.isMobile&&device=="mouse"){}else{self.keyDown(device,key)}}}else{if(self.input[device][key]==true){if(ige.isMobile&&device=="mouse"){}else{self.keyUp(device,key)}}}}}self.mouseMove();if(ige._currentTime-self.lastInputSent>100){self.sendPlayerInput=true;self.lastInputSent=ige._currentTime}if(self.newMousePosition&&(self.newMousePosition[0]!=self.lastMousePosition[0]||self.newMousePosition[1]!=self.lastMousePosition[1])){if(!ige.isMobile){if(ige._mouseAbsoluteTranslation&&ige._mouseAbsoluteTranslation[0]&&ige._mouseAbsoluteTranslation[1]){var centerOfScreen={};centerOfScreen.innerWidth=window.innerWidth/2;centerOfScreen.innerHeight=window.innerHeight/2;var angle=0;if(centerOfScreen&&ige._mouseAbsoluteTranslation[0]!=centerOfScreen.innerWidth&¢erOfScreen.innerHeight!=ige._mouseAbsoluteTranslation[1]){angle=Math.atan2(ige._mouseAbsoluteTranslation[0]-centerOfScreen.innerWidth,centerOfScreen.innerHeight-ige._mouseAbsoluteTranslation[1])}angle=parseFloat(angle.toPrecision(5));if(self.sendPlayerInput)ige.network.send("playerAbsoluteAngle",angle);if(ige.client.myPlayer){ige.client.myPlayer.absoluteAngle=angle}self.absoluteAngle=angle}if(ige.client&&ige.client.myPlayer){ige.client.myPlayer.control.input.mouse.x=self.newMousePosition[0];ige.client.myPlayer.control.input.mouse.y=self.newMousePosition[1]}if(self.sendPlayerInput)ige.network.send("playerMouseMoved",self.newMousePosition)}self.lastMousePosition=self.newMousePosition}var unit=ige.client.selectedUnit;if(ige.physics&&ige.game.cspEnabled&&unit){var x=unit._translate.x.toFixed(0);var y=unit._translate.y.toFixed(0);if(self.sendPlayerInput||self.lastPositionSent==undefined||self.lastPositionSent[0]!=x||self.lastPositionSent[1]!=y){var pos=[x,y];ige.network.send("playerUnitMoved",pos);self.lastPositionSent=pos}}self.sendPlayerInput=false}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=ControlComponent}var MobileControlsComponent=$i_56.extend({classId:"MobileControlsComponent",componentId:"mobileControls",init:function(entity){$i_56.prototype.init.call(this);var self=this;this.isSingleGame=this.isSingleGameMode();this._entity=entity;this.debug=false;this.controls=[];var canvas=document.getElementById("igeFrontBuffer");this.canvas={height:canvas.style.height&&parseInt(canvas.style.height.replace("px",""))||canvas.height,width:canvas.style.width&&parseInt(canvas.style.width.replace("px",""))||canvas.width};$(window).on("orientationchange load resize",function(){if(ige.mobileControls){if(ige.client&&ige.client.myPlayer&&ige.network.id()==ige.client.myPlayer._stats.clientId){var unit=ige.$(ige.client.myPlayer._stats.selectedUnitId);if(unit&&unit._stats.controls){var unitAbilities=unit._stats.controls.abilities;if(unitAbilities){ige.mobileControls.configure(unitAbilities)}}}}});this.id();ige.entityTrack.trackEntityById[this.id()]=this;self.addBehaviour("mobileControl",self._behaviour)},getParameterByName:function(name,url){if(!url)url=window.location.href;name=name.replace(/[\[\]]/g,"\\$&");var regex=new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);var results=regex.exec(url);if(!results)return null;if(!results[2])return"";return decodeURIComponent(results[2].replace(/\+/g," "))},isSingleGameMode:function(){var s=this.getParameterByName("s");if(parseInt(s)==1)return true;return false},attach:function(mountScene){if(!ige.isMobile)return;noAds=true;if(this.isSingleGame){$("#back-to-game-selection-button").hide()}else{$("#back-to-game-selection-button").show()}if(this.isPortrait()){$("#chat-input-field-div").css({width:"80%"})}else{$("#chat-input-field-div").css({width:"60%"})}var self=this;this.guide=new $i_56().depth(100).width(960).height(540).mount(this.mobileControls);return this},clearControls:function(newAbilities){var self=this;for(ix in this.controls){var uppercaseKey=ix;if(newAbilities&&!newAbilities[uppercaseKey]){var button=self.controls[uppercaseKey];if(typeof button==="object"&&button){button.destroy()}delete this.controls[uppercaseKey]}}},configure:function(abilities){if(!ige.isMobile||!abilities)return;$("#show-chat").hide();$("#chat-box").hide();$("#chat-box").css({top:"10vh",fontSize:"x-small"});$("#chat-box").css("min-width","200px");$("#chat-history").css("width","200px");$("#dev-console").hide();$("#modd-item-shop-modal").css({zIndex:9050});ige.scoreboard.hideScores();var self=this;this.clearControls(abilities);Object.keys(abilities).forEach(function(key,index){var ability=abilities[key];if(ability.mobilePosition&&!self.controls[key]){var x=ability.mobilePosition.x*2;var y=ability.mobilePosition.y*2;self.addControl(key,x,y,75,64,ability)}})},upPressed:function(){if(this.debug)console.log("UP PRESSED");var unit=ige.client.myPlayer.getSelectedUnit();unit.ability.moveUp();if(ige.isClient){ige.network.send("playerKeyDown",{device:"key",key:"w"})}},downPressed:function(){if(this.debug)console.log("DOWN PRESSED");var unit=ige.client.myPlayer.getSelectedUnit();unit.ability.moveDown();if(ige.isClient){ige.network.send("playerKeyDown",{device:"key",key:"s"})}},leftPressed:function(){if(this.debug)console.log("LEFT PRESSED");var unit=ige.client.myPlayer.getSelectedUnit();unit.ability.moveLeft();if(ige.isClient){ige.network.send("playerKeyDown",{device:"key",key:"a"})}},rightPressed:function(){if(self.debug)console.log("RIGHT PRESSED");var unit=ige.client.myPlayer.getSelectedUnit();unit.ability.moveRight();if(ige.isClient){ige.network.send("playerKeyDown",{device:"key",key:"d"})}},upReleased:function(){if(this.debug)console.log("UP RELEASED");var unit=ige.client.myPlayer.getSelectedUnit();if(unit.direction.y==-1)unit.ability.stopMovingY();if(ige.isClient){ige.network.send("playerKeyUp",{device:"key",key:"w"})}},downReleased:function(){if(this.debug)console.log("DOWN RELEASED");var unit=ige.client.myPlayer.getSelectedUnit();if(unit.direction.y==1)unit.ability.stopMovingY();if(ige.isClient){ige.network.send("playerKeyUp",{device:"key",key:"s"})}},leftReleased:function(){if(this.debug)console.log("LEFT RELEASED");var unit=ige.client.myPlayer.getSelectedUnit();if(unit.direction.x==-1)unit.ability.stopMovingX();if(ige.isClient){ige.network.send("playerKeyUp",{device:"key",key:"a"})}},rightReleased:function(){if(this.debug)console.log("RIGHT RELEASED");var unit=ige.client.myPlayer.getSelectedUnit();if(unit.direction.x==1)unit.ability.stopMovingX();if(ige.isClient){ige.network.send("playerKeyUp",{device:"key",key:"d"})}},addControl:function(key,x,y,w,h,ability){w=w||128;h=h||128;var self=this;var isStick=key=="movementWheel"||key=="lookWheel"||key=="lookAndFireWheel";if(isStick){if(key=="movementWheel"){let moveStick=new Joystick({outerScale:{x:1.2,y:1.2},innerScale:{x:0.5,y:0.5},onChange:data=>{if(ige.client.myPlayer){var compassAngle=(360-(data.angle-90))%360;var tolerance=12;var isUp=compassAngle<=90-tolerance||compassAngle>=270+tolerance;var isDown=compassAngle>=90+tolerance&&compassAngle<=270-tolerance;var isLeft=compassAngle<=360-tolerance&&compassAngle>=180+tolerance;var isRight=compassAngle>=tolerance&&compassAngle<=180-tolerance;if(data.power>0.5){if(isUp&&moveStick._isUp==false){self.upPressed()}if(!isUp&&moveStick._isUp==true){self.upReleased()}if(isDown&&moveStick._isDown==false){self.downPressed()}if(!isDown&&moveStick._isDown==true){self.downReleased()}if(isLeft&&moveStick._isLeft==false){self.leftPressed()}if(!isLeft&&moveStick._isLeft==true){self.leftReleased()}if(isRight&&moveStick._isRight==false){self.rightPressed()}if(!isRight&&moveStick._isRight==true){self.rightReleased()}moveStick._isUp=isUp;moveStick._isDown=isDown;moveStick._isLeft=isLeft;moveStick._isRight=isRight}else{if(moveStick._isUp){self.upReleased()}if(moveStick._isLeft){self.leftPressed()}if(moveStick._isDown){self.downReleased()}if(moveStick._isRight){self.rightReleased()}moveStick._isUp=false;moveStick._isDown=false;moveStick._isLeft=false;moveStick._isRight=false}}},onEnd:()=>{var unit=ige.client.myPlayer.getSelectedUnit();if(moveStick._isUp){self.upReleased()}if(moveStick._isLeft){self.leftReleased()}if(moveStick._isDown){self.downReleased()}if(moveStick._isRight){self.rightReleased()}moveStick._isUp=false;moveStick._isDown=false;moveStick._isLeft=false;moveStick._isRight=false}});ige.pixi.mobileControls.addChild(moveStick);moveStick.position.set(x+32,y+12);moveStick._isUp=false;moveStick._isDown=false;moveStick._isLeft=false;moveStick._isRight=false}if(key=="lookWheel"){let lookStick=new Joystick({outerScale:{x:1.2,y:1.2},innerScale:{x:0.5,y:0.5},onChange:data=>{if(ige.client.myPlayer){var compassAngle=-(data.angle-90);var unitTranslate=ige.client.myPlayer.getSelectedUnit()._translate;var mx=unitTranslate.x+Math.sin(compassAngle/360*2*Math.PI)*10*data.power;var my=unitTranslate.y-Math.cos(compassAngle/360*2*Math.PI)*10*data.power;ige.client.myPlayer.control.input.mouse.x=mx;ige.client.myPlayer.control.input.mouse.y=my;ige.client.myPlayer.absoluteAngle=compassAngle;ige.network.send("playerMouseMoved",[mx,my]);ige.network.send("playerAbsoluteAngle",compassAngle)}}});ige.pixi.mobileControls.addChild(lookStick);lookStick.position.set(x+32,y+12)}if(key=="lookAndFireWheel"){let fireStick=new Joystick({redFireZone:true,outerScale:{x:1.2,y:1.2},innerScale:{x:0.5,y:0.5},onChange:data=>{if(ige.client.myPlayer){var compassAngle=-(data.angle-90);var unitTranslate=ige.client.myPlayer.getSelectedUnit()._translate;var mx=unitTranslate.x+Math.sin(compassAngle/360*2*Math.PI)*10*data.power;var my=unitTranslate.y-Math.cos(compassAngle/360*2*Math.PI)*10*data.power;ige.client.myPlayer.control.input.mouse.x=mx;ige.client.myPlayer.control.input.mouse.y=my;ige.client.myPlayer.absoluteAngle=compassAngle;ige.network.send("playerMouseMoved",[mx,my]);ige.network.send("playerAbsoluteAngle",compassAngle);if(data.power>0.75){ige.client.myPlayer.control.keyDown("mouse","button1")}else{ige.client.myPlayer.control.keyUp("mouse","button1")}}},onEnd:()=>{if(ige.client.myPlayer){ige.client.myPlayer.control.keyUp("mouse","button1")}}});ige.pixi.mobileControls.addChild(fireStick);fireStick.position.set(x+32,y+12)}}else{var text=key.toUpperCase();var newButton=new PIXI.Sprite.from("https://cache.modd.io/asset/spriteImage/1549614640644_button1.png?version=123",{crossOrigin:true});ige.pixi.mobileControls.addChild(newButton);newButton.width=w;newButton.height=h;newButton.x=x;newButton.y=y;newButton._key=key.toLowerCase();var iconUrl=null;if(text=="BUTTON1")iconUrl="https://cache.modd.io/asset/spriteImage/1610494864771_fightFist_circle.png";if(iconUrl){var icon=new PIXI.Sprite.from(iconUrl,{crossOrigin:true});ige.pixi.mobileControls.addChild(icon);icon.scale.set(0.5);icon.anchor.set(0.5);icon.position.set(x+w/2,y+h/2)}else{var label=new PIXI.Text(text,{fontFamily:"Arial",fontSize:24,fill:16777215,align:"center"});ige.pixi.mobileControls.addChild(label);label.anchor.set(0.5);label.position.set(x+w/2,y+h/2)}newButton.isButton=true;newButton.interactive=true;newButton.alpha=0.6;newButton.on("touchstart",function(event){if(newButton._isClicked)return;newButton._isClicked=true;event.stopPropagation();let texture=PIXI.Texture.from("https://cache.modd.io/asset/spriteImage/1549614658007_button2.png?version=123",{crossOrigin:true});newButton.texture=texture;if(newButton._key){ige.network.send("playerKeyDown",{device:"key",key:newButton._key})}});newButton.on("touchend",function(event){if(!newButton._isClicked)return;newButton._isClicked=false;event.stopPropagation();let texture=PIXI.Texture.from("https://cache.modd.io/asset/spriteImage/1549614640644_button1.png?version=123",{crossOrigin:true});newButton.texture=texture;if(newButton._key){ige.network.send("playerKeyUp",{device:"key",key:newButton._key})}})}},isIframe(){try{return window.self!==window.top}catch(e){return true}},isPortrait:function(){return this.canvas.width=that.outerRadius*that.outerRadius){calRadius=that.outerRadius}else{calRadius=that.outerRadius-that.innerRadius}let direction=Direction.LEFT;if(sideX==0){if(sideY>0){centerPoint.set(0,sideY>that.outerRadius?that.outerRadius:sideY);angle=270;direction=Direction.BOTTOM}else{centerPoint.set(0,-(Math.abs(sideY)>that.outerRadius?that.outerRadius:Math.abs(sideY)));angle=90;direction=Direction.TOP}that.inner.position=centerPoint;power=that.getPower(centerPoint);if(that.settings.onChange){that.settings.onChange({angle,direction,power})}return}if(sideY==0){if(sideX>0){centerPoint.set(Math.abs(sideX)>that.outerRadius?that.outerRadius:Math.abs(sideX),0);angle=0;direction=Direction.LEFT}else{centerPoint.set(-(Math.abs(sideX)>that.outerRadius?that.outerRadius:Math.abs(sideX)),0);angle=180;direction=Direction.RIGHT}that.inner.position=centerPoint;power=that.getPower(centerPoint);if(that.settings.onChange){that.settings.onChange({angle,direction,power})}return}let tanVal=Math.abs(sideY/sideX);let radian=Math.atan(tanVal);angle=radian*180/Math.PI;let centerX=0;let centerY=0;if(sideX*sideX+sideY*sideY>=that.outerRadius*that.outerRadius){centerX=that.outerRadius*Math.cos(radian);centerY=that.outerRadius*Math.sin(radian)}else{centerX=Math.abs(sideX)>that.outerRadius?that.outerRadius:Math.abs(sideX);centerY=Math.abs(sideY)>that.outerRadius?that.outerRadius:Math.abs(sideY)}if(sideY<0){centerY=-Math.abs(centerY)}if(sideX<0){centerX=-Math.abs(centerX)}if(sideX>0&&sideY<0){}else if(sideX<0&&sideY<0){angle=180-angle}else if(sideX<0&&sideY>0){angle=angle+180}else if(sideX>0&&sideY>0){angle=360-angle}centerPoint.set(centerX,centerY);power=that.getPower(centerPoint);direction=that.getDirection(centerPoint);that.inner.position=centerPoint;if(that.settings.onChange){that.settings.onChange({angle,direction,power})}}this.on("pointerdown",onDragStart).on("pointerup",onDragEnd).on("pointerupoutside",onDragEnd).on("pointermove",onDragMove)}getPower(centerPoint){const a=centerPoint.x-0;const b=centerPoint.y-0;return Math.min(1,Math.sqrt(a*a+b*b)/this.outerRadius)}getDirection(center){let rad=Math.atan2(center.y,center.x);if(rad>=-Math.PI/8&&rad<0||rad>=0&&rad=Math.PI/8&&rad<3*Math.PI/8){return Direction.BOTTOM_RIGHT}else if(rad>=3*Math.PI/8&&rad<5*Math.PI/8){return Direction.BOTTOM}else if(rad>=5*Math.PI/8&&rad<7*Math.PI/8){return Direction.BOTTOM_LEFT}else if(rad>=7*Math.PI/8&&rad=-Math.PI&&rad<-7*Math.PI/8){return Direction.LEFT}else if(rad>=-7*Math.PI/8&&rad<-5*Math.PI/8){return Direction.TOP_LEFT}else if(rad>=-5*Math.PI/8&&rad<-3*Math.PI/8){return Direction.TOP}else{return Direction.TOP_RIGHT}}}var shutdownMessages=[{checkpoint:1,message:"2 hours",timeMS:120*60000},{checkpoint:2,message:"1 hour",timeMS:60*60000},{checkpoint:3,message:"30 minutes",timeMS:30*60000},{checkpoint:4,message:"15 minutes",timeMS:15*60000},{checkpoint:5,message:"5 minutes",timeMS:5*60000},{checkpoint:6,message:"1 minute",timeMS:1*60000}];var TimerComponent=$i_56.extend({classId:"TimerComponent",componentId:"timer",init:function(){var self=this;if(ige.isServer){self.emptyTimeLimit=self.getTimeLimit();self.startedAt=new Date(ige.server.startedOn);console.log("initialized timer component",self.startedAt);self.now=self.serverEmptySince=self.startedAt}},getTimeLimit:function(){let timeLimitMin=10;return timeLimitMin*60*1000},getLifeSpan:function(){var maxLifeSpan=6*60*60*1000;var lifeSpan=ige.server.lifeSpan;if(lifeSpan>maxLifeSpan){lifeSpan=maxLifeSpan}return lifeSpan},startGameClock:function(){var self=this;console.log(new Date,"gameClock started");self.shutdownMessageCheckpoint=-1;var everySecond=setInterval(function(){self.now=Date.now();if(ige.isServer){self.lastTick=self.now;ige.trigger.fire("secondTick");var lifeSpan=self.getLifeSpan();var age=self.now-self.startedAt;var messageToBroadcast=shutdownMessages.find(function(messageDetails){return age>lifeSpan-messageDetails.timeMS&&self.shutdownMessageCheckpoint1){self.currentPagination--}}else{self.currentPagination=parseInt(buttonPressed)}self.paginationForSkins()});$(document).on("click",".btn-purchase-item",function(){var isItemRequirementSetisfied=$(this).attr("requirementsSatisfied")=="true";var isItemAffordable=$(this).attr("isItemAffordable")=="true";var name=$(this).attr("name");if(!isItemRequirementSetisfied){self.purchaseWarning("requirement",name);return}if(!isItemAffordable){self.purchaseWarning("price",name);return}self.purchase($(this).attr("id"))});$(document).on("click",".btn-purchase-unit",function(){$("#modd-item-shop-modal").modal("hide");self.purchaseUnit($(this).attr("id"))});$("#modd-item-shop-modal").on("hidden.bs.modal",function(){$(".popover").remove()});$(document).on("click",".btn-purchase-purchasable",function(){if($(this).hasClass("disabled"))return;var itemDom=$(this);var name=itemDom[0].dataset.purchasable;var price=isNaN(parseFloat(itemDom[0].dataset.price))?itemDom[0].dataset.price:parseFloat(itemDom[0].dataset.price);var isUnauthenticated=itemDom[0].dataset.unauthenticated;if(isUnauthenticated==="true"&&!(price==="facebook"||price==="twitter")){$("#login-modal").modal("show");return}var hasSharedDefer=$.Deferred();if(price<=0){promise=$.ajax({url:`/api/user/has-shared/${ige.game.data.defaultData.parentGame||ige.client.server.gameId}`,dataType:"html",type:"GET",success:function(data){var response=JSON.parse(data);if(response.status==="success"){hasSharedDefer.resolve(response.message)}else{hasSharedDefer.reject(response.message)}},error:function(req,status,err){hasSharedDefer.reject(err)}})}else{hasSharedDefer.resolve(true)}hasSharedDefer.promise().then(function(hasShared){if(hasShared){var itemId=itemDom.attr("id");var gameData=ige.game.data.defaultData;if(price==="facebook"||price==="twitter"){var item={value:gameData._id,type:"game"};var from="shopModal";if(price==="facebook"){var config={url:location.href,caption:`Join me at ${gameData.title}`,image:gameData.cover?gameData.cover.replace(" ","%20"):undefined};shareOnFacebook(item,from,config,function(response){if(response){$(`[id=${itemId}][data-price=facebook]`).addClass("disabled");self.buySkin(itemId,"facebook")}})}else if(price==="twitter"){}}else{$("#purchasable-purchase-modal").data("purchasable",itemId);$("#purchasable-purchase-modal").modal("show")}}else{$(".share-modal").modal("show")}}).catch(function(err){console.error(err)})});$(document).on("click","button.btn-equip",function(){var button=$(this);$.ajax({url:`/api/user/equip/${ige.game.data.defaultData.parentGame||ige.client.server.gameId}/${button.attr("id")}`,dataType:"html",type:"POST",success:function(data){var response=JSON.parse(data);if(response.status=="success"){self.updateModdShop();if(!ige.client.myPlayer._stats.purchasables||!(ige.client.myPlayer._stats.purchasables instanceof Array))ige.client.myPlayer._stats.purchasables=[];var equipedPurchasable=response.message;var myUnit=ige.$(ige.client.myPlayer._stats.selectedUnitId);ige.network.send("equipSkin",equipedPurchasable)}else if(response.status=="error"){if(!response.message.includes("No matching document found")){alert(response.message)}}}})});$(document).on("click","button.btn-unequip",function(){var button=$(this);var unEquipedId=button.attr("id");$.ajax({url:`/api/user/unequip/${ige.game.data.defaultData.parentGame||ige.client.server.gameId}/${unEquipedId}`,dataType:"html",type:"POST",success:function(data){var response=JSON.parse(data);if(response.status=="success"){var myUnit=ige.$(ige.client.myPlayer._stats.selectedUnitId);ige.network.send("unEquipSkin",unEquipedId);self.updateModdShop()}else if(response.status=="error"){alert(response.message)}}})})}},loadUserPurchases:function(){let self=this;$.ajax({url:`/api/user/${gameId}/purchases`,type:"GET",success:function(response){if(response.status=="success"){userPurchases=response.message||[];var userPurchasedItemIds=userPurchases.reduce(function(partial,purchase){partial[purchase._id]=true;return partial},{});var purchasableItems=typeof purchasables.filter==="function"&&purchasables.filter(function(purchasable){return!userPurchasedItemIds[purchasable._id]})||[];purchasableItems=purchasableItems.slice(0,4);purchasableItems.forEach(function(purchasable,index){let html=`
    `+"
    "+` `+"\t
    "+"\t
    ";if(purchasable.soldForSocialShare){html+=self.getTwitterBtnHtml(purchasable)}else{html+=` "}html+="\t
    "+"
    ";var skin=$(html);$("#skins-list").append(skin)});$("#loading-skins").addClass("d-none");$("#skins-list").removeClass("d-none").addClass("row")}else if(response.status=="error"){$("#loading-skins").addClass("d-none");console.log(response.message)}}})},purchaseWarning:function(type,itemName){var text="";switch(type){case"requirement":text=`${itemName} requirements not met.`;break;case"price":text=`Cannot afford ${itemName}.`;break;case"inventory_full":text="No room in inventory.";break;case"purchase":text="Item purchased.";break;}if($("#modd-item-shop-modal").hasClass("show")){$("#item-purchase-warning").html(text);$("#item-purchase-warning").show();setTimeout(function(){$("#item-purchase-warning").fadeOut()},800)}},buySkin:function(itemId,sharedOn=""){var self=this;$.ajax({url:`/api/user/purchase/${ige.game.data.defaultData.parentGame||ige.client.server.gameId}/${itemId}?sharedOn=${sharedOn}`,dataType:"html",type:"POST",success:function(data){var response=JSON.parse(data);if(response.status=="success"){$(".player-coins").html(parseInt(response.remaining_coins));if(ige.client.myPlayer){ige.client.myPlayer._stats.coins=parseInt(response.remaining_coins)}$("#purchasable-purchase-modal").modal("hide");self.updateModdShop();self.updateSkinList(itemId);var details=$(`.btn-purchase-purchasable#${itemId}`);var purchasableInfo=details.find(".purchasable-details");if(purchasableInfo&&purchasableInfo.html){details.removeClass("btn-purchase-purchasable");purchasableInfo.html("")}}else if(response.status=="error"){if(!response.message.includes("No matching document found")){var error=`
    ${response.message}
    `;$("#purchasable-purchase-modal .purchasable-info-container").html(error)}}}})},openModdShop:function(tabSelected,elementIdToFocus){if(ige.isClient){var self=this;this.hideEmptyTabs();if(tabSelected&&tabSelected=="item"&&$("[id=item]").css("display")=="none"){tabSelected="unit"}if(tabSelected&&tabSelected=="unit"&&$("[id=unit]").css("display")=="none"){tabSelected="item"}this.updateModdShop(tabSelected);if(elementIdToFocus){$("#modd-shop-modal").one("shown.bs.modal",function(){$(this).animate({scrollTop:$(elementIdToFocus).offset().top-100},1000,function(){$(elementIdToFocus).effect("highlight",{},3000)})})}$("#modd-shop-modal").modal({show:true,keyboard:true})}},hideEmptyTabs:function(){var self=this;var unitArr=[];var itemArr=[];if(!ige.game.data.unitTypes){$("[id=unit]").hide();$("[id=unitSkins]").hide()}else{for(unitId in ige.game.data.unitTypes){var unit=ige.game.data.unitTypes[unitId];if(unit.isPurchasable){unitArr.push(unit)}}if(unitArr.length===0){$("[id=unit]").hide()}}if(!ige.game.data.itemTypes){$("[id=item]").hide();$("[id=itemSkins]").hide()}else{for(itemId in ige.game.data.itemTypes){var item=ige.game.data.itemTypes[itemId];if(item.isPurchasable){itemArr.push(item)}}if(itemArr.length===0){$("[id=item]").hide()}else if(unitArr.length===0){if(self.shopType===undefined){self.shopType="item";$("[id=item]").addClass("active")}}}$.ajax({url:`/api/game/${ige.game.data.defaultData.parentGame||ige.client.server.gameId}/shopCount`,type:"GET",success:function(data){if(data.status==="success"){if(data.message){if(!data.message.unitCount||data.message.unitCount.length===0){$("[id=unitSkins]").hide()}else if(data.message.unitCount){for(var i in ige.game.data.unitTypes){var total=data.message.unitCount.filter(function(unit,key){if(unit&&unit.target&&unit.target.key===i)return true});if(total){total=total.length}else{total=0}self.unitSkinCount[i]=total}}if(!data.message.itemCount||data.message.itemCount.length===0){$("[id=itemSkins]").hide()}else if(data.message.itemCount){for(var i in ige.game.data.itemTypes){var total=data.message.itemCount.filter(function(item,key){if(item&&item.target&&item.target.key===i)return true});if(total){total=total.length}else{total=0}self.itemSkinCount[i]=total}}self.checkIfAnyTabSelected()}}}})},getTwitterBtnHtml:function(item){var sharedOn=item.sharedOn||{};var title=item.title||item.name;var sharedOnTwitter=sharedOn.twitter?"disabled":"";var gameId=ige.game.data.defaultData._id;var textToTweet=`Join me in ${ige.game.data.defaultData.title} (${location.href})`;var hashTags=["games","moddio"];var mentions=["moddio"];var twitterUrl=`https://twitter.com/intent/tweet?text=${textToTweet}&hashtags=${hashTags.join(",")}&via=${mentions.join(",")}`;return``},buttonForSocialShare:function(item,unauthenticated){var btnHtml="";var sharedOn=item.sharedOn||{};var sharedOnFacebook=sharedOn.facebook?"disabled":"";var gameId=ige.game.data.defaultData._id;if(item){var title=item.title||item.name;btnHtml+="
    ";btnHtml+=this.getTwitterBtnHtml(item);btnHtml+="
    "}return btnHtml},updateModdShop:function(tabSelected){var self=this;if(ige.isMobile){$(".open-coin-shop-button").hide()}var keyList=$("
      ",{class:"list-group"});var isFirstKey=true;if(self.shopType===undefined){self.shopType="unit"}if(tabSelected){self.shopType=tabSelected}if(self.shopType=="unitSkins"){$(".shop-navbar .nav-link").each(function(){$(this).removeClass("active")});$("#unitSkins").addClass("active");var unitKeys=Object.keys(ige.game.data.unitTypes);unitKeys=unitKeys.sort();for(var p=0;p0){if(!self.shopKey&&isFirstKey){self.shopKey=key}keyDiv=$("
    • ",{class:`list-group-item list-group-item-action cursor-pointer ${key==self.shopKey?"active":""}`,text:`${ige.game.data.unitTypes[key].name} (${self.unitSkinCount[key]})`,name:key}).on("click",function(){self.shopKey=$(this).attr("name");$("#modd-shop-modal .shop-items").html("");$(".list-group.item").each(function(){$(this).removeClass("active")});$(this).addClass("active");self.updateModdShop()});keyList.append(keyDiv);var isFirstKey=false}}$(".shop-sidebar").html(keyList).show()}else if(self.shopType=="itemSkins"){$(".shop-navbar .nav-link").each(function(){$(this).removeClass("active")});$("#itemSkins").addClass("active");for(key in ige.game.data.itemTypes){$("#modd-shop-modal .shop-items").html("");if(self.itemSkinCount[key]>0){if(!self.shopKey&&isFirstKey){self.shopKey=key}keyDiv=$("
    • ",{class:`list-group-item ${key==self.shopKey?"active":""}`,text:`${ige.game.data.itemTypes[key].name} (${self.itemSkinCount[key]})`,name:key}).on("click",function(){self.shopKey=$(this).attr("name");$("#modd-shop-modal .shop-items").html("");$(".list-group.item").each(function(){$(this).removeClass("active")});$(this).addClass("active");self.updateModdShop()});keyList.append(keyDiv);var isFirstKey=false}}$(".shop-sidebar").html(keyList).show()}else if(self.shopType=="item"){$(".shop-sidebar").hide()}else if(self.shopType=="unit"){$(".shop-sidebar").hide()}if(self.shopType=="unitSkins"||self.shopType=="itemSkins"){$.ajax({url:`/api/game/${ige.game.data.defaultData.parentGame||ige.client.server.gameId}/shop`,data:{type:self.shopType==="unitSkins"?"unit":"item",key:self.shopKey,page:self.shopPage},dataType:"html",type:"GET",success:function(data){var items=JSON.parse(data).message;var groupedItems={purchased:[],notPurchased:[]};items.forEach(function(item){if(item.status=="not_purchased"){groupedItems.notPurchased.push(item)}else{groupedItems.purchased.push(item)}});self.skinItems=groupedItems.purchased.concat(groupedItems.notPurchased);self.currentPagination=1;self.paginationForSkins()}})}},updateSkinList:function(itemId){debugger;var skinItemActionButton=$(`#skin-list-${itemId} .action-button-container`);skinItemActionButton.html("")},checkIfAnyTabSelected:function(){var anyTabSelected=false;$(".shop-navbar .nav-link").each(function(){if($(this).hasClass("active")&&$(this).css("display")!="none"){anyTabSelected=true;return false}});if(!anyTabSelected){var self=this;$(".shop-navbar .nav-link").each(function(){if($(this).css("display")!="none"){self.shopType=$(this)[0].id;self.updateModdShop(self.shopType);return false}})}},isItemRequirementSetisfied:function(req,priceAttr){var ownerPlayer=ige.client.myPlayer;var playerTypeAttribute=ownerPlayer._stats.attributes;if(playerTypeAttribute[priceAttr]){switch(req.type){case"atmost":if(playerTypeAttribute[priceAttr].value>req.value){return false}break;case"exactly":if(playerTypeAttribute[priceAttr].value!=req.value){return false}break;case"atleast":default:if(playerTypeAttribute[priceAttr].value${item.description}

      `}if(shopItem&&typeof shopItem.requirement==="object"){var requirements="";for(var priceAttr in shopItem.requirement.playerAttributes){var req=shopItem.requirement.playerAttributes[priceAttr];var requirementsSatisfied=self.isItemRequirementSetisfied(req,priceAttr)&&"text-success"||"text-danger";requirements+=`

      `;requirements+=req.value;requirements+=" ";requirements+=ige.game.data.attributeTypes[priceAttr]&&ige.game.data.attributeTypes[priceAttr].name||ownerPlayer._stats.attributes[priceAttr]&&ownerPlayer._stats.attributes[priceAttr].name;requirements+="

      "}var requiredItemTypesKeys=Object.keys(shopItem.requirement.requiredItemTypes||{});for(var i=0;i${requiredQty||""} ${item.name}

      `}if(requirements){html+="
      ";html+="

      Requirements:

      ";html+=requirements;html+="
      "}}if(shopItem&&typeof shopItem.price==="object"){var prices="";for(var priceAttr in shopItem.price.playerAttributes){var playerAttrValue=ownerPlayer._stats.attributes[priceAttr]&&ownerPlayer._stats.attributes[priceAttr].value||0;var requirementsSatisfied=parseFloat(shopItem.price.playerAttributes[priceAttr])<=parseFloat(playerAttrValue)&&"text-success"||"text-danger";prices+=`

      `;prices+=shopItem.price.playerAttributes[priceAttr];prices+=" ";prices+=ige.game.data.attributeTypes[priceAttr]&&ige.game.data.attributeTypes[priceAttr].name||ownerPlayer._stats.attributes[priceAttr]&&ownerPlayer._stats.attributes[priceAttr].name;prices+="

      "}html+="
      ";var requiredItemTypesKeys=Object.keys(shopItem.price.requiredItemTypes||{});for(var i=0;i${requiredQty||""} ${item.name}

      `}if(shopItem.price.coins){prices+=`

      ${shopItem.price.coins}

      `}html+="

      Price:

      ";if(prices){html+=prices}else{html+="

      free

      "}html+="
      "}return html},openItemShop:function(type,selectedTab){var self=this;if(!ige.game.data.shops)return;self.currentType=type||self.currentType;if(!self.currentType)return;var shopItemsKeys=ige.game.data.shops[self.currentType]?Object.keys(ige.game.data.shops[self.currentType].itemTypes||{}):[];shopItemsKeys=shopItemsKeys.sort();var shopUnitsKeys=ige.game.data.shops[self.currentType]?Object.keys(ige.game.data.shops[self.currentType].unitTypes||{}):[];shopUnitsKeys=shopUnitsKeys.sort();var shopItems=ige.game.data.shops[self.currentType]?_.cloneDeep(ige.game.data.shops[self.currentType].itemTypes):[];var shopUnits=ige.game.data.shops[self.currentType]?ige.game.data.shops[self.currentType].unitTypes:[];var isDismissible=ige.game.data.shops[self.currentType]&&ige.game.data.shops[self.currentType].dismissible!=undefined?ige.game.data.shops[self.currentType].dismissible:true;var shopItemsKeysUsingCoins=[];for(var key in shopItems){if(typeof shopItems[key].price=="object"&&shopItems[key].price.coins!=undefined&&shopItems[key].price.coins>0){shopItemsKeysUsingCoins.push(key)}}shopItemsKeysUsingCoins.forEach(key=>{delete shopItems[key]});if(shopItemsKeys.length>0){$("[id=item]").show();if(!selectedTab){selectedTab="items"}}else{$("[id=item]").hide()}if(shopUnitsKeys.length>0){$("[id=unit]").show();if(!selectedTab){selectedTab="units"}}else{$("[id=unit]").hide()}var modalBody=$("
      ",{class:"row text-center"});var ownerPlayer=ige.client.myPlayer;if(!ownerPlayer)return;var isAdBlockEnabled=ownerPlayer._stats.isAdBlockEnabled;var ownerUnit=ige.$(ownerPlayer._stats.selectedUnitId);var playerTypeAttribute=ownerPlayer._stats.attributes;var imgArray=[];if(selectedTab==="items"){$(".item-shop-navbar .nav-link").each(function(){$(this).removeClass("active")});$("[id=item]").addClass("active");for(var i=0;i0&&ownerPlayer._stats&&ownerPlayer._stats.playerTypeId){isPurchasableByCurrentPlayerType=item.canBePurchasedBy.includes(ownerPlayer._stats.playerTypeId)}var isItemAffordable=true;var requirementsSatisfied=true;if(typeof shopItem.requirement==="object"){for(var priceAttr in shopItem.requirement.playerAttributes){if(playerTypeAttribute&&playerTypeAttribute[priceAttr]){var req=shopItem.requirement.playerAttributes[priceAttr];var requirementsSatisfied=self.isItemRequirementSetisfied(req,priceAttr);if(!requirementsSatisfied){break}}}if(requirementsSatisfied){var requiredItemTypesKeys=Object.keys(shopItem.requirement.requiredItemTypes||{});for(var j=0;j",{style:"font-size: 16px; width: 250px;",html:self.getItemPopoverHtml(item,shopItem)});var bgColor=requirementsSatisfied&&isItemAffordable?"bg-light-green":"bg-light-red";var itemImage=$("
      ",{id:shopItemsKeys[i],isadblockenabled:isAdBlockEnabled,class:"col-sm-2-5 rounded align-bottom btn-purchase-item item-shop-button",name:item.name,requirementsSatisfied:!!requirementsSatisfied,isItemAffordable:!!isItemAffordable});if((!isItemAffordable||!isPurchasableByCurrentPlayerType)&&shopItem.hideIfUnaffordable||!requirementsSatisfied&&shopItem.hideIfRequirementNotMet){}else{var img=$("
      ").html(`img_index_${imgArray.length}`);imgArray.push({wrapper:img,value:``});var itemName="
      ";itemName+=item.name;itemName+="
      ";var combine=$("
      ",{class:`mx-2 p-3 mb-3 rounded item-shop-button-div d-flex flex-column justify-content-end align-items-center ${bgColor}`,style:"min-height:110px;max-height:110px;position:relative;","data-toggle":"popover","data-placement":"top","data-content":itemDetail.prop("outerHTML")}).append(img).append(itemName);combine.popover({html:true,trigger:"hover"});modalBody.append(itemImage.append(combine))}}}}else if(selectedTab==="units"){$(".item-shop-navbar .nav-link").each(function(){$(this).removeClass("active")});$("[id=unit]").addClass("active");for(var i=0;i0&&ownerPlayer._stats&&ownerPlayer._stats.playerTypeId){isPurchasableByCurrentPlayerType=unit.canBePurchasedBy.includes(ownerPlayer._stats.playerTypeId)}var isUnitAffordable=true;var requirementsSatisfied=true;if(typeof shopUnit.requirement==="object"){for(var priceAttr in shopUnit.requirement.playerAttributes){if(playerTypeAttribute&&playerTypeAttribute[priceAttr]){var req=shopUnit.requirement.playerAttributes[priceAttr];var requirementsSatisfied=self.isItemRequirementSetisfied(req,priceAttr);if(!requirementsSatisfied){break}}}}if(requirementsSatisfied){if(typeof shopUnit.price==="object"){for(var priceAttr in shopUnit.price.playerAttributes){if(playerTypeAttribute&&playerTypeAttribute[priceAttr]&&playerTypeAttribute[priceAttr].value",{type:"button",class:`btn ${requirementsSatisfied&&isUnitAffordable&&isPurchasableByCurrentPlayerType?"btn-success btn-purchase-unit":"btn-danger"}`,style:"",id:shopUnitsKeys[i],name:unit.name});var btnLabel=self.shopBtnLabel(shopUnit,playerTypeAttribute);button.append(btnLabel);if(shopUnit.hideIfUnaffordable&&!isUnitAffordable||shopUnit.hideIfRequirementNotMet&&!requirementsSatisfied){}else{modalBody.append($("
      ",{class:"col-sm-3 align-bottom",style:"margin-bottom: 30px;"}).append($("",{src:unit.inventoryImage||unit.cellSheet.url,style:"width: auto; height: auto; max-width: 64px; max-height: 64px"})).append(`
      ${unit.name}
      `).append(button))}}}}if(modalBody.html()==""){modalBody.append("
      There's nothing to be displayed here
      ")}var modalUpdated=false;if(self.oldModalHTMLBody!=modalBody.html()){modalUpdated=true;self.oldModalHTMLBody=_.cloneDeep(modalBody.html());$("#modd-item-shop-modal .items-shop").html(modalBody);imgArray.forEach(function(data){data.wrapper.html(data.value)})}$("#modd-item-shop-modal").modal({backdrop:isDismissible?true:"static",keyboard:isDismissible,show:false});if(isDismissible){$("#modd-item-shop-dismiss-button").show()}else{$("#modd-item-shop-dismiss-button").hide()}},shopBtnLabel:function(type,playerTypeAttribute){var firstLoop=true;var btnLabel="";var priceKey=[];var coins=0;var itemsRequired=[];var attributeTypes=ige.game.data.attributeTypes;if(typeof type.price==="object"){coins=type.price.coins;priceKey=Object.keys(type.price.playerAttributes||{});itemsRequired=type.price.requiredItemTypes}if(!priceKey||priceKey.length===0){btnLabel="free"}priceKey.forEach(function(key){var price=type.price.playerAttributes[key];var selectedAttribute={};selectedAttribute=ige.game.data.attributeTypes[key]||playerTypeAttribute[key];if(typeof selectedAttribute==="object"){if(Object.keys(selectedAttribute||[]).length===0){selectedAttribute=attributeTypes[key]}var label=Object.keys(selectedAttribute||[]).length?selectedAttribute.name:null}if(!firstLoop&&label){btnLabel+="
      "}if(firstLoop&&label===null){btnLabel="free"}else{btnLabel+=`${label} ${price}`}firstLoop=false});var requiredItemTypesKeys=Object.keys(itemsRequired||{});for(var i=0;i"}btnLabel+=item.name;if(requiredQty){btnLabel+=` - ${requiredQty}`}}if(coins){if(btnLabel=="free"){btnLabel=""}if(btnLabel){btnLabel+="
      "}btnLabel+=`${coins}`}return btnLabel},openCoinShop:function(){if(ige.isClient){$("#coin-shop-modal").modal({show:true,keybfoard:true})}},enableShop:function(){$("#shop-modal").modal({show:false,keyboard:true}).on("hidden.bs.modal",function(){shoppingModalManuallyHidden=true;$("#footer").hide()})},renderSkinsButtons:function(items){var self=this;var modalBody=$("
      ",{class:"row text-center"});for(var i in items){var item=items[i];if(item.status=="not_purchased"){if(item.soldForSocialShare){var button=self.buttonForSocialShare(item)}else{var button=$("");$("#region-delete-btn").prop("disabled",true)}else{ige.regionManager.isAddNewRegion=false;$("#region-update-btn").html(" Save");$("#region-delete-btn").prop("disabled",false)}$("button").focus(function(){this.blur()});$("#region-modal-client").modal({show:true})}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=RegionManager}var TweenComponent=$i_56.extend({classId:"TweenComponent",componentId:"tween",init:function(parentEntity){var self=this;self._entity=parentEntity;self.queue=[];self.keyFrames=[];self.offset={x:0,y:0,rotate:0};self.tweens={idle:{type:"translate",loopCount:-1,keyFrames:[[0,[0,0,0]],[400,[0,-2,0]],[800,[0,0,0]]]},wobble:{type:"swing",loopCount:-1,keyFrames:[[0,[0,0,0]],[50,[0,0,0.1]],[100,[0,0,-0.1]],[50,[0,0,0]]]},poke:{type:"translate",loopCount:1,keyFrames:[[0,[0,0,0]],[60,[0,50,0]],[180,[0,0,0]]]},recoil:{type:"translate",loopCount:1,keyFrames:[[0,[0,0,0]],[20,[0,-10,0]],[150,[0,0,0]]]},swingCW:{type:"swing",loopCount:1,keyFrames:[[0,[0,0,0]],[100,[0,0,3.14]],[250,[0,0,0]]]},swingCCW:{type:"swing",loopCount:1,keyFrames:[[0,[0,0,0]],[100,[0,0,-3.14]],[250,[0,0,0]]]}}},start:function(tweenId,angle,customTween){if(customTween){var tween=customTween}else{if(!this.tweens[tweenId]){this.stop();return}var tween=JSON.parse(JSON.stringify(this.tweens[tweenId]))}this.tweenId=tweenId;this.keyFrames=tween.keyFrames;this.type=tween.type;this.loopCount=tween.loopCount;this.angle=angle;this.startTime=ige._currentTime;this.offset={x:0,y:0,rotate:0};this.lastFrame=this.keyFrames.shift();this.nextFrame=this.keyFrames[0];this.isTweening=true},stop:function(){this.tweenId=undefined;this.isTweening=false},update:function(){var angle=this.angle;if(angle==undefined){angle=this._entity._rotate.z}if(this.keyFrames.length>0){var nextFrameEndsAt=this.startTime+this.nextFrame[0];if(ige._currentTimeMath.PI){if(targetRotate>rotate)rotate+=Math.PI*2;else rotate-=Math.PI*2}this.offset.rotate=interpolatedRotate;if(this._entity._category=="item"&&this._entity._stats.currentBody){if(this._entity._stats.currentBody.jointType=="weldJoint"){var ownerUnit=this._entity.getOwnerUnit();if(ownerUnit){rotate=ownerUnit._rotate.z}}if(this.offset.rotate!=0){rotate=this._entity._rotate.z;var before=this._entity.getAnchoredOffset(rotate);var after=this._entity.getAnchoredOffset(rotate+interpolatedRotate);this.offset.x=after.x-before.x;this.offset.y=after.y-before.y;return}}interpolatedRotate+=angle;this.offset.x=interpolatedX*Math.cos(interpolatedRotate)+interpolatedY*Math.sin(interpolatedRotate);this.offset.y=interpolatedX*Math.sin(interpolatedRotate)-interpolatedY*Math.cos(interpolatedRotate)}else{this.lastFrame=this.keyFrames.shift();this.nextFrame=this.keyFrames[0];this.startTime=ige._currentTime}}else{if(this.loopCount==-1){this.start(this.tweenId);return}this.offset={x:0,y:0,rotate:0};this.isTweening=false}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=TweenComponent}var MenuUiComponent=$i_56.extend({classId:"MenuUiComponent",componentId:"menuUi",init:function(){var self=this;var playButtonClick=document.querySelector("#play-game-button");if(ige.isClient){console.log("initializing UI elements...");self.shopType="";self.shopKey="";self.shopPage=1;$("#reconnect-button").on("click",function(){location.reload()});$("#kick-player").on("click",function(){$("#kick-players-outofgame-modal").modal("show")});$("#resolution-high").on("click",function(){localStorage.setItem("resolution","high");self.setResolution()});$("#resolution-low").on("click",function(){if($("#igeFrontBuffer").attr("width")!=640&&$("#igeFrontBuffer").attr("height")!=480){localStorage.setItem("resolution","low");self.setResolution();if(typeof incrLowResolution==="function"){incrLowResolution()}}});$("#dev-error-button").on("click",function(){$("#error-log-modal").modal("show")});$("#bandwidth-usage").on("click",function(){$("#dev-status-modal").modal("show")});$("#leaderboard-link").on("click",function(e){e.preventDefault();$("#leaderboard-modal").modal("show")});$("#refresh-server-list-button").on("click",function(){ige.client.refreshServerList()});$("#max-players").on("change",function(){ige.client.refreshServerList()});$("#map-list").on("change",function(){ige.client.refreshServerList()});$("#kick-player-body").on("click",".kick-player-btn",function(){var clientId=$(this).attr("data-clientid");if((ige.game.data.isDeveloper||ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod)&&clientId){ige.network.send("kick",clientId)}});$("#kick-player-body").on("click",".ban-player-btn",function(){var userId=$(this).attr("data-userId");var gameId=$(this).attr("data-gameId");var clientId=$(this).attr("data-clientid");if((ige.game.data.isDeveloper||ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod)&&userId){ige.network.send("ban-user",{kickuserId:clientId,userId:userId})}});$("#kick-player-body").on("click",".ban-ip-btn",function(){var gameId=$(this).attr("data-gameId");var clientId=$(this).attr("data-clientid");if((ige.game.data.isDeveloper||ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod)&&gameId){ige.network.send("ban-ip",{gameId:gameId,kickuserId:clientId})}});$("#kick-player-body").on("click",".ban-chat-btn",function(){var gameId=$(this).attr("data-gameId");var clientId=$(this).attr("data-clientid");if((ige.game.data.isDeveloper||ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod)&&gameId){ige.network.send("ban-chat",{gameId:gameId,kickuserId:clientId})}});$("#open-inventory-button").on("click",function(){if($("#backpack").is(":visible")){$("#backpack").hide()}else{$("#backpack").show()}});$(".open-menu-button").on("click",function(){self.toggleMenu();$(".open-menu-button").hide()});$("#change-server").on("click",function(){window.location.replace(`/play/${gameSlug}?serverId=${ige.client.changedServer}&joinGame=true`)});$("#add-player-instance").on("click",function(){var url=`${window.location.host}/play/${gameSlug}?add-instance=true`;Swal({html:`
      Want to add player instance?
      Copy the link given below and open it in incognito mode.
      `,button:"close"})});$("#help-modal").on("hidden.bs.modal",function(e){localStorage.setItem("tutorial","off")});$("#server-list").on("change",function(){var gameSlug=$(this).attr("game-slug");ige.client.gameSlug=gameSlug;if(ige.client.servers){for(var i=0;iConnecting.....";$("#play-game-button .content").html(html)},playGame:function(wasGamePaused){var self=this;self.startLoading();$("#featured-youtuber").hide();setTimeout(function(){var html=$("#play-game-button .content").html();if(/connecting/i.test(html)){$.post(`${analyticsUrl}api/game-report/game-access/${gameId}/infinite-connecting`)}},10000);var gameId=ige.game.data.defaultData._id;if(gameId&&!wasGamePaused&&!window.isStandalone){if(window.innerWidth<1000){setTimeout(()=>{$("#show-chat").removeClass("d-none");$("#chat-box").addClass("d-none")},1500)}$.post(`${analyticsUrl}api/game-report/game-access/${gameId}/play-button`).then(function(){},function(xhr,status,error){$.post("/api/log",{event:"play-button",game:gameId,status:xhr.status,text:xhr.statusText})})}ige.client.joinGame();if(!window.isStandalone){ige.ad.showAnchorTag()}},kickPlayerFromGame:function(excludeEntity){var self=this;var players=ige.$$("player").filter(function(player){if(player&&player._stats&&player._stats.controlledBy==="human"&&player._alive&&player.id()!==excludeEntity)return true});var html="";html+="";html+="";html+="";html+="";players.forEach(function(player){html+="";html+=`";html+="";html+=""});html+="
      NameAction
      ${player._stats.name}`;if(ige.client.myPlayer&&player.id()===ige.client.myPlayer.id()){html+=" (you)"}html+="";html+="
      ";html+=``;html+=``;html+=``;html+="
      ";html+="
      ";$("#kick-player-body").html(html)},showMenu:function(selectBestServer){var self=this;if(ige.isClient){var selectedServer=undefined;var gameSlug=window.location.pathname.split("/").pop();if(window.isStandalone){return $("#menu-wrapper").removeClass("d-none").addClass("d-flex")}if(!ige.isMobile){$("#friends-panel").removeClass("d-none")}this.changesForMobile(true);this.toggleScoreBoard(false);this.toggleLeaderBoard(false);this.toggleGameSuggestionCard(false);$.ajax({type:"GET",url:`/api/game-server/${gameId}`,success:function(res){if(res.status=="success"){var servers=res.message;var serversList="";var index=0;function separate(str){var alphabets="";var numbers="";var chars=str.split("");var numberRegex=/[0-9]/;while(chars.length){var char=chars[chars.length-1];if(numberRegex.test(char)){numbers=char+numbers;chars.pop()}else{break}}return{alphabets:chars.join(""),numbers:numbers}}servers.forEach(function(server){var protocol=location.protocol.indexOf("https")>-1?"wss":"ws";var dataUrl=`${protocol}://${server.ip}${server.port?`:${server.port}`:""}`;if(server){var serverIP=server.ip.slice(0,server.ip.indexOf("."));var separated=separate(serverIP);var optionText=`${separated.alphabets} ${separated.numbers}`;var acceptingPlayers=server.acceptingPlayers?"":" not accepting players";serversList+=`${"`}if(selectBestServer&&!selectedServer&&server.acceptingPlayers){selectedServer=server}});if(serversList){$("#server-list").html(serversList);ige.client.servers=ige.client.getServersArray();if(selectBestServer&&selectedServer){ige.client.server=selectedServer.id;$("#server-list").val(selectedServer.id);$("#play-game-button").hide();$("#change-server").show()}else{$("#server-list").val(ige.client.server.id)}self.getServerPing()}else{$("#server-list").hide()}}$("#menu-wrapper").removeClass("d-none").addClass("d-flex")}})}},getServerPing:function(shouldPickOneWithLeast){var serverOptions=$("option.game-server:enabled");var promises=[];var self=this},getPing:function(serverOption,duration){return new Promise(function promiseFunction(resolve,reject){var data=$(serverOption).data();var socket=new WebSocket(`${data.url}/?token=`);var ping=Number.MAX_VALUE;socket.onopen=function(event){socket.send(JSON.stringify({type:"ping",sentAt:Date.now()}));setTimeout(function(){if(socket.readyState!==WebSocket.CLOSED&&socket.readyState!==WebSocket.CLOSING){socket.close();var existingText=$(serverOption).text();$(serverOption).text(`${existingText} (${Number.POSITIVE_INFINITY} ms)`);resolve({server:serverOption,ping:ping})}},5000)};socket.onmessage=function(event){var jsonString=LZString.decompressFromUTF16(event.data);var json=JSON.parse(jsonString);if(json.type==="pong"){ping=Date.now()-json.clientSentAt;var existingText=$(serverOption).text();socket.close();console.log(json);$(serverOption).text(`${existingText} (${ping} ms)`);resolve({server:serverOption,ping:ping})}};socket.onerror=function(err){console.log("Error while testing ping",err);reject(err)}})},changesForMobile:function(isMenuVisible){if(ige.isMobile){var loginDiv=$("#login-div");var myScoreDiv=$("#my-score-div");var leaderBoard=$("#leaderboard");var topText=$(".ui-text-top");var topMenuButtons=$("#top-menu-buttons");var friendsPanel=$("#friends-panel");var mobileChatBox=$("#mobile-chat-box");var shopButton=$("#mobile-shop-button");var shopButton=$("#mobile-shop-button");var homeButton=$("#home-button");if(isMenuVisible){topMenuButtons.addClass("d-none");leaderBoard.addClass("d-none");topText.addClass("d-none");homeButton.removeClass("d-none");myScoreDiv.removeClass("d-block");loginDiv.removeClass("hide-on-mobile");friendsPanel.addClass("d-none");mobileChatBox.addClass("d-none");shopButton.removeClass("d-inline");homeButton.removeClass("d-none")}else{topMenuButtons.removeClass("d-none");leaderBoard.removeClass("d-none");topText.removeClass("d-none");homeButton.addClass("d-none");myScoreDiv.addClass("d-block");loginDiv.addClass("hide-on-mobile");mobileChatBox.removeClass("d-none invisible");shopButton.addClass("d-inline")}$("#modd-shop-modal").css({fontSize:11});var allControls=ige.mobileControls.controls;if(allControls){for(var k in allControls){var control=allControls[k];control&&control.opacity&&control.opacity(isMenuVisible?0:0.5)}}if(ige.miniMap&&ige.miniMap.miniMap){var newWidth=isMenuVisible?0:ige.miniMap.maxMapDimension.width;ige.miniMap.miniMap.width(newWidth)}}},hideMenu:function(){$("#menu-wrapper").removeClass("d-flex").addClass("d-none");if(!ige.isMobile){$("#friends-panel").addClass("d-none")}this.changesForMobile(false);this.toggleScoreBoard(true);this.toggleLeaderBoard(true);this.toggleGameSuggestionCard(true)},toggleMenu:function(){if($("#menu-wrapper").is(":visible")){this.hideMenu()}else{this.showMenu()}},clipImageForShop:function(){var skins=$("#menu-purchasables")[0]?$("#menu-purchasables")[0].children:[];for(var i=0;i",{src:ige.game.data.settings.images.logo,height:"75px"}))}else{$(".game-title").html(server?server.gameName:"")}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=ThemeComponent}var PlayerUiComponent=$i_56.extend({classId:"PlayerUiComponent",componentId:"playerUi",init:function(entity,options){var self=this;self._entity=entity;self.setupListeners();self.pressedButton=false;self.lastInputValue="";self.dialogue={message:null,messagePrinter:null}},setupListeners:function(){var self=this;$("#player-input-modal").on("hidden.bs.modal",function(){if(self.pressedButton){ige.network.send("playerCustomInput",{status:"submitted",inputText:self.lastInputValue});self.lastInputValue=""}else{ige.network.send("playerCustomInput",{status:"dismissed"})}$("#player-input-modal").removeClass("d-flex")});$("#custom-modal").on("hidden.bs.modal",function(){$("#custom-modal").removeClass("d-flex")});$("#custom-modal").on("shown.bs.modal",function(){$("#custom-modal-cancel").focus()});$("#player-input-modal").on("shown.bs.modal",function(){if(self.isDismissibleInputModalShown){$("#player-input-cancel").focus()}else{$("#player-input-field").focus()}});$("button#player-input-submit").on("click",function(){self.lastInputValue=$("#player-input-field").val();self.pressedButton=true;$("#player-input-modal").modal("hide")});$("button#player-input-cancel").on("click",function(){self.pressedButton=false;ige.network.send("playerCustomInput",{status:"cancelled"});$("#player-input-modal").modal("hide")})},updatePlayerAttributesDiv:function(attributes){var self=this;$("#players-attribute-div").html("");var attributeTypes=ige.game.data.attributeTypes;if(attributeTypes==undefined)return;for(var attrKey in attributes){var attr=attributes[attrKey];if(attr){if(!attr.isVisible)continue;var attributeType=attributeTypes[attrKey];var name=attributeType?attributeType.name:attr.name;var attrName=$("",{class:`pt-attribute-${attrKey}`});var attrValue=$("",{class:`pt-attribute-value-${attrKey}`});$("#players-attribute-div").append(attrName).append(attrValue).append($("
      "));attrName.text(`${name}: `);if(attr.value%1===0){attr.value=parseInt(attr.value)}else{if(attr.decimalPlaces!=undefined&&attr.decimalPlaces!=null){var decimalPlace=parseInt(attr.decimalPlaces);if(decimalPlace!=NaN){attr.value=parseFloat(attr.value).toFixed(decimalPlace)}else{attr.value=parseFloat(attr.value).toFixed(2)}}else{attr.value=parseFloat(attr.value).toFixed(2)}}var value=attr.value&&attr.value.toLocaleString("en-US")||0;attrValue.text(value)}}if($("#modd-item-shop-modal").hasClass("show")){ige.shop.openItemShop()}},updatePlayerCoin:function(newValue){var coin=parseInt($(".player-coins").html());if(coin!=NaN){$(".player-coins").html(parseInt(newValue))}},showFriendsModal:function(config){$("#invite-friends-modal").modal("show")},showInputModal:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;self.isDismissibleInputModalShown=config.isDismissible;$("#player-input-field-label").html(config.fieldLabel||"Field");$("#player-input-field").val("");$("#player-input-modal").addClass("d-flex");$("#player-input-modal").modal({backdrop:config.isDismissible?true:"static",keyboard:config.isDismissible});if(config.isDismissible){$("#player-input-cancel-container").show();$("#player-input-modal-dismiss-button").show()}else{$("#player-input-cancel-container").hide();$("#player-input-modal-dismiss-button").hide()}$("#player-input-modal").modal("show");self.pressedButton=false},showCustomModal:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;$("#custom-modal .content").html(config.content||"");if(config.title){$("#custom-modal .modal-title").html(config.title);$("#custom-modal .modal-header").show()}else{$("#custom-modal .modal-header").hide()}$("#custom-modal").addClass("d-flex");$("#custom-modal").modal({backdrop:config.isDismissible?true:"static",keyboard:config.isDismissible});if(config.isDismissible){$("#custom-modal-cancel-container").show();$("#custom-modal-dismiss-button").show()}else{$("#custom-modal-cancel-container").hide();$("#custom-modal-dismiss-button").hide()}$("#custom-modal").modal("show");self.pressedButton=false},openWebsite:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;var newWin=window.open(config.url);if(!newWin||newWin.closed||typeof newWin.closed=="undefined"){swal({title:"Please allow Popups",text:"Your browser is blocking the content modd.io is trying to display",imageWidth:300,imageUrl:"/assets/images/enable-popup.gif",imageClass:"rounded border"})}},showWebsiteModal:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;$("#website-modal").find("iframe").attr("src",config.url);$("#website-modal").modal({backdrop:config.isDismissible?true:"static",keyboard:config.isDismissible})},showSocialShareModal:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;$("#social-share-modal").modal({backdrop:config.isDismissible?true:"static",keyboard:config.isDismissible})},openDialogueModal:function(dialogueId,extraData){var self=this;function getDialogueInstance(dialogue){var playerName=extraData&&extraData.playerName;dialogue=JSON.parse(JSON.stringify(dialogue));if(dialogue.message.indexOf("%PLAYER_NAME%")>-1&&playerName){dialogue.message=dialogue.message.replace(/%PLAYER_NAME%/g,playerName)}var variables=dialogue.message.match(new RegExp("\\$.+?\\$","g"));if(variables&&variables.length){variables.forEach(function(variable){var variableName=variable.split("$")[1];if(extraData.variables.hasOwnProperty(variableName)){var variableValue=extraData.variables[variableName];dialogue.message=dialogue.message.replace(new RegExp(`\\$${variableName}\\$`,"g"),variableValue)}})}dialogue.messageFragments=dialogue.message.split("%br%");dialogue.currentFragmentIndex=0;dialogue.areAllMessagesPrinted=function(){return this.currentFragmentIndex>=this.messageFragments.length};dialogue.getNextMessage=function(){return dialogue.messageFragments[dialogue.currentFragmentIndex++]};dialogue.hasOptions=function(){return Object.keys(dialogue.options).length>0};dialogue.areOptionsRendered=false;return dialogue}function initModal(){$("#modd-dialogue-message").html("");$("#modd-dialogue-image").attr("src","");$("#modd-dialogue-options-container").addClass("d-none");$("#modd-dialogue-skip-hint").addClass("d-none");if(self.dialogue.messagePrinter){clearInterval(self.dialogue.messagePrinter)}if(dialogue.image){$("#modd-dialogue-image-container").removeClass("d-none");$("#modd-dialogue-message-container").addClass("col-8");$("#modd-dialogue-message-container").addClass("pl-md-0");$("#modd-dialogue-message-container").removeClass("col-12");$("#modd-dialogue-image").attr("src",dialogue.image)}else{$("#modd-dialogue-image-container").addClass("d-none");$("#modd-dialogue-message-container").removeClass("col-8");$("#modd-dialogue-message-container").addClass("col-12");$("#modd-dialogue-image").attr("src","")}$(document).on("keydown.modd-dialogue",keyboardListener);$(document).on("click.modd-dialogue",skipText)}function printingCompleted(){window.isPrintingDialogue=false;if(dialogue.areAllMessagesPrinted()){if(dialogue.hasOptions()){if(!dialogue.areOptionsRendered){showOptions()}}else{$("#modd-dialogue-skip-hint").removeClass("d-none")}}else{$("#modd-dialogue-skip-hint").removeClass("d-none")}}function showOptions(){$("#modd-dialogue-options").html("");for(var key in dialogue.options){var optionObject=dialogue.options[key];var button=$(""}html+="\t
      "+"
      ";var skin=$(html);$("#skins-list").append(skin)});$("#loading-skins").addClass("d-none");$("#skins-list").removeClass("d-none").addClass("row")}else if(response.status=="error"){$("#loading-skins").addClass("d-none");console.log(response.message)}}})},purchaseWarning:function(type,itemName){var text="";switch(type){case"requirement":text=`${itemName} requirements not met.`;break;case"price":text=`Cannot afford ${itemName}.`;break;case"inventory_full":text="No room in inventory.";break;case"purchase":text="Item purchased.";break;}if($("#modd-item-shop-modal").hasClass("show")){$("#item-purchase-warning").html(text);$("#item-purchase-warning").show();setTimeout(function(){$("#item-purchase-warning").fadeOut()},800)}},buySkin:function(itemId,sharedOn=""){var self=this;$.ajax({url:`/api/user/purchase/${ige.game.data.defaultData.parentGame||ige.client.server.gameId}/${itemId}?sharedOn=${sharedOn}`,dataType:"html",type:"POST",success:function(data){var response=JSON.parse(data);if(response.status=="success"){$(".player-coins").html(parseInt(response.remaining_coins));if(ige.client.myPlayer){ige.client.myPlayer._stats.coins=parseInt(response.remaining_coins)}$("#purchasable-purchase-modal").modal("hide");self.updateModdShop();self.updateSkinList(itemId);var details=$(`.btn-purchase-purchasable#${itemId}`);var purchasableInfo=details.find(".purchasable-details");if(purchasableInfo&&purchasableInfo.html){details.removeClass("btn-purchase-purchasable");purchasableInfo.html("")}}else if(response.status=="error"){if(!response.message.includes("No matching document found")){var error=`
      ${response.message}
      `;$("#purchasable-purchase-modal .purchasable-info-container").html(error)}}}})},openModdShop:function(tabSelected,elementIdToFocus){if(ige.isClient){var self=this;this.hideEmptyTabs();if(tabSelected&&tabSelected=="item"&&$("[id=item]").css("display")=="none"){tabSelected="unit"}if(tabSelected&&tabSelected=="unit"&&$("[id=unit]").css("display")=="none"){tabSelected="item"}this.updateModdShop(tabSelected);if(elementIdToFocus){$("#modd-shop-modal").one("shown.bs.modal",function(){$(this).animate({scrollTop:$(elementIdToFocus).offset().top-100},1000,function(){$(elementIdToFocus).effect("highlight",{},3000)})})}$("#modd-shop-modal").modal({show:true,keyboard:true})}},hideEmptyTabs:function(){var self=this;var unitArr=[];var itemArr=[];if(!ige.game.data.unitTypes){$("[id=unit]").hide();$("[id=unitSkins]").hide()}else{for(unitId in ige.game.data.unitTypes){var unit=ige.game.data.unitTypes[unitId];if(unit.isPurchasable){unitArr.push(unit)}}if(unitArr.length===0){$("[id=unit]").hide()}}if(!ige.game.data.itemTypes){$("[id=item]").hide();$("[id=itemSkins]").hide()}else{for(itemId in ige.game.data.itemTypes){var item=ige.game.data.itemTypes[itemId];if(item.isPurchasable){itemArr.push(item)}}if(itemArr.length===0){$("[id=item]").hide()}else if(unitArr.length===0){if(self.shopType===undefined){self.shopType="item";$("[id=item]").addClass("active")}}}$.ajax({url:`/api/game/${ige.game.data.defaultData.parentGame||ige.client.server.gameId}/shopCount`,type:"GET",success:function(data){if(data.status==="success"){if(data.message){if(!data.message.unitCount||data.message.unitCount.length===0){$("[id=unitSkins]").hide()}else if(data.message.unitCount){for(var i in ige.game.data.unitTypes){var total=data.message.unitCount.filter(function(unit,key){if(unit&&unit.target&&unit.target.key===i)return true});if(total){total=total.length}else{total=0}self.unitSkinCount[i]=total}}if(!data.message.itemCount||data.message.itemCount.length===0){$("[id=itemSkins]").hide()}else if(data.message.itemCount){for(var i in ige.game.data.itemTypes){var total=data.message.itemCount.filter(function(item,key){if(item&&item.target&&item.target.key===i)return true});if(total){total=total.length}else{total=0}self.itemSkinCount[i]=total}}self.checkIfAnyTabSelected()}}}})},getTwitterBtnHtml:function(item){var sharedOn=item.sharedOn||{};var title=item.title||item.name;var sharedOnTwitter=sharedOn.twitter?"disabled":"";var gameId=ige.game.data.defaultData._id;var textToTweet=`Join me in ${ige.game.data.defaultData.title} (${location.href})`;var hashTags=["games","moddio"];var mentions=["moddio"];var twitterUrl=`https://twitter.com/intent/tweet?text=${textToTweet}&hashtags=${hashTags.join(",")}&via=${mentions.join(",")}`;return``},buttonForSocialShare:function(item,unauthenticated){var btnHtml="";var sharedOn=item.sharedOn||{};var sharedOnFacebook=sharedOn.facebook?"disabled":"";var gameId=ige.game.data.defaultData._id;if(item){var title=item.title||item.name;btnHtml+="
      ";btnHtml+=this.getTwitterBtnHtml(item);btnHtml+="
      "}return btnHtml},updateModdShop:function(tabSelected){var self=this;if(ige.isMobile){$(".open-coin-shop-button").hide()}var keyList=$("
        ",{class:"list-group"});var isFirstKey=true;if(self.shopType===undefined){self.shopType="unit"}if(tabSelected){self.shopType=tabSelected}if(self.shopType=="unitSkins"){$(".shop-navbar .nav-link").each(function(){$(this).removeClass("active")});$("#unitSkins").addClass("active");var unitKeys=Object.keys(ige.game.data.unitTypes);unitKeys=unitKeys.sort();for(var p=0;p0){if(!self.shopKey&&isFirstKey){self.shopKey=key}keyDiv=$("
      • ",{class:`list-group-item list-group-item-action cursor-pointer ${key==self.shopKey?"active":""}`,text:`${ige.game.data.unitTypes[key].name} (${self.unitSkinCount[key]})`,name:key}).on("click",function(){self.shopKey=$(this).attr("name");$("#modd-shop-modal .shop-items").html("");$(".list-group.item").each(function(){$(this).removeClass("active")});$(this).addClass("active");self.updateModdShop()});keyList.append(keyDiv);var isFirstKey=false}}$(".shop-sidebar").html(keyList).show()}else if(self.shopType=="itemSkins"){$(".shop-navbar .nav-link").each(function(){$(this).removeClass("active")});$("#itemSkins").addClass("active");for(key in ige.game.data.itemTypes){$("#modd-shop-modal .shop-items").html("");if(self.itemSkinCount[key]>0){if(!self.shopKey&&isFirstKey){self.shopKey=key}keyDiv=$("
      • ",{class:`list-group-item ${key==self.shopKey?"active":""}`,text:`${ige.game.data.itemTypes[key].name} (${self.itemSkinCount[key]})`,name:key}).on("click",function(){self.shopKey=$(this).attr("name");$("#modd-shop-modal .shop-items").html("");$(".list-group.item").each(function(){$(this).removeClass("active")});$(this).addClass("active");self.updateModdShop()});keyList.append(keyDiv);var isFirstKey=false}}$(".shop-sidebar").html(keyList).show()}else if(self.shopType=="item"){$(".shop-sidebar").hide()}else if(self.shopType=="unit"){$(".shop-sidebar").hide()}if(self.shopType=="unitSkins"||self.shopType=="itemSkins"){$.ajax({url:`/api/game/${ige.game.data.defaultData.parentGame||ige.client.server.gameId}/shop`,data:{type:self.shopType==="unitSkins"?"unit":"item",key:self.shopKey,page:self.shopPage},dataType:"html",type:"GET",success:function(data){var items=JSON.parse(data).message;var groupedItems={purchased:[],notPurchased:[]};items.forEach(function(item){if(item.status=="not_purchased"){groupedItems.notPurchased.push(item)}else{groupedItems.purchased.push(item)}});self.skinItems=groupedItems.purchased.concat(groupedItems.notPurchased);self.currentPagination=1;self.paginationForSkins()}})}},updateSkinList:function(itemId){debugger;var skinItemActionButton=$(`#skin-list-${itemId} .action-button-container`);skinItemActionButton.html("")},checkIfAnyTabSelected:function(){var anyTabSelected=false;$(".shop-navbar .nav-link").each(function(){if($(this).hasClass("active")&&$(this).css("display")!="none"){anyTabSelected=true;return false}});if(!anyTabSelected){var self=this;$(".shop-navbar .nav-link").each(function(){if($(this).css("display")!="none"){self.shopType=$(this)[0].id;self.updateModdShop(self.shopType);return false}})}},isItemRequirementSetisfied:function(req,priceAttr){var ownerPlayer=ige.client.myPlayer;var playerTypeAttribute=ownerPlayer._stats.attributes;if(playerTypeAttribute[priceAttr]){switch(req.type){case"atmost":if(playerTypeAttribute[priceAttr].value>req.value){return false}break;case"exactly":if(playerTypeAttribute[priceAttr].value!=req.value){return false}break;case"atleast":default:if(playerTypeAttribute[priceAttr].value${item.description}

        `}if(shopItem&&typeof shopItem.requirement==="object"){var requirements="";for(var priceAttr in shopItem.requirement.playerAttributes){var req=shopItem.requirement.playerAttributes[priceAttr];var requirementsSatisfied=self.isItemRequirementSetisfied(req,priceAttr)&&"text-success"||"text-danger";requirements+=`

        `;requirements+=req.value;requirements+=" ";requirements+=ige.game.data.attributeTypes[priceAttr]&&ige.game.data.attributeTypes[priceAttr].name||ownerPlayer._stats.attributes[priceAttr]&&ownerPlayer._stats.attributes[priceAttr].name;requirements+="

        "}var requiredItemTypesKeys=Object.keys(shopItem.requirement.requiredItemTypes||{});for(var i=0;i${requiredQty||""} ${item.name}

        `}if(requirements){html+="
        ";html+="

        Requirements:

        ";html+=requirements;html+="
        "}}if(shopItem&&typeof shopItem.price==="object"){var prices="";for(var priceAttr in shopItem.price.playerAttributes){var playerAttrValue=ownerPlayer._stats.attributes[priceAttr]&&ownerPlayer._stats.attributes[priceAttr].value||0;var requirementsSatisfied=parseFloat(shopItem.price.playerAttributes[priceAttr])<=parseFloat(playerAttrValue)&&"text-success"||"text-danger";prices+=`

        `;prices+=shopItem.price.playerAttributes[priceAttr];prices+=" ";prices+=ige.game.data.attributeTypes[priceAttr]&&ige.game.data.attributeTypes[priceAttr].name||ownerPlayer._stats.attributes[priceAttr]&&ownerPlayer._stats.attributes[priceAttr].name;prices+="

        "}html+="
        ";var requiredItemTypesKeys=Object.keys(shopItem.price.requiredItemTypes||{});for(var i=0;i${requiredQty||""} ${item.name}

        `}if(shopItem.price.coins){prices+=`

        ${shopItem.price.coins}

        `}html+="

        Price:

        ";if(prices){html+=prices}else{html+="

        free

        "}html+="
        "}return html},openItemShop:function(type,selectedTab){var self=this;if(!ige.game.data.shops)return;self.currentType=type||self.currentType;if(!self.currentType)return;var shopItemsKeys=ige.game.data.shops[self.currentType]?Object.keys(ige.game.data.shops[self.currentType].itemTypes||{}):[];shopItemsKeys=shopItemsKeys.sort();var shopUnitsKeys=ige.game.data.shops[self.currentType]?Object.keys(ige.game.data.shops[self.currentType].unitTypes||{}):[];shopUnitsKeys=shopUnitsKeys.sort();var shopItems=ige.game.data.shops[self.currentType]?_.cloneDeep(ige.game.data.shops[self.currentType].itemTypes):[];var shopUnits=ige.game.data.shops[self.currentType]?ige.game.data.shops[self.currentType].unitTypes:[];var isDismissible=ige.game.data.shops[self.currentType]&&ige.game.data.shops[self.currentType].dismissible!=undefined?ige.game.data.shops[self.currentType].dismissible:true;var shopItemsKeysUsingCoins=[];for(var key in shopItems){if(typeof shopItems[key].price=="object"&&shopItems[key].price.coins!=undefined&&shopItems[key].price.coins>0){shopItemsKeysUsingCoins.push(key)}}shopItemsKeysUsingCoins.forEach(key=>{delete shopItems[key]});if(shopItemsKeys.length>0){$("[id=item]").show();if(!selectedTab){selectedTab="items"}}else{$("[id=item]").hide()}if(shopUnitsKeys.length>0){$("[id=unit]").show();if(!selectedTab){selectedTab="units"}}else{$("[id=unit]").hide()}var modalBody=$("
        ",{class:"row text-center"});var ownerPlayer=ige.client.myPlayer;if(!ownerPlayer)return;var isAdBlockEnabled=ownerPlayer._stats.isAdBlockEnabled;var ownerUnit=ige.$(ownerPlayer._stats.selectedUnitId);var playerTypeAttribute=ownerPlayer._stats.attributes;var imgArray=[];if(selectedTab==="items"){$(".item-shop-navbar .nav-link").each(function(){$(this).removeClass("active")});$("[id=item]").addClass("active");for(var i=0;i0&&ownerPlayer._stats&&ownerPlayer._stats.playerTypeId){isPurchasableByCurrentPlayerType=item.canBePurchasedBy.includes(ownerPlayer._stats.playerTypeId)}var isItemAffordable=true;var requirementsSatisfied=true;if(typeof shopItem.requirement==="object"){for(var priceAttr in shopItem.requirement.playerAttributes){if(playerTypeAttribute&&playerTypeAttribute[priceAttr]){var req=shopItem.requirement.playerAttributes[priceAttr];var requirementsSatisfied=self.isItemRequirementSetisfied(req,priceAttr);if(!requirementsSatisfied){break}}}if(requirementsSatisfied){var requiredItemTypesKeys=Object.keys(shopItem.requirement.requiredItemTypes||{});for(var j=0;j",{style:"font-size: 16px; width: 250px;",html:self.getItemPopoverHtml(item,shopItem)});var bgColor=requirementsSatisfied&&isItemAffordable?"bg-light-green":"bg-light-red";var itemImage=$("
        ",{id:shopItemsKeys[i],isadblockenabled:isAdBlockEnabled,class:"col-sm-2-5 rounded align-bottom btn-purchase-item item-shop-button",name:item.name,requirementsSatisfied:!!requirementsSatisfied,isItemAffordable:!!isItemAffordable});if((!isItemAffordable||!isPurchasableByCurrentPlayerType)&&shopItem.hideIfUnaffordable||!requirementsSatisfied&&shopItem.hideIfRequirementNotMet){}else{var img=$("
        ").html(`img_index_${imgArray.length}`);imgArray.push({wrapper:img,value:``});var itemName="
        ";itemName+=item.name;itemName+="
        ";var combine=$("
        ",{class:`mx-2 p-3 mb-3 rounded item-shop-button-div d-flex flex-column justify-content-end align-items-center ${bgColor}`,style:"min-height:110px;max-height:110px;position:relative;","data-toggle":"popover","data-placement":"top","data-content":itemDetail.prop("outerHTML")}).append(img).append(itemName);combine.popover({html:true,trigger:"hover"});modalBody.append(itemImage.append(combine))}}}}else if(selectedTab==="units"){$(".item-shop-navbar .nav-link").each(function(){$(this).removeClass("active")});$("[id=unit]").addClass("active");for(var i=0;i0&&ownerPlayer._stats&&ownerPlayer._stats.playerTypeId){isPurchasableByCurrentPlayerType=unit.canBePurchasedBy.includes(ownerPlayer._stats.playerTypeId)}var isUnitAffordable=true;var requirementsSatisfied=true;if(typeof shopUnit.requirement==="object"){for(var priceAttr in shopUnit.requirement.playerAttributes){if(playerTypeAttribute&&playerTypeAttribute[priceAttr]){var req=shopUnit.requirement.playerAttributes[priceAttr];var requirementsSatisfied=self.isItemRequirementSetisfied(req,priceAttr);if(!requirementsSatisfied){break}}}}if(requirementsSatisfied){if(typeof shopUnit.price==="object"){for(var priceAttr in shopUnit.price.playerAttributes){if(playerTypeAttribute&&playerTypeAttribute[priceAttr]&&playerTypeAttribute[priceAttr].value",{type:"button",class:`btn ${requirementsSatisfied&&isUnitAffordable&&isPurchasableByCurrentPlayerType?"btn-success btn-purchase-unit":"btn-danger"}`,style:"",id:shopUnitsKeys[i],name:unit.name});var btnLabel=self.shopBtnLabel(shopUnit,playerTypeAttribute);button.append(btnLabel);if(shopUnit.hideIfUnaffordable&&!isUnitAffordable||shopUnit.hideIfRequirementNotMet&&!requirementsSatisfied){}else{modalBody.append($("
        ",{class:"col-sm-3 align-bottom",style:"margin-bottom: 30px;"}).append($("",{src:unit.inventoryImage||unit.cellSheet.url,style:"width: auto; height: auto; max-width: 64px; max-height: 64px"})).append(`
        ${unit.name}
        `).append(button))}}}}if(modalBody.html()==""){modalBody.append("
        There's nothing to be displayed here
        ")}var modalUpdated=false;if(self.oldModalHTMLBody!=modalBody.html()){modalUpdated=true;self.oldModalHTMLBody=_.cloneDeep(modalBody.html());$("#modd-item-shop-modal .items-shop").html(modalBody);imgArray.forEach(function(data){data.wrapper.html(data.value)})}$("#modd-item-shop-modal").modal({backdrop:isDismissible?true:"static",keyboard:isDismissible,show:false});if(isDismissible){$("#modd-item-shop-dismiss-button").show()}else{$("#modd-item-shop-dismiss-button").hide()}},shopBtnLabel:function(type,playerTypeAttribute){var firstLoop=true;var btnLabel="";var priceKey=[];var coins=0;var itemsRequired=[];var attributeTypes=ige.game.data.attributeTypes;if(typeof type.price==="object"){coins=type.price.coins;priceKey=Object.keys(type.price.playerAttributes||{});itemsRequired=type.price.requiredItemTypes}if(!priceKey||priceKey.length===0){btnLabel="free"}priceKey.forEach(function(key){var price=type.price.playerAttributes[key];var selectedAttribute={};selectedAttribute=ige.game.data.attributeTypes[key]||playerTypeAttribute[key];if(typeof selectedAttribute==="object"){if(Object.keys(selectedAttribute||[]).length===0){selectedAttribute=attributeTypes[key]}var label=Object.keys(selectedAttribute||[]).length?selectedAttribute.name:null}if(!firstLoop&&label){btnLabel+="
        "}if(firstLoop&&label===null){btnLabel="free"}else{btnLabel+=`${label} ${price}`}firstLoop=false});var requiredItemTypesKeys=Object.keys(itemsRequired||{});for(var i=0;i"}btnLabel+=item.name;if(requiredQty){btnLabel+=` - ${requiredQty}`}}if(coins){if(btnLabel=="free"){btnLabel=""}if(btnLabel){btnLabel+="
        "}btnLabel+=`${coins}`}return btnLabel},openCoinShop:function(){if(ige.isClient){$("#coin-shop-modal").modal({show:true,keybfoard:true})}},enableShop:function(){$("#shop-modal").modal({show:false,keyboard:true}).on("hidden.bs.modal",function(){shoppingModalManuallyHidden=true;$("#footer").hide()})},renderSkinsButtons:function(items){var self=this;var modalBody=$("
        ",{class:"row text-center"});for(var i in items){var item=items[i];if(item.status=="not_purchased"){if(item.soldForSocialShare){var button=self.buttonForSocialShare(item)}else{var button=$("");$("#region-delete-btn").prop("disabled",true)}else{ige.regionManager.isAddNewRegion=false;$("#region-update-btn").html(" Save");$("#region-delete-btn").prop("disabled",false)}$("button").focus(function(){this.blur()});$("#region-modal-client").modal({show:true})}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=RegionManager}var TweenComponent=$i_54.extend({classId:"TweenComponent",componentId:"tween",init:function(parentEntity){var self=this;self._entity=parentEntity;self.queue=[];self.keyFrames=[];self.offset={x:0,y:0,rotate:0};self.tweens={idle:{type:"translate",loopCount:-1,keyFrames:[[0,[0,0,0]],[400,[0,-2,0]],[800,[0,0,0]]]},wobble:{type:"swing",loopCount:-1,keyFrames:[[0,[0,0,0]],[50,[0,0,0.1]],[100,[0,0,-0.1]],[50,[0,0,0]]]},poke:{type:"translate",loopCount:1,keyFrames:[[0,[0,0,0]],[60,[0,50,0]],[180,[0,0,0]]]},recoil:{type:"translate",loopCount:1,keyFrames:[[0,[0,0,0]],[20,[0,-10,0]],[150,[0,0,0]]]},swingCW:{type:"swing",loopCount:1,keyFrames:[[0,[0,0,0]],[100,[0,0,3.14]],[250,[0,0,0]]]},swingCCW:{type:"swing",loopCount:1,keyFrames:[[0,[0,0,0]],[100,[0,0,-3.14]],[250,[0,0,0]]]}}},start:function(tweenId,angle,customTween){if(customTween){var tween=customTween}else{if(!this.tweens[tweenId]){this.stop();return}var tween=JSON.parse(JSON.stringify(this.tweens[tweenId]))}this.tweenId=tweenId;this.keyFrames=tween.keyFrames;this.type=tween.type;this.loopCount=tween.loopCount;this.angle=angle;this.startTime=ige._currentTime;this.offset={x:0,y:0,rotate:0};this.lastFrame=this.keyFrames.shift();this.nextFrame=this.keyFrames[0];this.isTweening=true},stop:function(){this.tweenId=undefined;this.isTweening=false},update:function(){var angle=this.angle;if(angle==undefined){angle=this._entity._rotate.z}if(this.keyFrames.length>0){var nextFrameEndsAt=this.startTime+this.nextFrame[0];if(ige._currentTimeMath.PI){if(targetRotate>rotate)rotate+=Math.PI*2;else rotate-=Math.PI*2}this.offset.rotate=interpolatedRotate;if(this._entity._category=="item"&&this._entity._stats.currentBody){if(this._entity._stats.currentBody.jointType=="weldJoint"){var ownerUnit=this._entity.getOwnerUnit();if(ownerUnit){rotate=ownerUnit._rotate.z}}if(this.offset.rotate!=0){rotate=this._entity._rotate.z;var before=this._entity.getAnchoredOffset(rotate);var after=this._entity.getAnchoredOffset(rotate+interpolatedRotate);this.offset.x=after.x-before.x;this.offset.y=after.y-before.y;return}}interpolatedRotate+=angle;this.offset.x=interpolatedX*Math.cos(interpolatedRotate)+interpolatedY*Math.sin(interpolatedRotate);this.offset.y=interpolatedX*Math.sin(interpolatedRotate)-interpolatedY*Math.cos(interpolatedRotate)}else{this.lastFrame=this.keyFrames.shift();this.nextFrame=this.keyFrames[0];this.startTime=ige._currentTime}}else{if(this.loopCount==-1){this.start(this.tweenId);return}this.offset={x:0,y:0,rotate:0};this.isTweening=false}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=TweenComponent}var MenuUiComponent=$i_54.extend({classId:"MenuUiComponent",componentId:"menuUi",init:function(){var self=this;var playButtonClick=document.querySelector("#play-game-button");if(ige.isClient){console.log("initializing UI elements...");self.shopType="";self.shopKey="";self.shopPage=1;$("#reconnect-button").on("click",function(){location.reload()});$("#kick-player").on("click",function(){$("#kick-players-outofgame-modal").modal("show")});$("#resolution-high").on("click",function(){localStorage.setItem("resolution","high");self.setResolution()});$("#resolution-low").on("click",function(){if($("#igeFrontBuffer").attr("width")!=640&&$("#igeFrontBuffer").attr("height")!=480){localStorage.setItem("resolution","low");self.setResolution();if(typeof incrLowResolution==="function"){incrLowResolution()}}});$("#dev-error-button").on("click",function(){$("#error-log-modal").modal("show")});$("#bandwidth-usage").on("click",function(){$("#dev-status-modal").modal("show")});$("#leaderboard-link").on("click",function(e){e.preventDefault();$("#leaderboard-modal").modal("show")});$("#refresh-server-list-button").on("click",function(){ige.client.refreshServerList()});$("#max-players").on("change",function(){ige.client.refreshServerList()});$("#map-list").on("change",function(){ige.client.refreshServerList()});$("#kick-player-body").on("click",".kick-player-btn",function(){var clientId=$(this).attr("data-clientid");if((ige.game.data.isDeveloper||ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod)&&clientId){ige.network.send("kick",clientId)}});$("#kick-player-body").on("click",".ban-player-btn",function(){var userId=$(this).attr("data-userId");var gameId=$(this).attr("data-gameId");var clientId=$(this).attr("data-clientid");if((ige.game.data.isDeveloper||ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod)&&userId){ige.network.send("ban-user",{kickuserId:clientId,userId:userId})}});$("#kick-player-body").on("click",".ban-ip-btn",function(){var gameId=$(this).attr("data-gameId");var clientId=$(this).attr("data-clientid");if((ige.game.data.isDeveloper||ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod)&&gameId){ige.network.send("ban-ip",{gameId:gameId,kickuserId:clientId})}});$("#kick-player-body").on("click",".ban-chat-btn",function(){var gameId=$(this).attr("data-gameId");var clientId=$(this).attr("data-clientid");if((ige.game.data.isDeveloper||ige.client.myPlayer&&ige.client.myPlayer._stats.isUserMod)&&gameId){ige.network.send("ban-chat",{gameId:gameId,kickuserId:clientId})}});$("#open-inventory-button").on("click",function(){if($("#backpack").is(":visible")){$("#backpack").hide()}else{$("#backpack").show()}});$(".open-menu-button").on("click",function(){self.toggleMenu();$(".open-menu-button").hide()});$("#change-server").on("click",function(){window.location.replace(`/play/${gameSlug}?serverId=${ige.client.changedServer}&joinGame=true`)});$("#add-player-instance").on("click",function(){var url=`${window.location.host}/play/${gameSlug}?add-instance=true`;Swal({html:`
        Want to add player instance?
        Copy the link given below and open it in incognito mode.
        `,button:"close"})});$("#help-modal").on("hidden.bs.modal",function(e){localStorage.setItem("tutorial","off")});$("#server-list").on("change",function(){var gameSlug=$(this).attr("game-slug");ige.client.gameSlug=gameSlug;if(ige.client.servers){for(var i=0;iConnecting.....";$("#play-game-button .content").html(html)},playGame:function(wasGamePaused){var self=this;self.startLoading();$("#featured-youtuber").hide();setTimeout(function(){var html=$("#play-game-button .content").html();if(/connecting/i.test(html)){$.post(`${analyticsUrl}api/game-report/game-access/${gameId}/infinite-connecting`)}},10000);var gameId=ige.game.data.defaultData._id;if(gameId&&!wasGamePaused&&!window.isStandalone){if(window.innerWidth<1000){setTimeout(()=>{$("#show-chat").removeClass("d-none");$("#chat-box").addClass("d-none")},1500)}$.post(`${analyticsUrl}api/game-report/game-access/${gameId}/play-button`).then(function(){},function(xhr,status,error){$.post("/api/log",{event:"play-button",game:gameId,status:xhr.status,text:xhr.statusText})})}ige.client.joinGame();if(!window.isStandalone){ige.ad.showAnchorTag()}},kickPlayerFromGame:function(excludeEntity){var self=this;var players=ige.$$("player").filter(function(player){if(player&&player._stats&&player._stats.controlledBy==="human"&&player._alive&&player.id()!==excludeEntity)return true});var html="";html+="";html+="";html+="";html+="";players.forEach(function(player){html+="";html+=`";html+="";html+=""});html+="
        NameAction
        ${player._stats.name}`;if(ige.client.myPlayer&&player.id()===ige.client.myPlayer.id()){html+=" (you)"}html+="";html+="
        ";html+=``;html+=``;html+=``;html+="
        ";html+="
        ";$("#kick-player-body").html(html)},showMenu:function(selectBestServer){var self=this;if(ige.isClient){var selectedServer=undefined;var gameSlug=window.location.pathname.split("/").pop();if(window.isStandalone){return $("#menu-wrapper").removeClass("d-none").addClass("d-flex")}if(!ige.isMobile){$("#friends-panel").removeClass("d-none")}this.changesForMobile(true);this.toggleScoreBoard(false);this.toggleLeaderBoard(false);this.toggleGameSuggestionCard(false);$.ajax({type:"GET",url:`/api/game-server/${gameId}`,success:function(res){if(res.status=="success"){var servers=res.message;var serversList="";var index=0;function separate(str){var alphabets="";var numbers="";var chars=str.split("");var numberRegex=/[0-9]/;while(chars.length){var char=chars[chars.length-1];if(numberRegex.test(char)){numbers=char+numbers;chars.pop()}else{break}}return{alphabets:chars.join(""),numbers:numbers}}servers.forEach(function(server){var protocol=location.protocol.indexOf("https")>-1?"wss":"ws";var dataUrl=`${protocol}://${server.ip}${server.port?`:${server.port}`:""}`;if(server){var serverIP=server.ip.slice(0,server.ip.indexOf("."));var separated=separate(serverIP);var optionText=`${separated.alphabets} ${separated.numbers}`;var acceptingPlayers=server.acceptingPlayers?"":" not accepting players";serversList+=`${"`}if(selectBestServer&&!selectedServer&&server.acceptingPlayers){selectedServer=server}});if(serversList){$("#server-list").html(serversList);ige.client.servers=ige.client.getServersArray();if(selectBestServer&&selectedServer){ige.client.server=selectedServer.id;$("#server-list").val(selectedServer.id);$("#play-game-button").hide();$("#change-server").show()}else{$("#server-list").val(ige.client.server.id)}self.getServerPing()}else{$("#server-list").hide()}}$("#menu-wrapper").removeClass("d-none").addClass("d-flex")}})}},getServerPing:function(shouldPickOneWithLeast){var serverOptions=$("option.game-server:enabled");var promises=[];var self=this},getPing:function(serverOption,duration){return new Promise(function promiseFunction(resolve,reject){var data=$(serverOption).data();var socket=new WebSocket(`${data.url}/?token=`);var ping=Number.MAX_VALUE;socket.onopen=function(event){socket.send(JSON.stringify({type:"ping",sentAt:Date.now()}));setTimeout(function(){if(socket.readyState!==WebSocket.CLOSED&&socket.readyState!==WebSocket.CLOSING){socket.close();var existingText=$(serverOption).text();$(serverOption).text(`${existingText} (${Number.POSITIVE_INFINITY} ms)`);resolve({server:serverOption,ping:ping})}},5000)};socket.onmessage=function(event){var jsonString=LZString.decompressFromUTF16(event.data);var json=JSON.parse(jsonString);if(json.type==="pong"){ping=Date.now()-json.clientSentAt;var existingText=$(serverOption).text();socket.close();console.log(json);$(serverOption).text(`${existingText} (${ping} ms)`);resolve({server:serverOption,ping:ping})}};socket.onerror=function(err){console.log("Error while testing ping",err);reject(err)}})},changesForMobile:function(isMenuVisible){if(ige.isMobile){var loginDiv=$("#login-div");var myScoreDiv=$("#my-score-div");var leaderBoard=$("#leaderboard");var topText=$(".ui-text-top");var topMenuButtons=$("#top-menu-buttons");var friendsPanel=$("#friends-panel");var mobileChatBox=$("#mobile-chat-box");var shopButton=$("#mobile-shop-button");var shopButton=$("#mobile-shop-button");var homeButton=$("#home-button");if(isMenuVisible){topMenuButtons.addClass("d-none");leaderBoard.addClass("d-none");topText.addClass("d-none");homeButton.removeClass("d-none");myScoreDiv.removeClass("d-block");loginDiv.removeClass("hide-on-mobile");friendsPanel.addClass("d-none");mobileChatBox.addClass("d-none");shopButton.removeClass("d-inline");homeButton.removeClass("d-none")}else{topMenuButtons.removeClass("d-none");leaderBoard.removeClass("d-none");topText.removeClass("d-none");homeButton.addClass("d-none");myScoreDiv.addClass("d-block");loginDiv.addClass("hide-on-mobile");mobileChatBox.removeClass("d-none invisible");shopButton.addClass("d-inline")}$("#modd-shop-modal").css({fontSize:11});var allControls=ige.mobileControls.controls;if(allControls){for(var k in allControls){var control=allControls[k];control&&control.opacity&&control.opacity(isMenuVisible?0:0.5)}}if(ige.miniMap&&ige.miniMap.miniMap){var newWidth=isMenuVisible?0:ige.miniMap.maxMapDimension.width;ige.miniMap.miniMap.width(newWidth)}}},hideMenu:function(){$("#menu-wrapper").removeClass("d-flex").addClass("d-none");if(!ige.isMobile){$("#friends-panel").addClass("d-none")}this.changesForMobile(false);this.toggleScoreBoard(true);this.toggleLeaderBoard(true);this.toggleGameSuggestionCard(true)},toggleMenu:function(){if($("#menu-wrapper").is(":visible")){this.hideMenu()}else{this.showMenu()}},clipImageForShop:function(){var skins=$("#menu-purchasables")[0]?$("#menu-purchasables")[0].children:[];for(var i=0;i",{src:ige.game.data.settings.images.logo,height:"75px"}))}else{$(".game-title").html(server?server.gameName:"")}}});if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=ThemeComponent}var PlayerUiComponent=$i_54.extend({classId:"PlayerUiComponent",componentId:"playerUi",init:function(entity,options){var self=this;self._entity=entity;self.setupListeners();self.pressedButton=false;self.lastInputValue="";self.dialogue={message:null,messagePrinter:null}},setupListeners:function(){var self=this;$("#player-input-modal").on("hidden.bs.modal",function(){if(self.pressedButton){ige.network.send("playerCustomInput",{status:"submitted",inputText:self.lastInputValue});self.lastInputValue=""}else{ige.network.send("playerCustomInput",{status:"dismissed"})}$("#player-input-modal").removeClass("d-flex")});$("#custom-modal").on("hidden.bs.modal",function(){$("#custom-modal").removeClass("d-flex")});$("#custom-modal").on("shown.bs.modal",function(){$("#custom-modal-cancel").focus()});$("#player-input-modal").on("shown.bs.modal",function(){if(self.isDismissibleInputModalShown){$("#player-input-cancel").focus()}else{$("#player-input-field").focus()}});$("button#player-input-submit").on("click",function(){self.lastInputValue=$("#player-input-field").val();self.pressedButton=true;$("#player-input-modal").modal("hide")});$("button#player-input-cancel").on("click",function(){self.pressedButton=false;ige.network.send("playerCustomInput",{status:"cancelled"});$("#player-input-modal").modal("hide")})},updatePlayerAttributesDiv:function(attributes){var self=this;$("#players-attribute-div").html("");var attributeTypes=ige.game.data.attributeTypes;if(attributeTypes==undefined)return;for(var attrKey in attributes){var attr=attributes[attrKey];if(attr){if(!attr.isVisible)continue;var attributeType=attributeTypes[attrKey];var name=attributeType?attributeType.name:attr.name;var attrName=$("",{class:`pt-attribute-${attrKey}`});var attrValue=$("",{class:`pt-attribute-value-${attrKey}`});$("#players-attribute-div").append(attrName).append(attrValue).append($("
        "));attrName.text(`${name}: `);if(attr.value%1===0){attr.value=parseInt(attr.value)}else{if(attr.decimalPlaces!=undefined&&attr.decimalPlaces!=null){var decimalPlace=parseInt(attr.decimalPlaces);if(decimalPlace!=NaN){attr.value=parseFloat(attr.value).toFixed(decimalPlace)}else{attr.value=parseFloat(attr.value).toFixed(2)}}else{attr.value=parseFloat(attr.value).toFixed(2)}}var value=attr.value&&attr.value.toLocaleString("en-US")||0;attrValue.text(value)}}if($("#modd-item-shop-modal").hasClass("show")){ige.shop.openItemShop()}},updatePlayerCoin:function(newValue){var coin=parseInt($(".player-coins").html());if(coin!=NaN){$(".player-coins").html(parseInt(newValue))}},showFriendsModal:function(config){$("#invite-friends-modal").modal("show")},showInputModal:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;self.isDismissibleInputModalShown=config.isDismissible;$("#player-input-field-label").html(config.fieldLabel||"Field");$("#player-input-field").val("");$("#player-input-modal").addClass("d-flex");$("#player-input-modal").modal({backdrop:config.isDismissible?true:"static",keyboard:config.isDismissible});if(config.isDismissible){$("#player-input-cancel-container").show();$("#player-input-modal-dismiss-button").show()}else{$("#player-input-cancel-container").hide();$("#player-input-modal-dismiss-button").hide()}$("#player-input-modal").modal("show");self.pressedButton=false},showCustomModal:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;$("#custom-modal .content").html(config.content||"");if(config.title){$("#custom-modal .modal-title").html(config.title);$("#custom-modal .modal-header").show()}else{$("#custom-modal .modal-header").hide()}$("#custom-modal").addClass("d-flex");$("#custom-modal").modal({backdrop:config.isDismissible?true:"static",keyboard:config.isDismissible});if(config.isDismissible){$("#custom-modal-cancel-container").show();$("#custom-modal-dismiss-button").show()}else{$("#custom-modal-cancel-container").hide();$("#custom-modal-dismiss-button").hide()}$("#custom-modal").modal("show");self.pressedButton=false},openWebsite:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;function openTab(){var newWin=window.open(config.url);if(!newWin||newWin.closed||typeof newWin.closed=="undefined"){swal({title:"Please allow Popups",text:"Your browser is blocking the content modd.io is trying to display",imageWidth:300,imageUrl:"/assets/images/enable-popup.gif",imageClass:"rounded border"})}}var isExternal=!new URL(config.url).hostname.includes("modd.io");if(isExternal){swal({html:`You are being redirected to ${config.url}.
        Are you sure you want to visit this external site?`,type:"warning",showCancelButton:true,confirmButtonText:"Yes"}).then(result=>{if(result.value){openTab()}})}else{openTab()}},showWebsiteModal:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;$("#website-modal").find("iframe").attr("src",config.url);$("#website-modal").modal({backdrop:config.isDismissible?true:"static",keyboard:config.isDismissible})},showSocialShareModal:function(config){var self=this;config.isDismissible=config.isDismissible===undefined?true:!!config.isDismissible;$("#social-share-modal").modal({backdrop:config.isDismissible?true:"static",keyboard:config.isDismissible})},openDialogueModal:function(dialogueId,extraData){var self=this;function getDialogueInstance(dialogue){var playerName=extraData&&extraData.playerName;dialogue=JSON.parse(JSON.stringify(dialogue));if(dialogue.message.indexOf("%PLAYER_NAME%")>-1&&playerName){dialogue.message=dialogue.message.replace(/%PLAYER_NAME%/g,playerName)}var variables=dialogue.message.match(new RegExp("\\$.+?\\$","g"));if(variables&&variables.length){variables.forEach(function(variable){var variableName=variable.split("$")[1];if(extraData.variables.hasOwnProperty(variableName)){var variableValue=extraData.variables[variableName];dialogue.message=dialogue.message.replace(new RegExp(`\\$${variableName}\\$`,"g"),variableValue)}})}dialogue.messageFragments=dialogue.message.split("%br%");dialogue.currentFragmentIndex=0;dialogue.areAllMessagesPrinted=function(){return this.currentFragmentIndex>=this.messageFragments.length};dialogue.getNextMessage=function(){return dialogue.messageFragments[dialogue.currentFragmentIndex++]};dialogue.hasOptions=function(){return Object.keys(dialogue.options).length>0};dialogue.areOptionsRendered=false;return dialogue}function initModal(){$("#modd-dialogue-message").html("");$("#modd-dialogue-image").attr("src","");$("#modd-dialogue-options-container").addClass("d-none");$("#modd-dialogue-skip-hint").addClass("d-none");if(self.dialogue.messagePrinter){clearInterval(self.dialogue.messagePrinter)}if(dialogue.image){$("#modd-dialogue-image-container").removeClass("d-none");$("#modd-dialogue-message-container").addClass("col-8");$("#modd-dialogue-message-container").addClass("pl-md-0");$("#modd-dialogue-message-container").removeClass("col-12");$("#modd-dialogue-image").attr("src",dialogue.image)}else{$("#modd-dialogue-image-container").addClass("d-none");$("#modd-dialogue-message-container").removeClass("col-8");$("#modd-dialogue-message-container").addClass("col-12");$("#modd-dialogue-image").attr("src","")}$(document).on("keydown.modd-dialogue",keyboardListener);$(document).on("click.modd-dialogue",skipText)}function printingCompleted(){window.isPrintingDialogue=false;if(dialogue.areAllMessagesPrinted()){if(dialogue.hasOptions()){if(!dialogue.areOptionsRendered){showOptions()}}else{$("#modd-dialogue-skip-hint").removeClass("d-none")}}else{$("#modd-dialogue-skip-hint").removeClass("d-none")}}function showOptions(){$("#modd-dialogue-options").html("");for(var key in dialogue.options){var optionObject=dialogue.options[key];var button=$("