made with requirebin
Created
July 21, 2016 17:11
-
-
Save jtenner/a39a9bc546b34193738c27b9c2b7501e to your computer and use it in GitHub Desktop.
requirebin sketch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var e2d = require('e2d'); | |
var p2 = require('p2'); | |
var r = e2d.Renderer.create(800, 600); | |
var cvs = e2d.Canvas.create(800, 600); | |
r.ready(); | |
r.on('frame', function() { | |
if (!r.mouseData.clicked && r.mouseData.state === 'down') { | |
cvs.render( | |
e2d.moveTo(r.previousMouseData.x, r.previousMouseData.y), | |
e2d.lineTo(r.mouseData.x, r.mouseData.y), | |
e2d.stroke() | |
); | |
} | |
return r.render( | |
e2d.clearRect(800, 600), | |
e2d.drawCanvas(cvs) | |
); | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setTimeout(function(){require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({e2d:[function(require,module,exports){(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["e2d"]=factory();else root["e2d"]=factory()})(this,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)}([function(module,exports,__webpack_require__){"use strict";var src=__webpack_require__(1),path=__webpack_require__(11);module.exports=src.keys().reduce(function(index,key){index[path.basename(key,path.extname(key))]=src(key);return index},{})},function(module,exports,__webpack_require__){var map={"./Canvas.js":2,"./Img.js":10,"./Instruction.js":13,"./Renderer.js":3,"./addColorStop.js":14,"./arc.js":15,"./arcTo.js":16,"./beginPath.js":17,"./bezierCurveTo.js":18,"./clearRect.js":19,"./clip.js":20,"./clipPath.js":21,"./closePath.js":22,"./createClass.js":23,"./createImagePattern.js":24,"./createLinearGradient.js":4,"./createRadialGradient.js":5,"./createRegularPolygon.js":25,"./drawCanvas.js":26,"./drawImage.js":27,"./ellipse.js":28,"./fill.js":29,"./fillArc.js":30,"./fillCanvas.js":31,"./fillImage.js":32,"./fillImagePattern.js":33,"./fillRect.js":34,"./fillStyle.js":35,"./fillText.js":36,"./globalAlpha.js":37,"./globalCompositeOperation.js":38,"./hitRect.js":39,"./hitRegion.js":40,"./imageSmoothingEnabled.js":41,"./lineStyle.js":42,"./lineTo.js":43,"./measureText.js":44,"./moveTo.js":45,"./moveToLineTo.js":46,"./path.js":47,"./placeHolder.js":48,"./quadraticCurveTo.js":49,"./rect.js":50,"./resetTransform.js":51,"./rotate.js":53,"./scale.js":54,"./setTransform.js":52,"./shadowStyle.js":55,"./skewX.js":56,"./skewY.js":57,"./stroke.js":58,"./strokeArc.js":59,"./strokeRect.js":60,"./strokeStyle.js":61,"./strokeText.js":62,"./text.js":63,"./textStyle.js":64,"./transform.js":65,"./transformPoints.js":8,"./translate.js":66};function webpackContext(req){return __webpack_require__(webpackContextResolve(req))}function webpackContextResolve(req){return map[req]||function(){throw new Error("Cannot find module '"+req+"'.")}()}webpackContext.keys=function webpackContextKeys(){return Object.keys(map)};webpackContext.resolve=webpackContextResolve;module.exports=webpackContext;webpackContext.id=1},function(module,exports,__webpack_require__){"use strict";function Canvas(width,height){var Renderer=__webpack_require__(3);this.renderer=new Renderer(width,height,window.document.createElement("div"));this.fillPattern=null;this.skipPatternCreation=false;return Object.seal(this)}Canvas.prototype.render=function render(children){var result=[],i;for(i=0;i<arguments.length;i++){result.push(arguments[i])}this.renderer.render(result);if(!this.skipPatternCreation){this.fillPattern=this.renderer.ctx.createPattern(this.renderer.canvas,"no-repeat")}return this};Canvas.prototype.style=function style(){var defs=[];for(var i=0;i<arguments.length;i++){defs.push(arguments[i])}this.renderer.style.apply(this.renderer,defs);return this};Canvas.prototype.toImage=function toImage(imageID){return this.renderer.toImage()};Canvas.prototype.resize=function resize(width,height){this.renderer.resize(+width,+height);return this};Object.defineProperty(Canvas.prototype,"height",{get:function(){return this.renderer.canvas.width},enumerable:true,configurable:false});Object.defineProperty(Canvas.prototype,"width",{get:function(){return this.renderer.canvas.width},enumerable:true,configurable:false});Canvas.create=function create(width,height,id){return new Canvas(width,height,id)};Object.seal(Canvas);Object.seal(Canvas.prototype);module.exports=Canvas},function(module,exports,__webpack_require__){"use strict";var createLinearGradient=__webpack_require__(4),createRadialGradient=__webpack_require__(5),events=__webpack_require__(6),keycode=__webpack_require__(7),transformPoints=__webpack_require__(8),pointInPolygon=__webpack_require__(9),identity=[1,0,0,1,0,0],Img=__webpack_require__(10);function Renderer(width,height,parent,opts){events.EventEmitter.call(this);opts=opts||{};this.transformStack=new Float64Array(((opts.transformStackCount||500)+1)*6);this.transformStackIndex=6;this.transformStack.set(identity);this.fillStyleStack=[];this.strokeStyleStack=[];this.lineStyleStack=[];this.textStyleStack=[];this.shadowStyleStack=[];this.globalAlphaStack=[];this.imageSmoothingEnabledStack=[];this.globalCompositeOperationStack=[];this.pi2=Math.PI*2;this.isReady=false;this.mouseData={x:0,y:0,state:"up",clicked:0,activeRegions:[]};this.previousMouseData={x:0,y:0,state:"up",clicked:0,activeRegions:[]};this.lastMouseEvent=null;this.ranMouseEvent=false;this.mouseRegions=[];this.activeRegions=[];this.styleQueue=[];this.keyData={};this.touchData={touches:[],ids:[]};this.lastTouchEvent=null;this.ranTouchEvent=false;this.touchRegions=[];if(parent&&parent.nodeType===1){this.parent=parent}else{this.parent=window.document.createElement("div");this.parent.style.margin="0 auto";this.parent.style.width=width+"px";this.parent.style.height=height+"px";window.document.body.appendChild(this.parent)}if(!width||width<=0){width=window.innerWidth}if(!height||height<=0){height=window.innerHeight}this.canvas=window.document.createElement("canvas");this.canvas.tabIndex=1;this.ctx=this.canvas.getContext("2d");this.canvas.width=width;this.canvas.height=height;this.parent.appendChild(this.canvas);this.hookMouseEvents();this.hookKeyboardEvents();this.hookTouchEvents();this.boundHookRenderFunction=this.hookRender.bind(this);return Object.seal(this)}Renderer.prototype=Object.create(events.EventEmitter.prototype);Renderer.prototype.render=function render(args){var i,len,child,props,type,cache,matrix=[1,0,0,1,0,0],ctx=this.ctx,children=[],concat=children.concat;this.fillStyleStack.splice(0,this.fillStyleStack.length);this.strokeStyleStack.splice(0,this.strokeStyleStack.length);this.lineStyleStack.splice(0,this.lineStyleStack.length);this.textStyleStack.splice(0,this.textStyleStack.length);this.shadowStyleStack.splice(0,this.shadowStyleStack.length);this.globalCompositeOperationStack.splice(0,this.globalCompositeOperationStack.length);this.globalAlphaStack.splice(0,this.globalAlphaStack.length);this.imageSmoothingEnabledStack.splice(0,this.imageSmoothingEnabledStack.length);for(i=0,len=arguments.length;i<len;i++){children.push(arguments[i])}for(i=0,len=children.length;i<len;i++){child=children[i];if(child&&child.constructor===Array){children=concat.apply([],children);child=children[i];while(child&&child.constructor===Array){children=concat.apply([],children);child=children[i]}len=children.length}if(!child){continue}props=child.props;type=child.type;if(type==="transform"){matrix[0]=this.transformStack[this.transformStackIndex-6];matrix[1]=this.transformStack[this.transformStackIndex-5];matrix[2]=this.transformStack[this.transformStackIndex-4];matrix[3]=this.transformStack[this.transformStackIndex-3];matrix[4]=this.transformStack[this.transformStackIndex-2];matrix[5]=this.transformStack[this.transformStackIndex-1];this.transformStackIndex+=6;if(this.transformStackIndex>this.transformStack.length){this.increaseTransformStackSize()}this.transformStack[this.transformStackIndex-6]=matrix[0]*props[0]+matrix[2]*props[1];this.transformStack[this.transformStackIndex-5]=matrix[1]*props[0]+matrix[3]*props[1];this.transformStack[this.transformStackIndex-4]=matrix[0]*props[2]+matrix[2]*props[3];this.transformStack[this.transformStackIndex-3]=matrix[1]*props[2]+matrix[3]*props[3];this.transformStack[this.transformStackIndex-2]=matrix[0]*props[4]+matrix[2]*props[5]+matrix[4];this.transformStack[this.transformStackIndex-1]=matrix[1]*props[4]+matrix[3]*props[5]+matrix[5];ctx.setTransform(this.transformStack[this.transformStackIndex-6],this.transformStack[this.transformStackIndex-5],this.transformStack[this.transformStackIndex-4],this.transformStack[this.transformStackIndex-3],this.transformStack[this.transformStackIndex-2],this.transformStack[this.transformStackIndex-1]);continue}if(type==="setTransform"){this.transformStackIndex+=6;if(this.transformStackIndex>this.transformStack.length){this.increaseTransformStackSize()}this.transformStack[this.transformStackIndex-6]=props[0];this.transformStack[this.transformStackIndex-5]=props[1];this.transformStack[this.transformStackIndex-4]=props[2];this.transformStack[this.transformStackIndex-3]=props[3];this.transformStack[this.transformStackIndex-2]=props[4];this.transformStack[this.transformStackIndex-1]=props[5];ctx.setTransform(props[0],props[1],props[2],props[3],props[4],props[5]);continue}if(type==="scale"){matrix[0]=this.transformStack[this.transformStackIndex-6];matrix[1]=this.transformStack[this.transformStackIndex-5];matrix[2]=this.transformStack[this.transformStackIndex-4];matrix[3]=this.transformStack[this.transformStackIndex-3];matrix[4]=this.transformStack[this.transformStackIndex-2];matrix[5]=this.transformStack[this.transformStackIndex-1];this.transformStackIndex+=6;if(this.transformStackIndex>this.transformStack.length){this.increaseTransformStackSize()}this.transformStack[this.transformStackIndex-6]=matrix[0]*props.x;this.transformStack[this.transformStackIndex-5]=matrix[1]*props.x;this.transformStack[this.transformStackIndex-4]=matrix[2]*props.y;this.transformStack[this.transformStackIndex-3]=matrix[3]*props.y;this.transformStack[this.transformStackIndex-2]=matrix[4];this.transformStack[this.transformStackIndex-1]=matrix[5];ctx.setTransform(this.transformStack[this.transformStackIndex-6],this.transformStack[this.transformStackIndex-5],this.transformStack[this.transformStackIndex-4],this.transformStack[this.transformStackIndex-3],this.transformStack[this.transformStackIndex-2],this.transformStack[this.transformStackIndex-1]);continue}if(type==="translate"){matrix[0]=this.transformStack[this.transformStackIndex-6];matrix[1]=this.transformStack[this.transformStackIndex-5];matrix[2]=this.transformStack[this.transformStackIndex-4];matrix[3]=this.transformStack[this.transformStackIndex-3];matrix[4]=this.transformStack[this.transformStackIndex-2];matrix[5]=this.transformStack[this.transformStackIndex-1];this.transformStackIndex+=6;if(this.transformStackIndex>this.transformStack.length){this.increaseTransformStackSize()}this.transformStack[this.transformStackIndex-6]=matrix[0];this.transformStack[this.transformStackIndex-5]=matrix[1];this.transformStack[this.transformStackIndex-4]=matrix[2];this.transformStack[this.transformStackIndex-3]=matrix[3];this.transformStack[this.transformStackIndex-2]=matrix[4]+matrix[0]*props.x+matrix[2]*props.y;this.transformStack[this.transformStackIndex-1]=matrix[5]+matrix[1]*props.x+matrix[3]*props.y;ctx.setTransform(this.transformStack[this.transformStackIndex-6],this.transformStack[this.transformStackIndex-5],this.transformStack[this.transformStackIndex-4],this.transformStack[this.transformStackIndex-3],this.transformStack[this.transformStackIndex-2],this.transformStack[this.transformStackIndex-1]);continue}if(type==="rotate"){matrix[0]=this.transformStack[this.transformStackIndex-6];matrix[1]=this.transformStack[this.transformStackIndex-5];matrix[2]=this.transformStack[this.transformStackIndex-4];matrix[3]=this.transformStack[this.transformStackIndex-3];matrix[4]=this.transformStack[this.transformStackIndex-2];matrix[5]=this.transformStack[this.transformStackIndex-1];this.transformStackIndex+=6;if(this.transformStackIndex>this.transformStack.length){this.increaseTransformStackSize()}this.transformStack[this.transformStackIndex-6]=matrix[0]*props.cos+matrix[2]*props.sin;this.transformStack[this.transformStackIndex-5]=matrix[1]*props.cos+matrix[3]*props.sin;this.transformStack[this.transformStackIndex-4]=matrix[0]*-props.sin+matrix[2]*props.cos;this.transformStack[this.transformStackIndex-3]=matrix[1]*-props.sin+matrix[3]*props.cos;this.transformStack[this.transformStackIndex-2]=matrix[4];this.transformStack[this.transformStackIndex-1]=matrix[5];ctx.setTransform(this.transformStack[this.transformStackIndex-6],this.transformStack[this.transformStackIndex-5],this.transformStack[this.transformStackIndex-4],this.transformStack[this.transformStackIndex-3],this.transformStack[this.transformStackIndex-2],this.transformStack[this.transformStackIndex-1]);continue}if(type==="skewX"){matrix[0]=this.transformStack[this.transformStackIndex-6];matrix[1]=this.transformStack[this.transformStackIndex-5];matrix[2]=this.transformStack[this.transformStackIndex-4];matrix[3]=this.transformStack[this.transformStackIndex-3];matrix[4]=this.transformStack[this.transformStackIndex-2];matrix[5]=this.transformStack[this.transformStackIndex-1];this.transformStackIndex+=6;if(this.transformStackIndex>this.transformStack.length){this.increaseTransformStackSize()}this.transformStack[this.transformStackIndex-6]=matrix[0];this.transformStack[this.transformStackIndex-5]=matrix[1];this.transformStack[this.transformStackIndex-4]=matrix[0]*props.x+matrix[2];this.transformStack[this.transformStackIndex-3]=matrix[1]*props.x+matrix[3];this.transformStack[this.transformStackIndex-2]=matrix[4];this.transformStack[this.transformStackIndex-1]=matrix[5];ctx.setTransform(this.transformStack[this.transformStackIndex-6],this.transformStack[this.transformStackIndex-5],this.transformStack[this.transformStackIndex-4],this.transformStack[this.transformStackIndex-3],this.transformStack[this.transformStackIndex-2],this.transformStack[this.transformStackIndex-1]);continue}if(type==="skewY"){matrix[0]=this.transformStack[this.transformStackIndex-6];matrix[1]=this.transformStack[this.transformStackIndex-5];matrix[2]=this.transformStack[this.transformStackIndex-4];matrix[3]=this.transformStack[this.transformStackIndex-3];matrix[4]=this.transformStack[this.transformStackIndex-2];matrix[5]=this.transformStack[this.transformStackIndex-1];this.transformStackIndex+=6;if(this.transformStackIndex>this.transformStack.length){this.increaseTransformStackSize()}this.transformStack[this.transformStackIndex-6]=matrix[0]*1+matrix[2]*props.y;this.transformStack[this.transformStackIndex-5]=matrix[1]*1+matrix[3]*props.y;this.transformStack[this.transformStackIndex-4]=matrix[2];this.transformStack[this.transformStackIndex-3]=matrix[3];this.transformStack[this.transformStackIndex-2]=matrix[4];this.transformStack[this.transformStackIndex-1]=matrix[5];ctx.setTransform(this.transformStack[this.transformStackIndex-6],this.transformStack[this.transformStackIndex-5],this.transformStack[this.transformStackIndex-4],this.transformStack[this.transformStackIndex-3],this.transformStack[this.transformStackIndex-2],this.transformStack[this.transformStackIndex-1]);continue}if(type==="restore"){this.transformStackIndex-=6;matrix[0]=this.transformStack[this.transformStackIndex-6];matrix[1]=this.transformStack[this.transformStackIndex-5];matrix[2]=this.transformStack[this.transformStackIndex-4];matrix[3]=this.transformStack[this.transformStackIndex-3];matrix[4]=this.transformStack[this.transformStackIndex-2];matrix[5]=this.transformStack[this.transformStackIndex-1];ctx.setTransform(matrix[0],matrix[1],matrix[2],matrix[3],matrix[4],matrix[5]);continue}if(type==="fillRect"){ctx.fillRect(props.x,props.y,props.width,props.height);continue}if(type==="strokeRect"){ctx.strokeRect(props.x,props.y,props.width,props.height);continue}if(type==="clearRect"){ctx.clearRect(props.x,props.y,props.width,props.height);continue}if(type==="rect"){ctx.rect(props.x,props.y,props.width,props.height);continue}if(type==="fillStyle"){this.fillStyleStack.push(ctx.fillStyle);ctx.fillStyle=props.value;continue}if(type==="strokeStyle"){this.strokeStyleStack.push(ctx.strokeStyle);ctx.strokeStyle=props.value;continue}if(type==="endFillStyle"){ctx.fillStyle=this.fillStyleStack.pop();continue}if(type==="endStrokeStyle"){ctx.strokeStyle=this.strokeStyleStack.pop();continue}if(type==="lineStyle"){this.lineStyleStack.push({lineWidth:ctx.lineWidth,lineCap:ctx.lineCap,lineJoin:ctx.lineJoin,miterLimit:ctx.miterLimit,lineDash:ctx.getLineDash(),lineDashOffset:ctx.lineDashOffset});if(props.lineWidth!==null){ctx.lineWidth=props.lineWidth}if(props.lineCap!==null){ctx.lineCap=props.lineCap}if(props.lineJoin!==null){ctx.lineJoin=props.lineJoin}if(props.miterLimit!==null){ctx.miterLimit=props.miterLimit}if(props.lineDash.length>0){ctx.setLineDash(props.lineDash)}if(props.lineDashOffset!==null){ctx.lineDashOffset=props.lineDashOffset}continue}if(type==="endLineStyle"){cache=this.lineStyleStack.pop();ctx.lineWidth=cache.lineWidth;ctx.lineCap=cache.lineCap;ctx.lineJoin=cache.lineJoin;ctx.miterLimit=cache.miterLimit;ctx.setLineDash(cache.lineDash);ctx.lineDashOffset=cache.lineDashOffset;continue}if(type==="textStyle"){this.textStyleStack.push({font:ctx.font,textAlign:ctx.textAlign,textBaseline:ctx.textBaseline,direction:ctx.direction});if(props.font!==null){ctx.font=props.font}if(props.textAlign!==null){ctx.textAlign=props.textAlign}if(props.textBaseline!==null){ctx.textBaseline=props.textBaseline}if(props.lineJoin!==null){ctx.direction=props.direction}continue}if(type==="endTextStyle"){cache=this.textStyleStack.pop();ctx.font=cache.font;ctx.textAlign=cache.textAlign;ctx.textBaseline=cache.textBaseline;ctx.direction=cache.direction;continue}if(type==="shadowStyle"){this.shadowStyleStack.push({shadowBlur:ctx.shadowBlur,shadowColor:ctx.shadowColor,shadowOffsetX:ctx.shadowOffsetX,shadowOffsetY:ctx.shadowOffsetY});if(props.shadowBlur!==null){ctx.shadowBlur=props.shadowBlur}if(props.shadowColor!==null){ctx.shadowColor=props.shadowColor}if(props.shadowOffsetX!==null){ctx.shadowOffsetX=props.shadowOffsetX}if(props.shadowOffsetY!==null){ctx.shadowOffsetY=props.shadowOffsetY}continue}if(type==="endShadowStyle"){cache=this.shadowStyleStack.pop();ctx.shadowBlur=cache.shadowBlur;ctx.shadowColor=cache.shadowColor;ctx.shadowOffsetX=cache.shadowOffsetX;ctx.shadowOffsetY=cache.shadowOffsetY;continue}if(type==="strokeText"){if(props.maxWidth){ctx.strokeText(props.text,props.x,props.y,props.maxWidth);continue}ctx.strokeText(props.text,props.x,props.y);continue}if(type==="fillText"){if(props.maxWidth){ctx.fillText(props.text,props.x,props.y,props.maxWidth);continue}ctx.fillText(props.text,props.x,props.y);continue}if(type==="text"){if(props.maxWidth!==0){if(props.fill){ctx.fillText(props.text,props.x,props.y,props.maxWidth)}if(props.stroke){ctx.strokeText(props.text,props.x,props.y,props.maxWidth)}continue}if(props.fill){ctx.fillText(props.text,props.x,props.y)}if(props.stroke){ctx.strokeText(props.text,props.x,props.y)}continue}if(type==="drawImage"){if(!props.img){continue}cache=props.img.imageElement||props.img||new Image;ctx.drawImage(cache||new Image,props.dx,props.dy);continue}if(type==="drawImageSize"){if(!props.img){continue}cache=props.img.imageElement||props.img||new Image;ctx.drawImage(cache,props.dx,props.dy,props.dWidth,props.dHeight);continue}if(type==="drawImageSource"){if(!props.img){continue}cache=props.img.imageElement||props.img||new Image;ctx.drawImage(cache,props.sx,props.sy,props.sWidth,props.sHeight,props.dx,props.dy,props.dWidth,props.dHeight);continue}if(type==="fillImagePattern"){if(!props.img){continue}ctx.fillStyle=props.img.imagePatternRepeat;ctx.translate(props.dx,props.dy);ctx.fillRect(0,0,props.dWidth,props.dHeight);ctx.restore();continue}if(type==="fillImage"){if(!props.img){continue}cache=props.img.imageElement;ctx.save();ctx.fillStyle=props.img.imagePattern;ctx.translate(props.dx,props.dy);ctx.fillRect(0,0,cache.width,cache.height);ctx.restore();continue}if(type==="fillImageSize"){if(!props.img){continue}cache=props.img.imageElement;ctx.save();ctx.fillStyle=props.img.imagePattern;ctx.translate(props.dx,props.dy);ctx.scale(props.dWidth/cache.width,props.dHeight/cache.height);ctx.fillRect(0,0,cache.width,cache.height);ctx.restore();continue}if(type==="fillImageSource"){if(!props.img){continue}ctx.save();ctx.fillStyle=props.img.imagePattern;ctx.translate(props.dx,props.dy);ctx.scale(props.dWidth/props.sWidth,props.dHeight/props.sHeight);ctx.translate(-props.sx,-props.sy);ctx.fillRect(props.sx,props.sy,props.sWidth,props.sHeight);ctx.restore();continue}if(type==="fillCanvas"){if(!props.img){continue}cache=props.img;ctx.save();ctx.fillStyle=cache.fillPattern;ctx.translate(props.dx,props.dy);ctx.fillRect(0,0,cache.width,cache.height);ctx.restore();continue}if(type==="fillCanvasSize"){if(!props.img){continue}cache=props.img;ctx.save();ctx.fillStyle=cache.fillPattern;ctx.translate(props.dx,props.dy);ctx.scale(props.dWidth/cache.width,props.dHeight/cache.height);ctx.fillRect(0,0,cache.width,cache.height);ctx.restore();continue}if(type==="fillCanvasSource"){if(!props.img){continue}ctx.save();ctx.fillStyle=props.img.fillPattern;ctx.translate(props.dx,props.dy);ctx.scale(props.dWidth/props.sWidth,props.dHeight/props.sHeight);ctx.translate(-props.sx,-props.sy);ctx.fillRect(props.sx,props.sy,props.sWidth,props.sHeight);ctx.restore();continue}if(type==="drawCanvas"){if(!props.img){continue}ctx.drawImage(props.img.renderer.canvas,props.dx,props.dy);continue}if(type==="drawCanvasSize"){if(!props.img){continue}ctx.drawImage(props.img.renderer.canvas,props.dx,props.dy,props.dWidth,props.dHeight);continue}if(type==="drawCanvasSource"){if(!props.img){continue}ctx.drawImage(props.img.renderer.canvas,props.sx,props.sy,props.sWidth,props.sHeight,props.dx,props.dy,props.dWidth,props.dHeight);continue}if(type==="strokeArc"){ctx.beginPath();ctx.arc(props.x,props.y,props.r,props.startAngle,props.endAngle);ctx.closePath();ctx.stroke();continue}if(type==="strokeArc-counterclockwise"){ctx.beginPath();ctx.arc(props.x,props.y,props.r,props.startAngle,props.endAngle,true);ctx.closePath();ctx.stroke();continue}if(type==="fillArc"){ctx.beginPath();ctx.arc(props.x,props.y,props.r,props.startAngle,props.endAngle);ctx.closePath();ctx.fill();continue}if(type==="fillArc-counterclockwise"){ctx.beginPath();ctx.arc(props.x,props.y,props.r,props.startAngle,props.endAngle,true);ctx.closePath();ctx.fill();continue}if(type==="moveTo"){ctx.moveTo(props.x,props.y);continue}if(type==="lineTo"){ctx.lineTo(props.x,props.y);continue}if(type==="bezierCurveTo"){ctx.bezierCurveTo(props.cp1x,props.cp1y,props.cp2x,props.cp2y,props.x,props.y);continue}if(type==="quadraticCurveTo"){ctx.quadraticCurveTo(props.cpx,props.cpy,props.x,props.y);continue}if(type==="anticlockwise-arc"){ctx.arc(props.x,props.y,props.r,props.startAngle,props.endAngle,true);continue}if(type==="arc"){ctx.arc(props.x,props.y,props.r,props.startAngle,props.endAngle);continue}if(type==="full-arc"){ctx.arc(props.x,props.y,props.r,0,this.pi2);continue}if(type==="quick-arc"){ctx.arc(0,0,props.r,0,this.pi2);continue}if(type==="arcTo"){ctx.arcTo(props.x1,props.y1,props.x2,props.y2,props.r);continue}if(type==="anticlockwise-ellipse"){this.save();this.translate(props.x,props.y);this.rotate(props.rotation);this.scale(props.radiusX,props.radiusY);this.arc(0,0,1,props.startAngle,props.endAngle,true);this.restore();continue}if(type==="ellipse"){this.save();this.translate(props.x,props.y);this.rotate(props.rotation);this.scale(props.radiusX,props.radiusY);this.arc(0,0,1,props.startAngle,props.endAngle);this.restore();continue}if(type==="full-ellipse"){this.save();this.translate(props.x,props.y);this.rotate(props.rotation);this.scale(props.radiusX,props.radiusY);this.arc(0,0,1,0,this.pi2);this.restore();continue}if(type==="quick-ellipse"){this.save();this.translate(props.x,props.y);this.scale(props.radiusX,props.radiusY);this.arc(0,0,1,0,this.pi2);this.restore();continue}if(type==="globalCompositeOperation"){this.globalCompositeOperationStack.push(ctx.globalCompositeOperation);ctx.globalCompositeOperation=props.value;continue}if(type==="endGlobalCompositeOperation"){ctx.globalCompositeOperation=this.globalCompositeOperationStack.pop();continue}if(type==="fill"){ctx.fill();continue}if(type==="stroke"){ctx.stroke();continue}if(type==="beginClip"){ctx.save();ctx.beginPath();continue}if(type==="clip"){ctx.clip();continue}if(type==="endClip"){ctx.restore();continue}if(type==="beginPath"){ctx.beginPath();continue}if(type==="closePath"){ctx.closePath();continue}if(type==="globalAlpha"){this.globalAlphaStack.push(ctx.globalAlpha);ctx.globalAlpha*=props.value;continue}if(type==="endGlobalAlpha"){ctx.globalAlpha=this.globalAlphaStack.pop();continue}if(type==="hitRegion"){matrix[0]=this.transformStack[this.transformStackIndex-6];matrix[1]=this.transformStack[this.transformStackIndex-5];matrix[2]=this.transformStack[this.transformStackIndex-4];matrix[3]=this.transformStack[this.transformStackIndex-3];matrix[4]=this.transformStack[this.transformStackIndex-2];matrix[5]=this.transformStack[this.transformStackIndex-1];cache={id:props.id,points:transformPoints(props.points,matrix)};this.mouseRegions.push(cache);this.touchRegions.push(cache);continue}if(type==="imageSmoothingEnabled"){this.imageSmoothingEnabledStack.push(ctx.imageSmoothingEnabled);ctx.imageSmoothingEnabled=props.value;continue}if(type==="endImageSmoothingEnabled"){ctx.imageSmoothingEnabled=this.imageSmoothingEnabledStack.pop();continue}}return this.applyStyles()};Renderer.create=function create(width,height,parent,worker){if(arguments.length>2){return new Renderer(width,height,parent,worker)}if(arguments.length===2){return new Renderer(width,height)}return new Renderer};Renderer.prototype.resize=function(width,height){if(this.canvas.width.toString()!==width.toString()){this.canvas.width=width;if(this.parent!==document.body){this.parent.style.width=width+"px"}}if(this.canvas.height.toString()!==height.toString()){this.canvas.height=height;if(this.parent!==document.body){this.parent.style.height=height+"px"}}};Renderer.prototype.toImage=function toImage(){var Img=__webpack_require__(10);var img=new Img;img.src=this.canvas.toDataURL("image/png");return img};Renderer.prototype.hookRender=function hookRender(){if(this.isReady){this.fireFrame()}return window.requestAnimationFrame(this.boundHookRenderFunction)};Renderer.prototype.cleanupMouseEvents=function cleanupMouseEvents(){this.previousMouseData.x=this.mouseData.x;this.previousMouseData.y=this.mouseData.y;this.previousMouseData.state=this.mouseData.state;this.previousMouseData.clicked=this.mouseData.clicked;this.previousMouseData.activeRegions=this.mouseData.activeRegions.splice(0,this.mouseData.activeRegions.length);this.mouseData.clicked=0;this.ranMouseEvent=false};Renderer.prototype.cleanupTouchEvents=function cleanupTouchEvents(){for(var i=0;i<this.touchData.touches.length;i++){var touch=this.touchData.touches[i];if(!touch.held){this.touchData.touches.splice(i,1);i-=1;continue}touch.previousX=touch.x;touch.previousY=touch.y;touch.touched=false;touch.activeRegions.splice(0,touch.activeRegions.length)}};Renderer.prototype.hookMouseEvents=function hookMouseEvents(){window.document.addEventListener("mousemove",this.mouseMove.bind(this));window.document.addEventListener("mousedown",this.mouseDown.bind(this));return window.document.addEventListener("mouseup",this.mouseUp.bind(this))};Renderer.prototype.hookTouchEvents=function hookTouchEvents(){var listener=this.touchEvent.bind(this);return["touchstart","touchmove","touchend","touchcancel"].forEach(function(evt){return window.document.addEventListener(evt,listener)})};Renderer.prototype.touchEvent=function touchEvent(evt){var rect=this.canvas.getBoundingClientRect(),mousePoint=[0,0],region,i,j;var type=evt.type,touches=evt.changedTouches,touchPoint,touch;for(i=0;i<touches.length;i++){touch=touches.item(i);if(type==="touchstart"){this.touchData.touches.push(touchPoint={x:0,y:0,activeRegions:[],id:touch.identifier,touched:true,moved:false,held:true})}if(type==="touchend"||type==="touchcancel"){for(j=0;j<this.touchData.length;j++){touchPoint=this.touchData.touches[j];if(touchPoint.id===touch.identifier){touchPoint.activeRegions.splice(0,touchPoint.activeRegions.length);touchPoint.held=false;break}}}if(type==="touchmove"){for(j=0;j<this.touchData.length;j++){touchPoint=this.touchData.touches[j];if(touchPoint.id===touch.identifier){touchPoint.moved=true;break}}}mousePoint[0]=touchPoint.x=touch.clientX-rect.left;mousePoint[1]=touchPoint.y=touch.clientY-rect.top;for(j=0;j<this.touchRegions.length;j++){region=this.touchRegions[j];if(pointInPolygon(mousePoint,region.points)){touchPoint.activeRegions.push(region.id)}}}this.lastTouchEvent=evt;this.ranTouchEvent=true;evt.preventDefault();this.emit("touch",this.touchData);return false};Renderer.prototype.mouseMove=function mouseMove(evt){var rect=this.canvas.getBoundingClientRect(),mousePoint=[0,0],region;this.lastMouseEvent=evt;this.ranMouseEvent=true;mousePoint[0]=evt.clientX-rect.left;mousePoint[1]=evt.clientY-rect.top;for(var i=0;i<this.mouseRegions.length;i++){region=this.mouseRegions[i];if(pointInPolygon(mousePoint,region.points)){this.mouseData.activeRegions.push(region.id);this.mouseRegions.splice(this.mouseRegions.indexOf(region),1);i-=1}}this.mouseData.x=mousePoint[0];this.mouseData.y=mousePoint[1];this.emit("mouse",this.mouseData);evt.preventDefault();return false};Renderer.prototype.mouseDown=function mouseMove(evt){if(evt.target===this.canvas){if(this.mouseData.state==="up"){this.mouseData.clicked+=1}this.mouseData.state="down";this.canvas.focus();return this.mouseMove(evt)}};Renderer.prototype.mouseUp=function mouseMove(evt){this.mouseData.state="up";return this.mouseMove(evt)};Renderer.prototype.hookKeyboardEvents=function hookKeyboardEvents(){for(var name in keycode.code){if(keycode.code.hasOwnProperty(name)){this.keyData[name]="up"}}this.canvas.addEventListener("keydown",this.keyDown.bind(this));return window.document.addEventListener("keyup",this.keyUp.bind(this))};Renderer.prototype.keyChange=function keyChange(evt){this.emit("key",this.keyData);evt.preventDefault();return false};Renderer.prototype.keyDown=function keyDown(evt){this.keyData[keycode(evt.keyCode)]="down";return this.keyChange(evt)};Renderer.prototype.keyUp=function keyUp(evt){this.keyData[keycode(evt.keyCode)]="up";return this.keyChange(evt)};Renderer.prototype.fireFrame=function(){if(this.lastMouseEvent&&!this.ranMouseEvent){this.mouseMove(this.lastMouseEvent)}if(this.lastTouchEvent&&!this.ranTouchEvent){this.touchEvent(this.lastMouseEvent)}this.mouseRegions.splice(0,this.mouseRegions.length);this.touchRegions.splice(0,this.touchRegions.length);this.emit("frame",{});this.activeRegions.splice(0,this.activeRegions.length);this.cleanupMouseEvents();this.cleanupTouchEvents();return this};Renderer.prototype.style=function style(){var children=[],styles=[],concat=children.concat,len,i,child,name;for(i=0,len=arguments.length;i<len;i++){children.push(arguments[i])}for(i=0,len=children.length;i<len;i++){child=children[i];if(child&&child.constructor===Array){children=concat.apply([],children);child=children[i];while(child&&child.constructor===Array){children=concat.apply([],children);child=children[i]}len=children.length}if(child){styles.push(child)}}for(i=0;i<styles.length;i++){this.styleQueue.push(styles[i])}return this};Renderer.prototype.applyStyles=function applyStyles(){var styleVal,value;for(var i=0;i<this.styleQueue.length;i++){styleVal=this.styleQueue[i];for(var name in styleVal){if(styleVal.hasOwnProperty(name)){ | |
this.canvas.style[name]=styleVal[name]}}}this.styleQueue.splice(0,this.styleQueue.length);return this};Renderer.prototype.ready=function ready(){this.isReady=true;this.fireFrame();return window.requestAnimationFrame(this.hookRender.bind(this))};Renderer.prototype.measureText=function measureText(font,text){var oldFont=this.ctx.font,result;this.ctx.font=font;result=this.ctx.measureText(text);this.ctx.font=oldFont;return result};Renderer.prototype.increaseTransformStackSize=function increaseTransformStackSize(){var cache=this.transformStack;this.transformStack=new Float64Array(this.transformStack.length+600);this.transformStack.set(cache);return this};Object.defineProperty(Renderer.prototype,"height",{get:function(){return this.canvas.width},enumerable:true,configurable:false});Object.defineProperty(Renderer.prototype,"width",{get:function(){return this.canvas.width},enumerable:true,configurable:false});Object.seal(Renderer);Object.seal(Renderer.prototype);module.exports=Renderer},function(module,exports){"use strict";if(typeof window!=="undefined"){var ctx=window.document.createElement("canvas").getContext("2d")}var concat=[].concat;function createLinearGradient(x0,y0,x1,y1){var grd=ctx.createLinearGradient(x0,y0,x1,y1),children=[];for(var i=0;i<arguments.length;i++){children.push(arguments[i])}for(i=0;i<children.length;i++){while(children[i]&&children[i].constructor===Array){children=concat.apply([],children)}var colorStop=children[i];if(colorStop&&colorStop.type==="addColorStop"){grd.addColorStop(colorStop.props.offset,colorStop.props.color)}}return grd}module.exports=createLinearGradient},function(module,exports){"use strict";if(typeof window!=="undefined"){var ctx=window.document.createElement("canvas").getContext("2d"),concat=[].concat}function createRadialGradient(x0,y0,r0,x1,y1,r1){var grd=ctx.createRadialGradient(x0,y0,r0,x1,y1,r1),children=[];for(var i=0;i<arguments.length;i++){children.push(arguments[i])}for(i=0;i<children.length;i++){while(children[i]&&children[i].constructor===Array){children=concat.apply([],children)}var colorStop=children[i];if(colorStop&&colorStop.type==="addColorStop"){grd.addColorStop(colorStop.props.offset,colorStop.props.color)}}return grd}module.exports=createRadialGradient},function(module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},function(module,exports){exports=module.exports=function(searchInput){if(searchInput&&"object"===typeof searchInput){var hasKeyCode=searchInput.which||searchInput.keyCode||searchInput.charCode;if(hasKeyCode)searchInput=hasKeyCode}if("number"===typeof searchInput)return names[searchInput];var search=String(searchInput);var foundNamedKey=codes[search.toLowerCase()];if(foundNamedKey)return foundNamedKey;var foundNamedKey=aliases[search.toLowerCase()];if(foundNamedKey)return foundNamedKey;if(search.length===1)return search.charCodeAt(0);return undefined};var codes=exports.code=exports.codes={backspace:8,tab:9,enter:13,shift:16,ctrl:17,alt:18,"pause/break":19,"caps lock":20,esc:27,space:32,"page up":33,"page down":34,end:35,home:36,left:37,up:38,right:39,down:40,insert:45,"delete":46,command:91,"left command":91,"right command":93,"numpad *":106,"numpad +":107,"numpad -":109,"numpad .":110,"numpad /":111,"num lock":144,"scroll lock":145,"my computer":182,"my calculator":183,";":186,"=":187,",":188,"-":189,".":190,"/":191,"`":192,"[":219,"\\":220,"]":221,"'":222};var aliases=exports.aliases={windows:91,"⇧":16,"⌥":18,"⌃":17,"⌘":91,ctl:17,control:17,option:18,pause:19,"break":19,caps:20,"return":13,escape:27,spc:32,pgup:33,pgdn:34,ins:45,del:46,cmd:91};for(i=97;i<123;i++)codes[String.fromCharCode(i)]=i-32;for(var i=48;i<58;i++)codes[i-48]=i;for(i=1;i<13;i++)codes["f"+i]=i+111;for(i=0;i<10;i++)codes["numpad "+i]=i+96;var names=exports.names=exports.title={};for(i in codes)names[codes[i]]=i;for(var alias in aliases){codes[alias]=aliases[alias]}},function(module,exports){"use strict";function transformPoints(points,matrix){var result=[],len=points.length,point;for(var i=0;i<len;i++){point=points[i];result.push([matrix[0]*point[0]+matrix[2]*point[1]+matrix[4],matrix[1]*point[0]+matrix[3]*point[1]+matrix[5]])}return result}module.exports=transformPoints},function(module,exports){module.exports=function(point,vs){var x=point[0],y=point[1];var inside=false;for(var i=0,j=vs.length-1;i<vs.length;j=i++){var xi=vs[i][0],yi=vs[i][1];var xj=vs[j][0],yj=vs[j][1];var intersect=yi>y!=yj>y&&x<(xj-xi)*(y-yi)/(yj-yi)+xi;if(intersect)inside=!inside}return inside}},function(module,exports,__webpack_require__){"use strict";var path=__webpack_require__(11),events=__webpack_require__(6);function Img(){events.EventEmitter.call(this);this.imageElement=null;this.imagePattern=null;this.imagePatternRepeat=null;return Object.seal(this)}Img.prototype=Object.create(events.EventEmitter.prototype);Object.defineProperty(Img.prototype,"src",{set:function(val){var element=new Image;this.imageElement=element;element.src=val;if(element.complete){setTimeout(this.imageLoad.bind(this),0)}else{element.onload=this.imageLoad.bind(this)}},get:function(){return this.imageElement.src}});Img.prototype.imageLoad=function imageLoad(){var ctx=window.document.createElement("canvas").getContext("2d");this.imagePattern=ctx.createPattern(this.imageElement,"no-repeat");this.imagePatternRepeat=ctx.createPattern(this.imageElement,"repeat");return this.emit("load",this)};Object.defineProperty(Img.prototype,"width",{enumerable:true,get:function(){return this.imageElement.width},set:function(value){this.imageElement.width=value}});Object.defineProperty(Img.prototype,"height",{enumerable:true,get:function(){return this.imageElement.height},set:function(value){this.imageElement.height=value}});Object.seal(Img);Object.seal(Img.prototype);module.exports=Img},function(module,exports,__webpack_require__){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPath(path)[3]};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(exports,__webpack_require__(12))},function(module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;(function(){try{cachedSetTimeout=setTimeout}catch(e){cachedSetTimeout=function(){throw new Error("setTimeout is not defined")}}try{cachedClearTimeout=clearTimeout}catch(e){cachedClearTimeout=function(){throw new Error("clearTimeout is not defined")}}})();var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=cachedSetTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;cachedClearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){cachedSetTimeout(drainQueue,0)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},function(module,exports){"use strict";function Instruction(type,props){this.type=type;this.props=props;return Object.seal(this)}Object.seal(Instruction);Object.seal(Instruction.prototype);module.exports=Instruction},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function addColorStop(offset,color){return new Instruction("addColorStop",{offset:offset,color:color})}module.exports=addColorStop},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function arc(x,y,r,startAngle,endAngle,anticlockwise){if(arguments.length>5){return new Instruction(anticlockwise?"anticlockwise-arc":"arc",{x:x,y:y,r:r,startAngle:startAngle,endAngle:endAngle})}if(arguments.length===5){return new Instruction("arc",{x:x,y:y,r:r,startAngle:startAngle,endAngle:endAngle})}if(arguments.length>=3){return new Instruction("full-arc",{x:x,y:y,r:r})}if(arguments.length>=1){return new Instruction("quick-arc",{r:x})}return new Instruction("quick-arc",{r:1})}module.exports=arc},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function arcTo(x1,y1,x2,y2,r){return new Instruction("arcTo",{x1:x1,y1:y1,x2:x2,y2:y2,r:r})}module.exports=arcTo},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function beginPath(){return new Instruction("beginPath")}module.exports=beginPath},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y){return new Instruction("bezierCurveTo",{cp1x:cp1x,cp1y:cp1y,cp2x:cp2x,cp2y:cp2y,x:x,y:y})}module.exports=bezierCurveTo},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function clearRect(x,y,width,height){if(arguments.length>2){return new Instruction("clearRect",{x:x,y:y,width:width,height:height})}else{return new Instruction("clearRect",{x:0,y:0,width:x,height:y})}}module.exports=clearRect},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function clip(path,children){var result=[new Instruction("beginClip"),path,new Instruction("clip")];for(var i=1;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("endClip"));return result}module.exports=clip},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function clipPath(){return new Instruction("clipPath")}module.exports=clipPath},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function closePath(){return new Instruction("closePath")}module.exports=closePath},function(module,exports){"use strict";var concat=[].concat;function createClass(){var args=[],i;for(i=0;i<arguments.length;i++){args.push(arguments[i])}for(i=0;i<args.length;i++){while(args[i]&&args[i].constructor===Array){args=concat.apply([],args)}if(args[i]&&args[i].type==="placeholder"){break}}return function(){var start=args,end=start.splice(i+1,args.length);start.pop();return function createdClass(){var children=[],i;for(i=0;i<arguments.length;i++){children.push(arguments[i])}return[start,children,end]}}()}module.exports=createClass},function(module,exports,__webpack_require__){"use strict";if(typeof window!=="undefined"){var ctx=document.createElement("canvas").getContext("2d"),Img=__webpack_require__(10)}function createImagePattern(img,type){if(img){return ctx.createImagePattern(img.constructor===Img?img.imageElement:img,type)}return null}module.exports=createImagePattern},function(module,exports){"use strict";function createRegularPolygon(radius,position,sides){radius=+radius||1;position[0]=+position[0]||0;position[1]=+position[1]||0;sides=+sides||3;var polygon=[];for(var i=0;i<sides;i++){polygon.push([position[0]+radius*Math.cos(Math.PI*2*i/sides),position[1]+radius*Math.sin(Math.PI*2*i/sides)])}return polygon}module.exports=createRegularPolygon},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function drawCanvas(canvas,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight){if(arguments.length===9){return new Instruction("drawCanvasSource",{img:canvas,sx:sx,sy:sy,sWidth:sWidth,sHeight:sHeight,dx:dx,dy:dy,dWidth:dWidth,dHeight:dHeight})}if(arguments.length>=5){return new Instruction("drawCanvasSize",{img:canvas,dx:sx,dy:sy,dWidth:sWidth,dHeight:sHeight})}if(arguments.length>=3){return new Instruction("drawCanvas",{img:canvas,dx:sx,dy:sy})}return new Instruction("drawCanvas",{img:canvas,dx:0,dy:0})}module.exports=drawCanvas},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function drawImage(img,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight){if(arguments.length===9){return new Instruction("drawImageSource",{img:img,sx:sx,sy:sy,sWidth:sWidth,sHeight:sHeight,dx:dx,dy:dy,dWidth:dWidth,dHeight:dHeight})}if(arguments.length>=5){return new Instruction("drawImageSize",{img:img,dx:sx,dy:sy,dWidth:sWidth,dHeight:sHeight})}if(arguments.length>=3){return new Instruction("drawImage",{img:img,dx:sx,dy:sy})}return new Instruction("drawImage",{img:img,dx:0,dy:0})}module.exports=drawImage},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function ellipse(x,y,radiusX,radiusY,rotation,startAngle,endAngle,anticlockwise){if(arguments.length>7){return new Instruction(anticlockwise?"anticlockwise-ellipse":"ellipse",{x:x,y:y,radiusX:radiusX,radiusY:radiusY,startAngle:startAngle,endAngle:endAngle})}if(arguments.length===7){return new Instruction("ellipse",{x:x,y:y,radiusX:radiusX,radiusY:radiusY,rotation:rotation,startAngle:startAngle,endAngle:endAngle})}if(arguments.length>=5){return new Instruction("full-ellipse",{x:x,y:y,radiusX:radiusX,radiusY:radiusY,rotation:rotation})}if(arguments.length===4){return new Instruction("quick-ellipse",{x:x,y:y,radiusX:radiusX,radiusY:radiusY})}return new Instruction("quick-ellipse",{x:0,y:0,radiusX:x,radiusY:y})}module.exports=ellipse},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function fill(){return new Instruction("fill")}module.exports=fill},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13),pi2=Math.PI*2;function fillArc(x,y,r,startAngle,endAngle,counterclockwise){if(arguments.length>=6&&counterclockwise){return new Instruction("fillArc-counterclockwise",{x:x,y:y,r:r,startAngle:startAngle,endAngle:endAngle})}if(arguments.length>3){return new Instruction("fillArc",{x:x,y:y,r:r,startAngle:startAngle,endAngle:endAngle})}if(arguments.length>1){return new Instruction("fillArc",{x:x,y:y,r:r,startAngle:0,endAngle:pi2})}return new Instruction("fillArc",{x:0,y:0,r:x,startAngle:0,endAngle:pi2})}module.exports=fillArc},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function fillImage(img,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight){if(arguments.length===9){return new Instruction("fillCanvasSource",{img:img,sx:sx,sy:sy,sWidth:sWidth,sHeight:sHeight,dx:dx,dy:dy,dWidth:dWidth,dHeight:dHeight})}if(arguments.length>=5){return new Instruction("fillCanvasSize",{img:img,dx:sx,dy:sy,dWidth:sWidth,dHeight:sHeight})}if(arguments.length>=3){return new Instruction("fillCanvas",{img:img,dx:sx,dy:sy})}return new Instruction("fillCanvas",{img:img,dx:0,dy:0})}module.exports=fillImage},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function fillImage(img,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight){if(arguments.length===9){return new Instruction("fillImageSource",{img:img,sx:sx,sy:sy,sWidth:sWidth,sHeight:sHeight,dx:dx,dy:dy,dWidth:dWidth,dHeight:dHeight})}if(arguments.length>=5){return new Instruction("fillImageSize",{img:img,dx:sx,dy:sy,dWidth:sWidth,dHeight:sHeight})}if(arguments.length>=3){return new Instruction("fillImage",{img:img,dx:sx,dy:sy})}return new Instruction("fillImage",{img:img,dx:0,dy:0})}module.exports=fillImage},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function fillImagePattern(img,dx,dy,dWidth,dHeight){if(arguments.length>=5){return new Instruction("fillImagePattern",{img:img,dx:dx,dy:dy,dWidth:dWidth,dHeight:dHeight})}if(arguments.length>=3){return new Instruction("fillImagePattern",{img:img,dx:0,dy:0,dWidth:dx,dHeight:dy})}return new Instruction("fillImagePattern",{img:img,dx:0,dy:0,dWidth:0,dHeight:0})}module.exports=fillImagePattern},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function fillRect(x,y,width,height){if(arguments.length>=4){return new Instruction("fillRect",{x:x,y:y,width:width,height:height})}else{return new Instruction("fillRect",{x:0,y:0,width:x,height:y})}}module.exports=fillRect},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function fillStyle(value,children){var result=[new Instruction("fillStyle",{value:value})];for(var i=1;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("endFillStyle"));return result}module.exports=fillStyle},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);module.exports=function fillText(text,x,y,maxWidth){if(arguments.length<4){maxWidth=null}if(arguments.length<3){x=0;y=0}return new Instruction("fillText",{text:text,x:x,y:y,maxWidth:maxWidth})}},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function globalAlpha(alpha,children){var result=[new Instruction("globalAlpha",{value:alpha})];for(var i=1;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("endGlobalAlpha"));return result}module.exports=globalAlpha},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function globalCompositeOperation(operationType,children){var result=[new Instruction("globalCompositeOperation",{value:operationType})];if(arguments.length===0){return[]}for(var i=1;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("endGlobalCompositeOperation"));return result}module.exports=globalCompositeOperation},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13),hitRegion=__webpack_require__(40);function hitRect(id,x,y,width,height){if(arguments.length<=3){width=x;height=y;x=0;y=0}var points=[[x,y],[x,y+height],[x+width,y+height],[x+width,y]];return hitRegion(id,points)}module.exports=hitRect},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function hitRegion(id,points){return new Instruction("hitRegion",{id:id,points:points})}module.exports=hitRegion},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);module.exports=function imageSmoothingEnabled(val,children){children=[];for(var i=1;i<arguments.length;i++){children.push(arguments[i])}return[new Instruction("imageSmoothingEnabled",{value:Boolean(val)})].concat(children).concat(new Instruction("endImageSmoothingEnabled"))}},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function lineStyle(value,children){value=value||{};var result={lineWidth:null,lineCap:null,lineJoin:null,miterLimit:null,lineDash:[],lineDashOffset:null};if(typeof value.lineWidth!=="undefined"){result.lineWidth=value.lineWidth}if(typeof value.lineCap!=="undefined"){result.lineCap=value.lineCap}if(typeof value.lineJoin!=="undefined"){result.lineJoin=value.lineJoin}if(typeof value.miterLimit!=="undefined"){result.miterLimit=value.miterLimit}if(typeof value.lineDash!=="undefined"){result.lineDash=value.lineDash}if(typeof value.lineDashOffset!=="undefined"){result.lineDashOffset=value.lineDashOffset}var tree=[new Instruction("lineStyle",result)];for(var i=1;i<arguments.length;i++){tree.push(arguments[i])}tree.push(new Instruction("endLineStyle"));return tree}module.exports=lineStyle},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function lineTo(x,y){if(arguments.length===0){return new Instruction("lineTo",{x:0,y:0})}return new Instruction("lineTo",{x:x,y:y})}module.exports=lineTo},function(module,exports){"use strict";if(typeof window!=="undefined"){var ctx=document.createElement("canvas").getContext("2d")}function measureText(text,font){ctx.font=font;return ctx.measureText(text)}module.exports=measureText},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function moveTo(x,y){if(arguments.length===0){return new Instruction("moveTo",{x:0,y:0})}return new Instruction("moveTo",{x:x,y:y})}module.exports=moveTo},function(module,exports,__webpack_require__){"use strict";var moveTo=__webpack_require__(45),lineTo=__webpack_require__(43);function moveToLineTo(point,index){return index===0?moveTo(point[0],point[1]):lineTo(point[0],point[1])}module.exports=moveToLineTo},function(module,exports,__webpack_require__){"use strict";var beginPath=__webpack_require__(17),closePath=__webpack_require__(22);function path(children){var result=[beginPath()];for(var i=0;i<arguments.length;i++){result.push(arguments[i])}result.push(closePath());return result}module.exports=path},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);module.exports=function placeHolder(){return new Instruction("placeholder")}},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function quadraticCurveTo(cpx,cpy,x,y){return new Instruction("quadraticCurveTo",{cpx:cpx,cpy:cpy,x:x,y:y})}module.exports=quadraticCurveTo},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function rect(x,y,width,height){if(arguments.length>2){return new Instruction("rect",{x:x,y:y,width:width,height:height})}else{return new Instruction("rect",{x:0,y:0,width:x,height:y})}}module.exports=rect},function(module,exports,__webpack_require__){"use strict";var setTransform=__webpack_require__(52);module.exports=function resetTransform(){var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i])}return setTransform([1,0,0,1,0,0],args)}},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);module.exports=function(matrix,children){var result=[new Instruction("setTransform",[matrix[0],matrix[1],matrix[2],matrix[3],matrix[4],matrix[5]])];for(var i=1;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("restore"));return result}},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function rotate(r,children){r=+r;var result=[new Instruction("rotate",{cos:Math.cos(r),sin:Math.sin(r)})];for(var i=1;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("restore"));return result}module.exports=rotate},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function scale(x,y,children){var i=2;if(typeof y!=="number"){y=x;i=1}children=children||[];var result=[new Instruction("scale",{x:x,y:y})],child;for(;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("restore"));return result}module.exports=scale},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function shadowStyle(value,children){value=value||{};var result={shadowBlur:null,shadowColor:null,shadowOffsetX:null,shadowOffsetY:null};if(typeof value.shadowBlur!=="undefined"){result.shadowBlur=value.shadowBlur}if(typeof value.shadowColor!=="undefined"){result.shadowColor=value.shadowColor}if(typeof value.shadowOffsetX!=="undefined"){result.shadowOffsetX=value.shadowOffsetX}if(typeof value.direction!=="undefined"){result.shadowOffsetY=value.shadowOffsetY}var tree=[new Instruction("shadowStyle",value)];for(var i=1;i<arguments.length;i++){tree.push(arguments[i])}tree.push(new Instruction("endShadowStyle"));return tree}module.exports=shadowStyle},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function skewX(x,children){var result=[new Instruction("skewX",{x:Math.tan(x)})];for(var i=1;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("restore"));return result}module.exports=skewX},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13); | |
function skewY(y,children){var result=[new Instruction("skewY",{y:Math.tan(y)})];for(var i=1;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("restore"));return result}module.exports=skewY},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function stroke(){return new Instruction("stroke")}module.exports=stroke},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13),pi2=Math.PI*2;function strokeArc(x,y,r,startAngle,endAngle,counterclockwise){if(arguments.length>=6&&counterclockwise){return new Instruction("strokeArc-counterclockwise",{x:x,y:y,r:r,startAngle:startAngle,endAngle:endAngle})}if(arguments.length>3){return new Instruction("strokeArc",{x:x,y:y,r:r,startAngle:startAngle,endAngle:endAngle})}if(arguments.length>1){return new Instruction("strokeArc",{x:x,y:y,r:r,startAngle:0,endAngle:pi2})}return new Instruction("strokeArc",{x:0,y:0,r:x,startAngle:0,endAngle:pi2})}module.exports=strokeArc},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function strokeRect(x,y,width,height){if(arguments.length>2){return new Instruction("strokeRect",{x:x,y:y,width:width,height:height})}else{return new Instruction("strokeRect",{x:0,y:0,width:x,height:y})}}module.exports=strokeRect},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function fillStyle(value,children){var result=[new Instruction("strokeStyle",{value:value})];for(var i=1;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("endStrokeStyle"));return result}module.exports=fillStyle},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function strokeText(text,x,y,maxWidth){if(arguments.length<4){maxWidth=null}if(arguments.length<3){x=0;y=0}return new Instruction("strokeText",{text:text,x:x,y:y,maxWidth:maxWidth})}module.exports=strokeText},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function text(str,x,y,fill,stroke,maxWidth){if(arguments.length===6){return new Instruction("text",{x:x,y:y,fill:fill,stroke:stroke,text:str,maxWidth:maxWidth})}if(arguments.length===5){return new Instruction("text",{x:x,y:y,fill:fill,stroke:stroke,text:str,maxWidth:0})}if(arguments.length===4){return new Instruction("text",{x:x,y:y,fill:fill,stroke:false,text:str,maxWidth:0})}if(arguments.length===3){return new Instruction("text",{x:x,y:y,fill:true,stroke:false,text:str,maxWidth:0})}return new Instruction("text",{x:0,y:0,fill:true,stroke:false,text:str,maxWidth:0})}module.exports=text},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function textStyle(value,children){value=value||{};var result={font:null,textAlign:null,textBaseline:null,direction:null};if(typeof value.font!=="undefined"){result.font=value.font}if(typeof value.textAlign!=="undefined"){result.textAlign=value.textAlign}if(typeof value.textBaseline!=="undefined"){result.textBaseline=value.textBaseline}if(typeof value.direction!=="undefined"){result.direction=value.direction}var tree=[new Instruction("textStyle",value)];for(var i=1;i<arguments.length;i++){tree.push(arguments[i])}tree.push(new Instruction("endTextStyle"));return tree}module.exports=textStyle},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function transform(values,children){var transformResult=[new Instruction("transform",[values[0],values[1],values[2],values[3],values[4],values[5]])];for(var i=1;i<arguments.length;i++){transformResult.push(arguments[i])}transformResult.push(new Instruction("restore"));return transformResult}module.exports=transform},function(module,exports,__webpack_require__){"use strict";var Instruction=__webpack_require__(13);function translate(x,y,children){var result=[new Instruction("translate",{x:x,y:y})];for(var i=2;i<arguments.length;i++){result.push(arguments[i])}result.push(new Instruction("restore"));return result}module.exports=translate}])})},{}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var Scalar=require("./Scalar");module.exports=Line;function Line(){}Line.lineInt=function(l1,l2,precision){precision=precision||0;var i=[0,0];var a1,b1,c1,a2,b2,c2,det;a1=l1[1][1]-l1[0][1];b1=l1[0][0]-l1[1][0];c1=a1*l1[0][0]+b1*l1[0][1];a2=l2[1][1]-l2[0][1];b2=l2[0][0]-l2[1][0];c2=a2*l2[0][0]+b2*l2[0][1];det=a1*b2-a2*b1;if(!Scalar.eq(det,0,precision)){i[0]=(b2*c1-b1*c2)/det;i[1]=(a1*c2-a2*c1)/det}return i};Line.segmentsIntersect=function(p1,p2,q1,q2){var dx=p2[0]-p1[0];var dy=p2[1]-p1[1];var da=q2[0]-q1[0];var db=q2[1]-q1[1];if(da*dy-db*dx==0)return false;var s=(dx*(q1[1]-p1[1])+dy*(p1[0]-q1[0]))/(da*dy-db*dx);var t=(da*(p1[1]-q1[1])+db*(q1[0]-p1[0]))/(db*dx-da*dy);return s>=0&&s<=1&&t>=0&&t<=1}},{"./Scalar":4}],2:[function(require,module,exports){module.exports=Point;function Point(){}Point.area=function(a,b,c){return(b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1])};Point.left=function(a,b,c){return Point.area(a,b,c)>0};Point.leftOn=function(a,b,c){return Point.area(a,b,c)>=0};Point.right=function(a,b,c){return Point.area(a,b,c)<0};Point.rightOn=function(a,b,c){return Point.area(a,b,c)<=0};var tmpPoint1=[],tmpPoint2=[];Point.collinear=function(a,b,c,thresholdAngle){if(!thresholdAngle)return Point.area(a,b,c)==0;else{var ab=tmpPoint1,bc=tmpPoint2;ab[0]=b[0]-a[0];ab[1]=b[1]-a[1];bc[0]=c[0]-b[0];bc[1]=c[1]-b[1];var dot=ab[0]*bc[0]+ab[1]*bc[1],magA=Math.sqrt(ab[0]*ab[0]+ab[1]*ab[1]),magB=Math.sqrt(bc[0]*bc[0]+bc[1]*bc[1]),angle=Math.acos(dot/(magA*magB));return angle<thresholdAngle}};Point.sqdist=function(a,b){var dx=b[0]-a[0];var dy=b[1]-a[1];return dx*dx+dy*dy}},{}],3:[function(require,module,exports){var Line=require("./Line"),Point=require("./Point"),Scalar=require("./Scalar");module.exports=Polygon;function Polygon(){this.vertices=[]}Polygon.prototype.at=function(i){var v=this.vertices,s=v.length;return v[i<0?i%s+s:i%s]};Polygon.prototype.first=function(){return this.vertices[0]};Polygon.prototype.last=function(){return this.vertices[this.vertices.length-1]};Polygon.prototype.clear=function(){this.vertices.length=0};Polygon.prototype.append=function(poly,from,to){if(typeof from=="undefined")throw new Error("From is not given!");if(typeof to=="undefined")throw new Error("To is not given!");if(to-1<from)throw new Error("lol1");if(to>poly.vertices.length)throw new Error("lol2");if(from<0)throw new Error("lol3");for(var i=from;i<to;i++){this.vertices.push(poly.vertices[i])}};Polygon.prototype.makeCCW=function(){var br=0,v=this.vertices;for(var i=1;i<this.vertices.length;++i){if(v[i][1]<v[br][1]||v[i][1]==v[br][1]&&v[i][0]>v[br][0]){br=i}}if(!Point.left(this.at(br-1),this.at(br),this.at(br+1))){this.reverse()}};Polygon.prototype.reverse=function(){var tmp=[];for(var i=0,N=this.vertices.length;i!==N;i++){tmp.push(this.vertices.pop())}this.vertices=tmp};Polygon.prototype.isReflex=function(i){return Point.right(this.at(i-1),this.at(i),this.at(i+1))};var tmpLine1=[],tmpLine2=[];Polygon.prototype.canSee=function(a,b){var p,dist,l1=tmpLine1,l2=tmpLine2;if(Point.leftOn(this.at(a+1),this.at(a),this.at(b))&&Point.rightOn(this.at(a-1),this.at(a),this.at(b))){return false}dist=Point.sqdist(this.at(a),this.at(b));for(var i=0;i!==this.vertices.length;++i){if((i+1)%this.vertices.length===a||i===a)continue;if(Point.leftOn(this.at(a),this.at(b),this.at(i+1))&&Point.rightOn(this.at(a),this.at(b),this.at(i))){l1[0]=this.at(a);l1[1]=this.at(b);l2[0]=this.at(i);l2[1]=this.at(i+1);p=Line.lineInt(l1,l2);if(Point.sqdist(this.at(a),p)<dist){return false}}}return true};Polygon.prototype.copy=function(i,j,targetPoly){var p=targetPoly||new Polygon;p.clear();if(i<j){for(var k=i;k<=j;k++)p.vertices.push(this.vertices[k])}else{for(var k=0;k<=j;k++)p.vertices.push(this.vertices[k]);for(var k=i;k<this.vertices.length;k++)p.vertices.push(this.vertices[k])}return p};Polygon.prototype.getCutEdges=function(){var min=[],tmp1=[],tmp2=[],tmpPoly=new Polygon;var nDiags=Number.MAX_VALUE;for(var i=0;i<this.vertices.length;++i){if(this.isReflex(i)){for(var j=0;j<this.vertices.length;++j){if(this.canSee(i,j)){tmp1=this.copy(i,j,tmpPoly).getCutEdges();tmp2=this.copy(j,i,tmpPoly).getCutEdges();for(var k=0;k<tmp2.length;k++)tmp1.push(tmp2[k]);if(tmp1.length<nDiags){min=tmp1;nDiags=tmp1.length;min.push([this.at(i),this.at(j)])}}}}}return min};Polygon.prototype.decomp=function(){var edges=this.getCutEdges();if(edges.length>0)return this.slice(edges);else return[this]};Polygon.prototype.slice=function(cutEdges){if(cutEdges.length==0)return[this];if(cutEdges instanceof Array&&cutEdges.length&&cutEdges[0]instanceof Array&&cutEdges[0].length==2&&cutEdges[0][0]instanceof Array){var polys=[this];for(var i=0;i<cutEdges.length;i++){var cutEdge=cutEdges[i];for(var j=0;j<polys.length;j++){var poly=polys[j];var result=poly.slice(cutEdge);if(result){polys.splice(j,1);polys.push(result[0],result[1]);break}}}return polys}else{var cutEdge=cutEdges;var i=this.vertices.indexOf(cutEdge[0]);var j=this.vertices.indexOf(cutEdge[1]);if(i!=-1&&j!=-1){return[this.copy(i,j),this.copy(j,i)]}else{return false}}};Polygon.prototype.isSimple=function(){var path=this.vertices;for(var i=0;i<path.length-1;i++){for(var j=0;j<i-1;j++){if(Line.segmentsIntersect(path[i],path[i+1],path[j],path[j+1])){return false}}}for(var i=1;i<path.length-2;i++){if(Line.segmentsIntersect(path[0],path[path.length-1],path[i],path[i+1])){return false}}return true};function getIntersectionPoint(p1,p2,q1,q2,delta){delta=delta||0;var a1=p2[1]-p1[1];var b1=p1[0]-p2[0];var c1=a1*p1[0]+b1*p1[1];var a2=q2[1]-q1[1];var b2=q1[0]-q2[0];var c2=a2*q1[0]+b2*q1[1];var det=a1*b2-a2*b1;if(!Scalar.eq(det,0,delta))return[(b2*c1-b1*c2)/det,(a1*c2-a2*c1)/det];else return[0,0]}Polygon.prototype.quickDecomp=function(result,reflexVertices,steinerPoints,delta,maxlevel,level){maxlevel=maxlevel||100;level=level||0;delta=delta||25;result=typeof result!="undefined"?result:[];reflexVertices=reflexVertices||[];steinerPoints=steinerPoints||[];var upperInt=[0,0],lowerInt=[0,0],p=[0,0];var upperDist=0,lowerDist=0,d=0,closestDist=0;var upperIndex=0,lowerIndex=0,closestIndex=0;var lowerPoly=new Polygon,upperPoly=new Polygon;var poly=this,v=this.vertices;if(v.length<3)return result;level++;if(level>maxlevel){console.warn("quickDecomp: max level ("+maxlevel+") reached.");return result}for(var i=0;i<this.vertices.length;++i){if(poly.isReflex(i)){reflexVertices.push(poly.vertices[i]);upperDist=lowerDist=Number.MAX_VALUE;for(var j=0;j<this.vertices.length;++j){if(Point.left(poly.at(i-1),poly.at(i),poly.at(j))&&Point.rightOn(poly.at(i-1),poly.at(i),poly.at(j-1))){p=getIntersectionPoint(poly.at(i-1),poly.at(i),poly.at(j),poly.at(j-1));if(Point.right(poly.at(i+1),poly.at(i),p)){d=Point.sqdist(poly.vertices[i],p);if(d<lowerDist){lowerDist=d;lowerInt=p;lowerIndex=j}}}if(Point.left(poly.at(i+1),poly.at(i),poly.at(j+1))&&Point.rightOn(poly.at(i+1),poly.at(i),poly.at(j))){p=getIntersectionPoint(poly.at(i+1),poly.at(i),poly.at(j),poly.at(j+1));if(Point.left(poly.at(i-1),poly.at(i),p)){d=Point.sqdist(poly.vertices[i],p);if(d<upperDist){upperDist=d;upperInt=p;upperIndex=j}}}}if(lowerIndex==(upperIndex+1)%this.vertices.length){p[0]=(lowerInt[0]+upperInt[0])/2;p[1]=(lowerInt[1]+upperInt[1])/2;steinerPoints.push(p);if(i<upperIndex){lowerPoly.append(poly,i,upperIndex+1);lowerPoly.vertices.push(p);upperPoly.vertices.push(p);if(lowerIndex!=0){upperPoly.append(poly,lowerIndex,poly.vertices.length)}upperPoly.append(poly,0,i+1)}else{if(i!=0){lowerPoly.append(poly,i,poly.vertices.length)}lowerPoly.append(poly,0,upperIndex+1);lowerPoly.vertices.push(p);upperPoly.vertices.push(p);upperPoly.append(poly,lowerIndex,i+1)}}else{if(lowerIndex>upperIndex){upperIndex+=this.vertices.length}closestDist=Number.MAX_VALUE;if(upperIndex<lowerIndex){return result}for(var j=lowerIndex;j<=upperIndex;++j){if(Point.leftOn(poly.at(i-1),poly.at(i),poly.at(j))&&Point.rightOn(poly.at(i+1),poly.at(i),poly.at(j))){d=Point.sqdist(poly.at(i),poly.at(j));if(d<closestDist){closestDist=d;closestIndex=j%this.vertices.length}}}if(i<closestIndex){lowerPoly.append(poly,i,closestIndex+1);if(closestIndex!=0){upperPoly.append(poly,closestIndex,v.length)}upperPoly.append(poly,0,i+1)}else{if(i!=0){lowerPoly.append(poly,i,v.length)}lowerPoly.append(poly,0,closestIndex+1);upperPoly.append(poly,closestIndex,i+1)}}if(lowerPoly.vertices.length<upperPoly.vertices.length){lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level)}else{upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level)}return result}}result.push(this);return result};Polygon.prototype.removeCollinearPoints=function(precision){var num=0;for(var i=this.vertices.length-1;this.vertices.length>3&&i>=0;--i){if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){this.vertices.splice(i%this.vertices.length,1);i--;num++}}return num}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(require,module,exports){module.exports=Scalar;function Scalar(){}Scalar.eq=function(a,b,precision){precision=precision||0;return Math.abs(a-b)<precision}},{}],5:[function(require,module,exports){module.exports={Polygon:require("./Polygon"),Point:require("./Point")}},{"./Point":2,"./Polygon":3}],6:[function(require,module,exports){module.exports={name:"p2",version:"0.7.1",description:"A JavaScript 2D physics engine.",author:"Stefan Hedman <[email protected]> (http://steffe.se)",keywords:["p2.js","p2","physics","engine","2d"],main:"./src/p2.js",engines:{node:"*"},repository:{type:"git",url:"https://github.com/schteppe/p2.js.git"},bugs:{url:"https://github.com/schteppe/p2.js/issues"},licenses:[{type:"MIT"}],devDependencies:{grunt:"^0.4.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.1"},readme:'p2.js\n=====\n\n2D rigid body physics engine written in JavaScript. Includes collision detection, contacts, friction, restitution, motors, springs, advanced constraints and various shape types.\n\n[Demos](#demos) | [Examples](#examples) | [Documentation](http://schteppe.github.io/p2.js/docs/) | [Download](https://raw.github.com/schteppe/p2.js/master/build/p2.js) | [CDN](http://cdnjs.com/libraries/p2.js) | [Wiki](https://github.com/schteppe/p2.js/wiki)\n\n### Featured projects using p2.js\n* [Google I/O 2015 Experiment](http://www.chromeexperiments.com/detail/io-2015-experiment) by Instrument\n* [PixiLights, a Christmas Experiment](http://christmasexperiments.com/experiments/11) by Mat Groves\n* [More...](https://github.com/schteppe/p2.js/wiki/Projects-using-p2.js)\n\n### Demos\nThese demos use the p2 Demo framework, which provides rendering and interactivity. Use mouse/touch to throw or create objects. Use the right menu (or console!) to tweak parameters. Or just check the source to see how to programmatically build the current scene using p2.\n\n* [Buoyancy](http://schteppe.github.io/p2.js/demos/buoyancy.html)\n* [Car](http://schteppe.github.io/p2.js/demos/car.html)\n* [CCD](http://schteppe.github.io/p2.js/demos/ccd.html)\n* [Circle container](http://schteppe.github.io/p2.js/demos/circles.html)\n* [Collision tests](http://schteppe.github.io/p2.js/demos/collisions.html)\n* [Compound objects](http://schteppe.github.io/p2.js/demos/compound.html)\n* [Concave objects](http://schteppe.github.io/p2.js/demos/concave.html)\n* [Constraints](http://schteppe.github.io/p2.js/demos/constraints.html)\n* [DistanceConstraint](http://schteppe.github.io/p2.js/demos/distanceConstraint.html)\n* [Fixed rotation](http://schteppe.github.io/p2.js/demos/fixedRotation.html)\n* [Fixed XY](http://schteppe.github.io/p2.js/demos/fixedXY.html)\n* [Friction](http://schteppe.github.io/p2.js/demos/friction.html)\n* [Gear constraint](http://schteppe.github.io/p2.js/demos/gearConstraint.html)\n* [Heightfield](http://schteppe.github.io/p2.js/demos/heightfield.html)\n* [Island solver](http://schteppe.github.io/p2.js/demos/islandSolver.html)\n* [Kinematic body](http://schteppe.github.io/p2.js/demos/kinematic.html)\n* [Lock constraint](http://schteppe.github.io/p2.js/demos/lock.html)\n* [Piston](http://schteppe.github.io/p2.js/demos/piston.html)\n* [Prismatic constraint](http://schteppe.github.io/p2.js/demos/prismatic.html)\n* [Ragdoll](http://schteppe.github.io/p2.js/demos/ragdoll.html)\n* [Sensor](http://schteppe.github.io/p2.js/demos/removeSensor.html)\n* [Restitution](http://schteppe.github.io/p2.js/demos/restitution.html)\n* [Sleep](http://schteppe.github.io/p2.js/demos/sleep.html)\n* [Segway](http://schteppe.github.io/p2.js/demos/segway.html)\n* [Sleep](http://schteppe.github.io/p2.js/demos/sleep.html)\n* [Springs](http://schteppe.github.io/p2.js/demos/springs.html)\n* [Surface velocity](http://schteppe.github.io/p2.js/demos/surfaceVelocity.html)\n* [Suspension](http://schteppe.github.io/p2.js/demos/suspension.html)\n* [Tearable constraints](http://schteppe.github.io/p2.js/demos/tearable.html)\n* [TopDownVehicle](http://schteppe.github.io/p2.js/demos/topDownVehicle.html)\n\n### Examples\nExamples showing how to use p2.js with your favorite renderer.\n\n* [Canvas: Asteroids game](http://schteppe.github.io/p2.js/examples/canvas/asteroids.html)\n* [Canvas: Box on plane](http://schteppe.github.io/p2.js/examples/canvas/box.html)\n* [Canvas: Character demo](http://schteppe.github.io/p2.js/examples/canvas/character.html)\n* [Canvas: Circle on plane](http://schteppe.github.io/p2.js/examples/canvas/circle.html)\n* [Canvas: Interpolation](http://schteppe.github.io/p2.js/examples/canvas/interpolation.html)\n* [Canvas: Mousejoint](http://schteppe.github.io/p2.js/examples/canvas/mouseJoint.html)\n* [Canvas: Raycasting](http://schteppe.github.io/p2.js/examples/canvas/raycasting.html)\n* [Canvas: Rayreflect](http://schteppe.github.io/p2.js/examples/canvas/rayreflect.html)\n* [Canvas: Sensors](http://schteppe.github.io/p2.js/examples/canvas/sensors.html)\n* [Canvas: Sensors 2](http://schteppe.github.io/p2.js/examples/canvas/sensors2.html)\n* [Pixi.js: Box on plane](http://schteppe.github.io/p2.js/examples/pixijs/box.html)\n\n### Sample code\nThe following example uses the [World](http://schteppe.github.io/p2.js/docs/classes/World.html), [Circle](http://schteppe.github.io/p2.js/docs/classes/Circle.html), [Body](http://schteppe.github.io/p2.js/docs/classes/Body.html) and [Plane](http://schteppe.github.io/p2.js/docs/classes/Plane.html) classes to set up a simple physics scene with a ball on a plane.\n\n```js\n// Create a physics world, where bodies and constraints live\nvar world = new p2.World({\n gravity:[0, -9.82]\n});\n\n// Create an empty dynamic body\nvar circleBody = new p2.Body({\n mass: 5,\n position: [0, 10]\n});\n\n// Add a circle shape to the body.\nvar circleShape = new p2.Circle({ radius: 1 });\ncircleBody.addShape(circleShape);\n\n// ...and add the body to the world.\n// If we don\'t add it to the world, it won\'t be simulated.\nworld.addBody(circleBody);\n\n// Create an infinite ground plane.\nvar groundBody = new p2.Body({\n mass: 0 // Setting mass to 0 makes the body static\n});\nvar groundShape = new p2.Plane();\ngroundBody.addShape(groundShape);\nworld.addBody(groundBody);\n\n// To get the trajectories of the bodies,\n// we must step the world forward in time.\n// This is done using a fixed time step size.\nvar timeStep = 1 / 60; // seconds\n\n// The "Game loop". Could be replaced by, for example, requestAnimationFrame.\nsetInterval(function(){\n\n // The step method moves the bodies forward in time.\n world.step(timeStep);\n\n // Print the circle position to console.\n // Could be replaced by a render call.\n console.log("Circle y position: " + circleBody.position[1]);\n\n}, 1000 * timeStep);\n```\n\n### Install\n##### Browser\nDownload either [p2.js](build/p2.js) or the minified [p2.min.js](build/p2.min.js) and include the script in your HTML:\n```html\n<script src="p2.js" type="text/javascript"></script>\n```\n\nIf you would like to use ordinary ```Array``` instead of ```Float32Array```, define ```P2_ARRAY_TYPE``` globally before loading the library.\n\n```html\n<script type="text/javascript">P2_ARRAY_TYPE = Array;</script>\n<script src="p2.js" type="text/javascript"></script>\n```\n\n##### Node.js\n```\nnpm install p2\n```\nThen require it like so:\n```js\nvar p2 = require(\'p2\');\n```\n\n### Supported collision pairs\n| | Circle | Plane | Box | Convex | Particle | Line | Capsule | Heightfield | Ray |\n| :--------------------------------------------------------------------------: |:------:|:-----:|:---------:|:------:|:--------:|:------:|:-------:|:-----------:|:------:|\n| [Circle](http://schteppe.github.io/p2.js/docs/classes/Circle.html) | Yes | - | - | - | - | - | - | - | - |\n| [Plane](http://schteppe.github.io/p2.js/docs/classes/Plane.html) | Yes | - | - | - | - | - | - | - | - |\n| [Box](http://schteppe.github.io/p2.js/docs/classes/Box.html) | Yes | Yes | Yes | - | - | - | - | - | - |\n| [Convex](http://schteppe.github.io/p2.js/docs/classes/Convex.html) | Yes | Yes | Yes | Yes | - | - | - | - | - |\n| [Particle](http://schteppe.github.io/p2.js/docs/classes/Particle.html) | Yes | Yes | Yes | Yes | - | - | - | - | - |\n| [Line](http://schteppe.github.io/p2.js/docs/classes/Line.html) | Yes | Yes | (todo) | (todo) | - | - | - | - | - |\n| [Capsule](http://schteppe.github.io/p2.js/docs/classes/Capsule.html) | Yes | Yes | Yes | Yes | Yes | (todo) | Yes | - | - |\n| [Heightfield](http://schteppe.github.io/p2.js/docs/classes/Heightfield.html) | Yes | - | Yes | Yes | (todo) | (todo) | (todo) | - | - |\n| [Ray](http://schteppe.github.io/p2.js/docs/classes/Ray.html) | Yes | Yes | Yes | Yes | - | Yes | Yes | Yes | - |\n\nNote that concave polygon shapes can be created using [Body.fromPolygon](http://schteppe.github.io/p2.js/docs/classes/Body.html#method_fromPolygon).\n\n### Unit testing\nTests are written for [Nodeunit](https://github.com/caolan/nodeunit). Run the tests with the command ```grunt test```.\n\n### Contribute\nMake sure you have git, [Node.js](http://nodejs.org), NPM and [grunt](http://gruntjs.com/) installed.\n```\ngit clone https://github.com/schteppe/p2.js.git; # Clone the repo\ncd p2.js;\nnpm install; # Install dependencies\n # (make changes to source)\ngrunt; # Builds build/p2.js and build/p2.min.js\n```\nThe most recent commits are currently pushed to the ```master``` branch. Thanks for contributing!\n',readmeFilename:"package/README.md",scripts:{}}},{}],7:[function(require,module,exports){var vec2=require("../math/vec2"),Utils=require("../utils/Utils");module.exports=AABB;function AABB(options){this.lowerBound=vec2.create();if(options&&options.lowerBound){vec2.copy(this.lowerBound,options.lowerBound)}this.upperBound=vec2.create();if(options&&options.upperBound){vec2.copy(this.upperBound,options.upperBound)}}var tmp=vec2.create();AABB.prototype.setFromPoints=function(points,position,angle,skinSize){var l=this.lowerBound,u=this.upperBound;if(typeof angle!=="number"){angle=0}if(angle!==0){vec2.rotate(l,points[0],angle)}else{vec2.copy(l,points[0])}vec2.copy(u,l);var cosAngle=Math.cos(angle),sinAngle=Math.sin(angle);for(var i=1;i<points.length;i++){var p=points[i];if(angle!==0){var x=p[0],y=p[1];tmp[0]=cosAngle*x-sinAngle*y;tmp[1]=sinAngle*x+cosAngle*y;p=tmp}for(var j=0;j<2;j++){if(p[j]>u[j]){u[j]=p[j]}if(p[j]<l[j]){l[j]=p[j]}}}if(position){vec2.add(this.lowerBound,this.lowerBound,position);vec2.add(this.upperBound,this.upperBound,position)}if(skinSize){this.lowerBound[0]-=skinSize;this.lowerBound[1]-=skinSize;this.upperBound[0]+=skinSize;this.upperBound[1]+=skinSize}};AABB.prototype.copy=function(aabb){vec2.copy(this.lowerBound,aabb.lowerBound);vec2.copy(this.upperBound,aabb.upperBound)};AABB.prototype.extend=function(aabb){var i=2;while(i--){var l=aabb.lowerBound[i];if(this.lowerBound[i]>l){this.lowerBound[i]=l}var u=aabb.upperBound[i];if(this.upperBound[i]<u){this.upperBound[i]=u}}};AABB.prototype.overlaps=function(aabb){var l1=this.lowerBound,u1=this.upperBound,l2=aabb.lowerBound,u2=aabb.upperBound;return(l2[0]<=u1[0]&&u1[0]<=u2[0]||l1[0]<=u2[0]&&u2[0]<=u1[0])&&(l2[1]<=u1[1]&&u1[1]<=u2[1]||l1[1]<=u2[1]&&u2[1]<=u1[1])};AABB.prototype.containsPoint=function(point){var l=this.lowerBound,u=this.upperBound;return l[0]<=point[0]&&point[0]<=u[0]&&l[1]<=point[1]&&point[1]<=u[1]};AABB.prototype.overlapsRay=function(ray){var t=0;var dirFracX=1/ray.direction[0];var dirFracY=1/ray.direction[1];var t1=(this.lowerBound[0]-ray.from[0])*dirFracX;var t2=(this.upperBound[0]-ray.from[0])*dirFracX;var t3=(this.lowerBound[1]-ray.from[1])*dirFracY;var t4=(this.upperBound[1]-ray.from[1])*dirFracY;var tmin=Math.max(Math.max(Math.min(t1,t2),Math.min(t3,t4)));var tmax=Math.min(Math.min(Math.max(t1,t2),Math.max(t3,t4)));if(tmax<0){return-1}if(tmin>tmax){return-1}return tmin}},{"../math/vec2":30,"../utils/Utils":56}],8:[function(require,module,exports){var vec2=require("../math/vec2");var Body=require("../objects/Body");module.exports=Broadphase;function Broadphase(type){this.type=type;this.result=[];this.world=null;this.boundingVolumeType=Broadphase.AABB}Broadphase.AABB=1;Broadphase.BOUNDING_CIRCLE=2;Broadphase.prototype.setWorld=function(world){this.world=world};Broadphase.prototype.getCollisionPairs=function(world){};var dist=vec2.create();Broadphase.boundingRadiusCheck=function(bodyA,bodyB){vec2.sub(dist,bodyA.position,bodyB.position);var d2=vec2.squaredLength(dist),r=bodyA.boundingRadius+bodyB.boundingRadius;return d2<=r*r};Broadphase.aabbCheck=function(bodyA,bodyB){return bodyA.getAABB().overlaps(bodyB.getAABB())};Broadphase.prototype.boundingVolumeCheck=function(bodyA,bodyB){var result;switch(this.boundingVolumeType){case Broadphase.BOUNDING_CIRCLE:result=Broadphase.boundingRadiusCheck(bodyA,bodyB);break;case Broadphase.AABB:result=Broadphase.aabbCheck(bodyA,bodyB);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return result};Broadphase.canCollide=function(bodyA,bodyB){var KINEMATIC=Body.KINEMATIC;var STATIC=Body.STATIC;if(bodyA.type===STATIC&&bodyB.type===STATIC){return false}if(bodyA.type===KINEMATIC&&bodyB.type===STATIC||bodyA.type===STATIC&&bodyB.type===KINEMATIC){return false}if(bodyA.type===KINEMATIC&&bodyB.type===KINEMATIC){return false}if(bodyA.sleepState===Body.SLEEPING&&bodyB.sleepState===Body.SLEEPING){return false}if(bodyA.sleepState===Body.SLEEPING&&bodyB.type===STATIC||bodyB.sleepState===Body.SLEEPING&&bodyA.type===STATIC){return false}return true};Broadphase.NAIVE=1;Broadphase.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(require,module,exports){var Circle=require("../shapes/Circle"),Plane=require("../shapes/Plane"),Shape=require("../shapes/Shape"),Particle=require("../shapes/Particle"),Broadphase=require("../collision/Broadphase"),vec2=require("../math/vec2");module.exports=NaiveBroadphase;function NaiveBroadphase(){Broadphase.call(this,Broadphase.NAIVE)}NaiveBroadphase.prototype=new Broadphase;NaiveBroadphase.prototype.constructor=NaiveBroadphase;NaiveBroadphase.prototype.getCollisionPairs=function(world){var bodies=world.bodies,result=this.result;result.length=0;for(var i=0,Ncolliding=bodies.length;i!==Ncolliding;i++){var bi=bodies[i];for(var j=0;j<i;j++){var bj=bodies[j];if(Broadphase.canCollide(bi,bj)&&this.boundingVolumeCheck(bi,bj)){result.push(bi,bj)}}}return result};NaiveBroadphase.prototype.aabbQuery=function(world,aabb,result){result=result||[];var bodies=world.bodies;for(var i=0;i<bodies.length;i++){var b=bodies[i];if(b.aabbNeedsUpdate){b.updateAABB()}if(b.aabb.overlaps(aabb)){result.push(b)}}return result}},{"../collision/Broadphase":8,"../math/vec2":30,"../shapes/Circle":38,"../shapes/Particle":42,"../shapes/Plane":43,"../shapes/Shape":44}],10:[function(require,module,exports){var vec2=require("../math/vec2"),sub=vec2.sub,add=vec2.add,dot=vec2.dot,Utils=require("../utils/Utils"),ContactEquationPool=require("../utils/ContactEquationPool"),FrictionEquationPool=require("../utils/FrictionEquationPool"),TupleDictionary=require("../utils/TupleDictionary"),Equation=require("../equations/Equation"),ContactEquation=require("../equations/ContactEquation"),FrictionEquation=require("../equations/FrictionEquation"),Circle=require("../shapes/Circle"),Convex=require("../shapes/Convex"),Shape=require("../shapes/Shape"),Body=require("../objects/Body"),Box=require("../shapes/Box");module.exports=Narrowphase;var yAxis=vec2.fromValues(0,1);var tmp1=vec2.fromValues(0,0),tmp2=vec2.fromValues(0,0),tmp3=vec2.fromValues(0,0),tmp4=vec2.fromValues(0,0),tmp5=vec2.fromValues(0,0),tmp6=vec2.fromValues(0,0),tmp7=vec2.fromValues(0,0),tmp8=vec2.fromValues(0,0),tmp9=vec2.fromValues(0,0),tmp10=vec2.fromValues(0,0),tmp11=vec2.fromValues(0,0),tmp12=vec2.fromValues(0,0),tmp13=vec2.fromValues(0,0),tmp14=vec2.fromValues(0,0),tmp15=vec2.fromValues(0,0),tmp16=vec2.fromValues(0,0),tmp17=vec2.fromValues(0,0),tmp18=vec2.fromValues(0,0),tmpArray=[];function Narrowphase(){this.contactEquations=[];this.frictionEquations=[];this.enableFriction=true;this.enabledEquations=true;this.slipForce=10;this.frictionCoefficient=.3;this.surfaceVelocity=0;this.contactEquationPool=new ContactEquationPool({size:32});this.frictionEquationPool=new FrictionEquationPool({size:64});this.restitution=0;this.stiffness=Equation.DEFAULT_STIFFNESS;this.relaxation=Equation.DEFAULT_RELAXATION;this.frictionStiffness=Equation.DEFAULT_STIFFNESS;this.frictionRelaxation=Equation.DEFAULT_RELAXATION;this.enableFrictionReduction=true;this.collidingBodiesLastStep=new TupleDictionary;this.contactSkinSize=.01}var bodiesOverlap_shapePositionA=vec2.create();var bodiesOverlap_shapePositionB=vec2.create();Narrowphase.prototype.bodiesOverlap=function(bodyA,bodyB){var shapePositionA=bodiesOverlap_shapePositionA;var shapePositionB=bodiesOverlap_shapePositionB;for(var k=0,Nshapesi=bodyA.shapes.length;k!==Nshapesi;k++){var shapeA=bodyA.shapes[k];bodyA.toWorldFrame(shapePositionA,shapeA.position);for(var l=0,Nshapesj=bodyB.shapes.length;l!==Nshapesj;l++){var shapeB=bodyB.shapes[l];bodyB.toWorldFrame(shapePositionB,shapeB.position);if(this[shapeA.type|shapeB.type](bodyA,shapeA,shapePositionA,shapeA.angle+bodyA.angle,bodyB,shapeB,shapePositionB,shapeB.angle+bodyB.angle,true)){return true}}}return false};Narrowphase.prototype.collidedLastStep=function(bodyA,bodyB){var id1=bodyA.id|0,id2=bodyB.id|0;return!!this.collidingBodiesLastStep.get(id1,id2)};Narrowphase.prototype.reset=function(){this.collidingBodiesLastStep.reset();var eqs=this.contactEquations; | |
var l=eqs.length;while(l--){var eq=eqs[l],id1=eq.bodyA.id,id2=eq.bodyB.id;this.collidingBodiesLastStep.set(id1,id2,true)}var ce=this.contactEquations,fe=this.frictionEquations;for(var i=0;i<ce.length;i++){this.contactEquationPool.release(ce[i])}for(var i=0;i<fe.length;i++){this.frictionEquationPool.release(fe[i])}this.contactEquations.length=this.frictionEquations.length=0};Narrowphase.prototype.createContactEquation=function(bodyA,bodyB,shapeA,shapeB){var c=this.contactEquationPool.get();c.bodyA=bodyA;c.bodyB=bodyB;c.shapeA=shapeA;c.shapeB=shapeB;c.restitution=this.restitution;c.firstImpact=!this.collidedLastStep(bodyA,bodyB);c.stiffness=this.stiffness;c.relaxation=this.relaxation;c.needsUpdate=true;c.enabled=this.enabledEquations;c.offset=this.contactSkinSize;return c};Narrowphase.prototype.createFrictionEquation=function(bodyA,bodyB,shapeA,shapeB){var c=this.frictionEquationPool.get();c.bodyA=bodyA;c.bodyB=bodyB;c.shapeA=shapeA;c.shapeB=shapeB;c.setSlipForce(this.slipForce);c.frictionCoefficient=this.frictionCoefficient;c.relativeVelocity=this.surfaceVelocity;c.enabled=this.enabledEquations;c.needsUpdate=true;c.stiffness=this.frictionStiffness;c.relaxation=this.frictionRelaxation;c.contactEquations.length=0;return c};Narrowphase.prototype.createFrictionFromContact=function(c){var eq=this.createFrictionEquation(c.bodyA,c.bodyB,c.shapeA,c.shapeB);vec2.copy(eq.contactPointA,c.contactPointA);vec2.copy(eq.contactPointB,c.contactPointB);vec2.rotate90cw(eq.t,c.normalA);eq.contactEquations.push(c);return eq};Narrowphase.prototype.createFrictionFromAverage=function(numContacts){var c=this.contactEquations[this.contactEquations.length-1];var eq=this.createFrictionEquation(c.bodyA,c.bodyB,c.shapeA,c.shapeB);var bodyA=c.bodyA;var bodyB=c.bodyB;vec2.set(eq.contactPointA,0,0);vec2.set(eq.contactPointB,0,0);vec2.set(eq.t,0,0);for(var i=0;i!==numContacts;i++){c=this.contactEquations[this.contactEquations.length-1-i];if(c.bodyA===bodyA){vec2.add(eq.t,eq.t,c.normalA);vec2.add(eq.contactPointA,eq.contactPointA,c.contactPointA);vec2.add(eq.contactPointB,eq.contactPointB,c.contactPointB)}else{vec2.sub(eq.t,eq.t,c.normalA);vec2.add(eq.contactPointA,eq.contactPointA,c.contactPointB);vec2.add(eq.contactPointB,eq.contactPointB,c.contactPointA)}eq.contactEquations.push(c)}var invNumContacts=1/numContacts;vec2.scale(eq.contactPointA,eq.contactPointA,invNumContacts);vec2.scale(eq.contactPointB,eq.contactPointB,invNumContacts);vec2.normalize(eq.t,eq.t);vec2.rotate90cw(eq.t,eq.t);return eq};Narrowphase.prototype[Shape.LINE|Shape.CONVEX]=Narrowphase.prototype.convexLine=function(convexBody,convexShape,convexOffset,convexAngle,lineBody,lineShape,lineOffset,lineAngle,justTest){if(justTest){return false}else{return 0}};Narrowphase.prototype[Shape.LINE|Shape.BOX]=Narrowphase.prototype.lineBox=function(lineBody,lineShape,lineOffset,lineAngle,boxBody,boxShape,boxOffset,boxAngle,justTest){if(justTest){return false}else{return 0}};function setConvexToCapsuleShapeMiddle(convexShape,capsuleShape){vec2.set(convexShape.vertices[0],-capsuleShape.length*.5,-capsuleShape.radius);vec2.set(convexShape.vertices[1],capsuleShape.length*.5,-capsuleShape.radius);vec2.set(convexShape.vertices[2],capsuleShape.length*.5,capsuleShape.radius);vec2.set(convexShape.vertices[3],-capsuleShape.length*.5,capsuleShape.radius)}var convexCapsule_tempRect=new Box({width:1,height:1}),convexCapsule_tempVec=vec2.create();Narrowphase.prototype[Shape.CAPSULE|Shape.CONVEX]=Narrowphase.prototype[Shape.CAPSULE|Shape.BOX]=Narrowphase.prototype.convexCapsule=function(convexBody,convexShape,convexPosition,convexAngle,capsuleBody,capsuleShape,capsulePosition,capsuleAngle,justTest){var circlePos=convexCapsule_tempVec;vec2.set(circlePos,capsuleShape.length/2,0);vec2.rotate(circlePos,circlePos,capsuleAngle);vec2.add(circlePos,circlePos,capsulePosition);var result1=this.circleConvex(capsuleBody,capsuleShape,circlePos,capsuleAngle,convexBody,convexShape,convexPosition,convexAngle,justTest,capsuleShape.radius);vec2.set(circlePos,-capsuleShape.length/2,0);vec2.rotate(circlePos,circlePos,capsuleAngle);vec2.add(circlePos,circlePos,capsulePosition);var result2=this.circleConvex(capsuleBody,capsuleShape,circlePos,capsuleAngle,convexBody,convexShape,convexPosition,convexAngle,justTest,capsuleShape.radius);if(justTest&&(result1||result2)){return true}var r=convexCapsule_tempRect;setConvexToCapsuleShapeMiddle(r,capsuleShape);var result=this.convexConvex(convexBody,convexShape,convexPosition,convexAngle,capsuleBody,r,capsulePosition,capsuleAngle,justTest);return result+result1+result2};Narrowphase.prototype[Shape.CAPSULE|Shape.LINE]=Narrowphase.prototype.lineCapsule=function(lineBody,lineShape,linePosition,lineAngle,capsuleBody,capsuleShape,capsulePosition,capsuleAngle,justTest){if(justTest){return false}else{return 0}};var capsuleCapsule_tempVec1=vec2.create();var capsuleCapsule_tempVec2=vec2.create();var capsuleCapsule_tempRect1=new Box({width:1,height:1});Narrowphase.prototype[Shape.CAPSULE|Shape.CAPSULE]=Narrowphase.prototype.capsuleCapsule=function(bi,si,xi,ai,bj,sj,xj,aj,justTest){var enableFrictionBefore;var circlePosi=capsuleCapsule_tempVec1,circlePosj=capsuleCapsule_tempVec2;var numContacts=0;for(var i=0;i<2;i++){vec2.set(circlePosi,(i===0?-1:1)*si.length/2,0);vec2.rotate(circlePosi,circlePosi,ai);vec2.add(circlePosi,circlePosi,xi);for(var j=0;j<2;j++){vec2.set(circlePosj,(j===0?-1:1)*sj.length/2,0);vec2.rotate(circlePosj,circlePosj,aj);vec2.add(circlePosj,circlePosj,xj);if(this.enableFrictionReduction){enableFrictionBefore=this.enableFriction;this.enableFriction=false}var result=this.circleCircle(bi,si,circlePosi,ai,bj,sj,circlePosj,aj,justTest,si.radius,sj.radius);if(this.enableFrictionReduction){this.enableFriction=enableFrictionBefore}if(justTest&&result){return true}numContacts+=result}}if(this.enableFrictionReduction){enableFrictionBefore=this.enableFriction;this.enableFriction=false}var rect=capsuleCapsule_tempRect1;setConvexToCapsuleShapeMiddle(rect,si);var result1=this.convexCapsule(bi,rect,xi,ai,bj,sj,xj,aj,justTest);if(this.enableFrictionReduction){this.enableFriction=enableFrictionBefore}if(justTest&&result1){return true}numContacts+=result1;if(this.enableFrictionReduction){var enableFrictionBefore=this.enableFriction;this.enableFriction=false}setConvexToCapsuleShapeMiddle(rect,sj);var result2=this.convexCapsule(bj,rect,xj,aj,bi,si,xi,ai,justTest);if(this.enableFrictionReduction){this.enableFriction=enableFrictionBefore}if(justTest&&result2){return true}numContacts+=result2;if(this.enableFrictionReduction){if(numContacts&&this.enableFriction){this.frictionEquations.push(this.createFrictionFromAverage(numContacts))}}return numContacts};Narrowphase.prototype[Shape.LINE|Shape.LINE]=Narrowphase.prototype.lineLine=function(bodyA,shapeA,positionA,angleA,bodyB,shapeB,positionB,angleB,justTest){if(justTest){return false}else{return 0}};Narrowphase.prototype[Shape.PLANE|Shape.LINE]=Narrowphase.prototype.planeLine=function(planeBody,planeShape,planeOffset,planeAngle,lineBody,lineShape,lineOffset,lineAngle,justTest){var worldVertex0=tmp1,worldVertex1=tmp2,worldVertex01=tmp3,worldVertex11=tmp4,worldEdge=tmp5,worldEdgeUnit=tmp6,dist=tmp7,worldNormal=tmp8,worldTangent=tmp9,verts=tmpArray,numContacts=0;vec2.set(worldVertex0,-lineShape.length/2,0);vec2.set(worldVertex1,lineShape.length/2,0);vec2.rotate(worldVertex01,worldVertex0,lineAngle);vec2.rotate(worldVertex11,worldVertex1,lineAngle);add(worldVertex01,worldVertex01,lineOffset);add(worldVertex11,worldVertex11,lineOffset);vec2.copy(worldVertex0,worldVertex01);vec2.copy(worldVertex1,worldVertex11);sub(worldEdge,worldVertex1,worldVertex0);vec2.normalize(worldEdgeUnit,worldEdge);vec2.rotate90cw(worldTangent,worldEdgeUnit);vec2.rotate(worldNormal,yAxis,planeAngle);verts[0]=worldVertex0;verts[1]=worldVertex1;for(var i=0;i<verts.length;i++){var v=verts[i];sub(dist,v,planeOffset);var d=dot(dist,worldNormal);if(d<0){if(justTest){return true}var c=this.createContactEquation(planeBody,lineBody,planeShape,lineShape);numContacts++;vec2.copy(c.normalA,worldNormal);vec2.normalize(c.normalA,c.normalA);vec2.scale(dist,worldNormal,d);sub(c.contactPointA,v,dist);sub(c.contactPointA,c.contactPointA,planeBody.position);sub(c.contactPointB,v,lineOffset);add(c.contactPointB,c.contactPointB,lineOffset);sub(c.contactPointB,c.contactPointB,lineBody.position);this.contactEquations.push(c);if(!this.enableFrictionReduction){if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}}}}if(justTest){return false}if(!this.enableFrictionReduction){if(numContacts&&this.enableFriction){this.frictionEquations.push(this.createFrictionFromAverage(numContacts))}}return numContacts};Narrowphase.prototype[Shape.PARTICLE|Shape.CAPSULE]=Narrowphase.prototype.particleCapsule=function(particleBody,particleShape,particlePosition,particleAngle,capsuleBody,capsuleShape,capsulePosition,capsuleAngle,justTest){return this.circleLine(particleBody,particleShape,particlePosition,particleAngle,capsuleBody,capsuleShape,capsulePosition,capsuleAngle,justTest,capsuleShape.radius,0)};Narrowphase.prototype[Shape.CIRCLE|Shape.LINE]=Narrowphase.prototype.circleLine=function(circleBody,circleShape,circleOffset,circleAngle,lineBody,lineShape,lineOffset,lineAngle,justTest,lineRadius,circleRadius){var lineRadius=lineRadius||0,circleRadius=typeof circleRadius!=="undefined"?circleRadius:circleShape.radius,orthoDist=tmp1,lineToCircleOrthoUnit=tmp2,projectedPoint=tmp3,centerDist=tmp4,worldTangent=tmp5,worldEdge=tmp6,worldEdgeUnit=tmp7,worldVertex0=tmp8,worldVertex1=tmp9,worldVertex01=tmp10,worldVertex11=tmp11,dist=tmp12,lineToCircle=tmp13,lineEndToLineRadius=tmp14,verts=tmpArray;vec2.set(worldVertex0,-lineShape.length/2,0);vec2.set(worldVertex1,lineShape.length/2,0);vec2.rotate(worldVertex01,worldVertex0,lineAngle);vec2.rotate(worldVertex11,worldVertex1,lineAngle);add(worldVertex01,worldVertex01,lineOffset);add(worldVertex11,worldVertex11,lineOffset);vec2.copy(worldVertex0,worldVertex01);vec2.copy(worldVertex1,worldVertex11);sub(worldEdge,worldVertex1,worldVertex0);vec2.normalize(worldEdgeUnit,worldEdge);vec2.rotate90cw(worldTangent,worldEdgeUnit);sub(dist,circleOffset,worldVertex0);var d=dot(dist,worldTangent);sub(centerDist,worldVertex0,lineOffset);sub(lineToCircle,circleOffset,lineOffset);var radiusSum=circleRadius+lineRadius;if(Math.abs(d)<radiusSum){vec2.scale(orthoDist,worldTangent,d);sub(projectedPoint,circleOffset,orthoDist);vec2.scale(lineToCircleOrthoUnit,worldTangent,dot(worldTangent,lineToCircle));vec2.normalize(lineToCircleOrthoUnit,lineToCircleOrthoUnit);vec2.scale(lineToCircleOrthoUnit,lineToCircleOrthoUnit,lineRadius);add(projectedPoint,projectedPoint,lineToCircleOrthoUnit);var pos=dot(worldEdgeUnit,projectedPoint);var pos0=dot(worldEdgeUnit,worldVertex0);var pos1=dot(worldEdgeUnit,worldVertex1);if(pos>pos0&&pos<pos1){if(justTest){return true}var c=this.createContactEquation(circleBody,lineBody,circleShape,lineShape);vec2.scale(c.normalA,orthoDist,-1);vec2.normalize(c.normalA,c.normalA);vec2.scale(c.contactPointA,c.normalA,circleRadius);add(c.contactPointA,c.contactPointA,circleOffset);sub(c.contactPointA,c.contactPointA,circleBody.position);sub(c.contactPointB,projectedPoint,lineOffset);add(c.contactPointB,c.contactPointB,lineOffset);sub(c.contactPointB,c.contactPointB,lineBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1}}verts[0]=worldVertex0;verts[1]=worldVertex1;for(var i=0;i<verts.length;i++){var v=verts[i];sub(dist,v,circleOffset);if(vec2.squaredLength(dist)<Math.pow(radiusSum,2)){if(justTest){return true}var c=this.createContactEquation(circleBody,lineBody,circleShape,lineShape);vec2.copy(c.normalA,dist);vec2.normalize(c.normalA,c.normalA);vec2.scale(c.contactPointA,c.normalA,circleRadius);add(c.contactPointA,c.contactPointA,circleOffset);sub(c.contactPointA,c.contactPointA,circleBody.position);sub(c.contactPointB,v,lineOffset);vec2.scale(lineEndToLineRadius,c.normalA,-lineRadius);add(c.contactPointB,c.contactPointB,lineEndToLineRadius);add(c.contactPointB,c.contactPointB,lineOffset);sub(c.contactPointB,c.contactPointB,lineBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1}}return 0};Narrowphase.prototype[Shape.CIRCLE|Shape.CAPSULE]=Narrowphase.prototype.circleCapsule=function(bi,si,xi,ai,bj,sj,xj,aj,justTest){return this.circleLine(bi,si,xi,ai,bj,sj,xj,aj,justTest,sj.radius)};Narrowphase.prototype[Shape.CIRCLE|Shape.CONVEX]=Narrowphase.prototype[Shape.CIRCLE|Shape.BOX]=Narrowphase.prototype.circleConvex=function(circleBody,circleShape,circleOffset,circleAngle,convexBody,convexShape,convexOffset,convexAngle,justTest,circleRadius){var circleRadius=typeof circleRadius==="number"?circleRadius:circleShape.radius;var worldVertex0=tmp1,worldVertex1=tmp2,worldEdge=tmp3,worldEdgeUnit=tmp4,worldNormal=tmp5,centerDist=tmp6,convexToCircle=tmp7,orthoDist=tmp8,projectedPoint=tmp9,dist=tmp10,worldVertex=tmp11,closestEdge=-1,closestEdgeDistance=null,closestEdgeOrthoDist=tmp12,closestEdgeProjectedPoint=tmp13,candidate=tmp14,candidateDist=tmp15,minCandidate=tmp16,found=false,minCandidateDistance=Number.MAX_VALUE;var numReported=0;var verts=convexShape.vertices;for(var i=0;i!==verts.length+1;i++){var v0=verts[i%verts.length],v1=verts[(i+1)%verts.length];vec2.rotate(worldVertex0,v0,convexAngle);vec2.rotate(worldVertex1,v1,convexAngle);add(worldVertex0,worldVertex0,convexOffset);add(worldVertex1,worldVertex1,convexOffset);sub(worldEdge,worldVertex1,worldVertex0);vec2.normalize(worldEdgeUnit,worldEdge);vec2.rotate90cw(worldNormal,worldEdgeUnit);vec2.scale(candidate,worldNormal,-circleShape.radius);add(candidate,candidate,circleOffset);if(pointInConvex(candidate,convexShape,convexOffset,convexAngle)){vec2.sub(candidateDist,worldVertex0,candidate);var candidateDistance=Math.abs(vec2.dot(candidateDist,worldNormal));if(candidateDistance<minCandidateDistance){vec2.copy(minCandidate,candidate);minCandidateDistance=candidateDistance;vec2.scale(closestEdgeProjectedPoint,worldNormal,candidateDistance);vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,candidate);found=true}}}if(found){if(justTest){return true}var c=this.createContactEquation(circleBody,convexBody,circleShape,convexShape);vec2.sub(c.normalA,minCandidate,circleOffset);vec2.normalize(c.normalA,c.normalA);vec2.scale(c.contactPointA,c.normalA,circleRadius);add(c.contactPointA,c.contactPointA,circleOffset);sub(c.contactPointA,c.contactPointA,circleBody.position);sub(c.contactPointB,closestEdgeProjectedPoint,convexOffset);add(c.contactPointB,c.contactPointB,convexOffset);sub(c.contactPointB,c.contactPointB,convexBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1}if(circleRadius>0){for(var i=0;i<verts.length;i++){var localVertex=verts[i];vec2.rotate(worldVertex,localVertex,convexAngle);add(worldVertex,worldVertex,convexOffset);sub(dist,worldVertex,circleOffset);if(vec2.squaredLength(dist)<Math.pow(circleRadius,2)){if(justTest){return true}var c=this.createContactEquation(circleBody,convexBody,circleShape,convexShape);vec2.copy(c.normalA,dist);vec2.normalize(c.normalA,c.normalA);vec2.scale(c.contactPointA,c.normalA,circleRadius);add(c.contactPointA,c.contactPointA,circleOffset);sub(c.contactPointA,c.contactPointA,circleBody.position);sub(c.contactPointB,worldVertex,convexOffset);add(c.contactPointB,c.contactPointB,convexOffset);sub(c.contactPointB,c.contactPointB,convexBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1}}}return 0};var pic_worldVertex0=vec2.create(),pic_worldVertex1=vec2.create(),pic_r0=vec2.create(),pic_r1=vec2.create();function pointInConvex(worldPoint,convexShape,convexOffset,convexAngle){var worldVertex0=pic_worldVertex0,worldVertex1=pic_worldVertex1,r0=pic_r0,r1=pic_r1,point=worldPoint,verts=convexShape.vertices,lastCross=null;for(var i=0;i!==verts.length+1;i++){var v0=verts[i%verts.length],v1=verts[(i+1)%verts.length];vec2.rotate(worldVertex0,v0,convexAngle);vec2.rotate(worldVertex1,v1,convexAngle);add(worldVertex0,worldVertex0,convexOffset);add(worldVertex1,worldVertex1,convexOffset);sub(r0,worldVertex0,point);sub(r1,worldVertex1,point);var cross=vec2.crossLength(r0,r1);if(lastCross===null){lastCross=cross}if(cross*lastCross<=0){return false}lastCross=cross}return true}Narrowphase.prototype[Shape.PARTICLE|Shape.CONVEX]=Narrowphase.prototype[Shape.PARTICLE|Shape.BOX]=Narrowphase.prototype.particleConvex=function(particleBody,particleShape,particleOffset,particleAngle,convexBody,convexShape,convexOffset,convexAngle,justTest){var worldVertex0=tmp1,worldVertex1=tmp2,worldEdge=tmp3,worldEdgeUnit=tmp4,worldTangent=tmp5,centerDist=tmp6,convexToparticle=tmp7,orthoDist=tmp8,projectedPoint=tmp9,dist=tmp10,worldVertex=tmp11,closestEdge=-1,closestEdgeDistance=null,closestEdgeOrthoDist=tmp12,closestEdgeProjectedPoint=tmp13,r0=tmp14,r1=tmp15,localPoint=tmp16,candidateDist=tmp17,minEdgeNormal=tmp18,minCandidateDistance=Number.MAX_VALUE;var numReported=0,found=false,verts=convexShape.vertices;if(!pointInConvex(particleOffset,convexShape,convexOffset,convexAngle)){return 0}if(justTest){return true}var lastCross=null;for(var i=0;i!==verts.length+1;i++){var v0=verts[i%verts.length],v1=verts[(i+1)%verts.length];vec2.rotate(worldVertex0,v0,convexAngle);vec2.rotate(worldVertex1,v1,convexAngle);add(worldVertex0,worldVertex0,convexOffset);add(worldVertex1,worldVertex1,convexOffset);sub(worldEdge,worldVertex1,worldVertex0);vec2.normalize(worldEdgeUnit,worldEdge);vec2.rotate90cw(worldTangent,worldEdgeUnit);sub(dist,particleOffset,worldVertex0);var d=dot(dist,worldTangent);sub(centerDist,worldVertex0,convexOffset);sub(convexToparticle,particleOffset,convexOffset);vec2.sub(candidateDist,worldVertex0,particleOffset);var candidateDistance=Math.abs(vec2.dot(candidateDist,worldTangent));if(candidateDistance<minCandidateDistance){minCandidateDistance=candidateDistance;vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance);vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,particleOffset);vec2.copy(minEdgeNormal,worldTangent);found=true}}if(found){var c=this.createContactEquation(particleBody,convexBody,particleShape,convexShape);vec2.scale(c.normalA,minEdgeNormal,-1);vec2.normalize(c.normalA,c.normalA);vec2.set(c.contactPointA,0,0);add(c.contactPointA,c.contactPointA,particleOffset);sub(c.contactPointA,c.contactPointA,particleBody.position);sub(c.contactPointB,closestEdgeProjectedPoint,convexOffset);add(c.contactPointB,c.contactPointB,convexOffset);sub(c.contactPointB,c.contactPointB,convexBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1}return 0};Narrowphase.prototype[Shape.CIRCLE]=Narrowphase.prototype.circleCircle=function(bodyA,shapeA,offsetA,angleA,bodyB,shapeB,offsetB,angleB,justTest,radiusA,radiusB){var dist=tmp1,radiusA=radiusA||shapeA.radius,radiusB=radiusB||shapeB.radius;sub(dist,offsetA,offsetB);var r=radiusA+radiusB;if(vec2.squaredLength(dist)>Math.pow(r,2)){return 0}if(justTest){return true}var c=this.createContactEquation(bodyA,bodyB,shapeA,shapeB);sub(c.normalA,offsetB,offsetA);vec2.normalize(c.normalA,c.normalA);vec2.scale(c.contactPointA,c.normalA,radiusA);vec2.scale(c.contactPointB,c.normalA,-radiusB);add(c.contactPointA,c.contactPointA,offsetA);sub(c.contactPointA,c.contactPointA,bodyA.position);add(c.contactPointB,c.contactPointB,offsetB);sub(c.contactPointB,c.contactPointB,bodyB.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1};Narrowphase.prototype[Shape.PLANE|Shape.CONVEX]=Narrowphase.prototype[Shape.PLANE|Shape.BOX]=Narrowphase.prototype.planeConvex=function(planeBody,planeShape,planeOffset,planeAngle,convexBody,convexShape,convexOffset,convexAngle,justTest){var worldVertex=tmp1,worldNormal=tmp2,dist=tmp3;var numReported=0;vec2.rotate(worldNormal,yAxis,planeAngle);for(var i=0;i!==convexShape.vertices.length;i++){var v=convexShape.vertices[i];vec2.rotate(worldVertex,v,convexAngle);add(worldVertex,worldVertex,convexOffset);sub(dist,worldVertex,planeOffset);if(dot(dist,worldNormal)<=0){if(justTest){return true}numReported++;var c=this.createContactEquation(planeBody,convexBody,planeShape,convexShape);sub(dist,worldVertex,planeOffset);vec2.copy(c.normalA,worldNormal);var d=dot(dist,c.normalA);vec2.scale(dist,c.normalA,d);sub(c.contactPointB,worldVertex,convexBody.position);sub(c.contactPointA,worldVertex,dist);sub(c.contactPointA,c.contactPointA,planeBody.position);this.contactEquations.push(c);if(!this.enableFrictionReduction){if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}}}}if(this.enableFrictionReduction){if(this.enableFriction&&numReported){this.frictionEquations.push(this.createFrictionFromAverage(numReported))}}return numReported};Narrowphase.prototype[Shape.PARTICLE|Shape.PLANE]=Narrowphase.prototype.particlePlane=function(particleBody,particleShape,particleOffset,particleAngle,planeBody,planeShape,planeOffset,planeAngle,justTest){var dist=tmp1,worldNormal=tmp2;planeAngle=planeAngle||0;sub(dist,particleOffset,planeOffset);vec2.rotate(worldNormal,yAxis,planeAngle);var d=dot(dist,worldNormal);if(d>0){return 0}if(justTest){return true}var c=this.createContactEquation(planeBody,particleBody,planeShape,particleShape);vec2.copy(c.normalA,worldNormal);vec2.scale(dist,c.normalA,d);sub(c.contactPointA,particleOffset,dist);sub(c.contactPointA,c.contactPointA,planeBody.position);sub(c.contactPointB,particleOffset,particleBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1};Narrowphase.prototype[Shape.CIRCLE|Shape.PARTICLE]=Narrowphase.prototype.circleParticle=function(circleBody,circleShape,circleOffset,circleAngle,particleBody,particleShape,particleOffset,particleAngle,justTest){var dist=tmp1;sub(dist,particleOffset,circleOffset);if(vec2.squaredLength(dist)>Math.pow(circleShape.radius,2)){return 0}if(justTest){return true}var c=this.createContactEquation(circleBody,particleBody,circleShape,particleShape);vec2.copy(c.normalA,dist);vec2.normalize(c.normalA,c.normalA);vec2.scale(c.contactPointA,c.normalA,circleShape.radius);add(c.contactPointA,c.contactPointA,circleOffset);sub(c.contactPointA,c.contactPointA,circleBody.position);sub(c.contactPointB,particleOffset,particleBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1};var planeCapsule_tmpCircle=new Circle({radius:1}),planeCapsule_tmp1=vec2.create(),planeCapsule_tmp2=vec2.create(),planeCapsule_tmp3=vec2.create();Narrowphase.prototype[Shape.PLANE|Shape.CAPSULE]=Narrowphase.prototype.planeCapsule=function(planeBody,planeShape,planeOffset,planeAngle,capsuleBody,capsuleShape,capsuleOffset,capsuleAngle,justTest){var end1=planeCapsule_tmp1,end2=planeCapsule_tmp2,circle=planeCapsule_tmpCircle,dst=planeCapsule_tmp3;vec2.set(end1,-capsuleShape.length/2,0);vec2.rotate(end1,end1,capsuleAngle);add(end1,end1,capsuleOffset);vec2.set(end2,capsuleShape.length/2,0);vec2.rotate(end2,end2,capsuleAngle);add(end2,end2,capsuleOffset);circle.radius=capsuleShape.radius;var enableFrictionBefore;if(this.enableFrictionReduction){enableFrictionBefore=this.enableFriction;this.enableFriction=false}var numContacts1=this.circlePlane(capsuleBody,circle,end1,0,planeBody,planeShape,planeOffset,planeAngle,justTest),numContacts2=this.circlePlane(capsuleBody,circle,end2,0,planeBody,planeShape,planeOffset,planeAngle,justTest);if(this.enableFrictionReduction){this.enableFriction=enableFrictionBefore}if(justTest){return numContacts1||numContacts2}else{var numTotal=numContacts1+numContacts2;if(this.enableFrictionReduction){if(numTotal){this.frictionEquations.push(this.createFrictionFromAverage(numTotal))}}return numTotal}};Narrowphase.prototype[Shape.CIRCLE|Shape.PLANE]=Narrowphase.prototype.circlePlane=function(bi,si,xi,ai,bj,sj,xj,aj,justTest){var circleBody=bi,circleShape=si,circleOffset=xi,planeBody=bj,shapeB=sj,planeOffset=xj,planeAngle=aj;planeAngle=planeAngle||0;var planeToCircle=tmp1,worldNormal=tmp2,temp=tmp3;sub(planeToCircle,circleOffset,planeOffset);vec2.rotate(worldNormal,yAxis,planeAngle);var d=dot(worldNormal,planeToCircle);if(d>circleShape.radius){return 0}if(justTest){return true}var contact=this.createContactEquation(planeBody,circleBody,sj,si);vec2.copy(contact.normalA,worldNormal);vec2.scale(contact.contactPointB,contact.normalA,-circleShape.radius);add(contact.contactPointB,contact.contactPointB,circleOffset);sub(contact.contactPointB,contact.contactPointB,circleBody.position);vec2.scale(temp,contact.normalA,d);sub(contact.contactPointA,planeToCircle,temp);add(contact.contactPointA,contact.contactPointA,planeOffset);sub(contact.contactPointA,contact.contactPointA,planeBody.position);this.contactEquations.push(contact);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(contact))}return 1};Narrowphase.prototype[Shape.CONVEX]=Narrowphase.prototype[Shape.CONVEX|Shape.BOX]=Narrowphase.prototype[Shape.BOX]=Narrowphase.prototype.convexConvex=function(bi,si,xi,ai,bj,sj,xj,aj,justTest,precision){var sepAxis=tmp1,worldPoint=tmp2,worldPoint0=tmp3,worldPoint1=tmp4,worldEdge=tmp5,projected=tmp6,penetrationVec=tmp7,dist=tmp8,worldNormal=tmp9,numContacts=0,precision=typeof precision==="number"?precision:0;var found=Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis);if(!found){return 0}sub(dist,xj,xi);if(dot(sepAxis,dist)>0){vec2.scale(sepAxis,sepAxis,-1)}var closestEdge1=Narrowphase.getClosestEdge(si,ai,sepAxis,true),closestEdge2=Narrowphase.getClosestEdge(sj,aj,sepAxis);if(closestEdge1===-1||closestEdge2===-1){return 0}for(var k=0;k<2;k++){var closestEdgeA=closestEdge1,closestEdgeB=closestEdge2,shapeA=si,shapeB=sj,offsetA=xi,offsetB=xj,angleA=ai,angleB=aj,bodyA=bi,bodyB=bj;if(k===0){var tmp;tmp=closestEdgeA;closestEdgeA=closestEdgeB;closestEdgeB=tmp;tmp=shapeA;shapeA=shapeB;shapeB=tmp;tmp=offsetA;offsetA=offsetB;offsetB=tmp;tmp=angleA;angleA=angleB;angleB=tmp;tmp=bodyA;bodyA=bodyB;bodyB=tmp}for(var j=closestEdgeB;j<closestEdgeB+2;j++){var v=shapeB.vertices[(j+shapeB.vertices.length)%shapeB.vertices.length];vec2.rotate(worldPoint,v,angleB);add(worldPoint,worldPoint,offsetB);var insideNumEdges=0;for(var i=closestEdgeA-1;i<closestEdgeA+2;i++){var v0=shapeA.vertices[(i+shapeA.vertices.length)%shapeA.vertices.length],v1=shapeA.vertices[(i+1+shapeA.vertices.length)%shapeA.vertices.length];vec2.rotate(worldPoint0,v0,angleA);vec2.rotate(worldPoint1,v1,angleA);add(worldPoint0,worldPoint0,offsetA);add(worldPoint1,worldPoint1,offsetA);sub(worldEdge,worldPoint1,worldPoint0);vec2.rotate90cw(worldNormal,worldEdge);vec2.normalize(worldNormal,worldNormal);sub(dist,worldPoint,worldPoint0);var d=dot(worldNormal,dist);if(i===closestEdgeA&&d<=precision||i!==closestEdgeA&&d<=0){insideNumEdges++}}if(insideNumEdges>=3){if(justTest){return true}var c=this.createContactEquation(bodyA,bodyB,shapeA,shapeB);numContacts++;var v0=shapeA.vertices[closestEdgeA%shapeA.vertices.length],v1=shapeA.vertices[(closestEdgeA+1)%shapeA.vertices.length];vec2.rotate(worldPoint0,v0,angleA);vec2.rotate(worldPoint1,v1,angleA);add(worldPoint0,worldPoint0,offsetA);add(worldPoint1,worldPoint1,offsetA);sub(worldEdge,worldPoint1,worldPoint0);vec2.rotate90cw(c.normalA,worldEdge);vec2.normalize(c.normalA,c.normalA);sub(dist,worldPoint,worldPoint0);var d=dot(c.normalA,dist);vec2.scale(penetrationVec,c.normalA,d);sub(c.contactPointA,worldPoint,offsetA);sub(c.contactPointA,c.contactPointA,penetrationVec);add(c.contactPointA,c.contactPointA,offsetA);sub(c.contactPointA,c.contactPointA,bodyA.position);sub(c.contactPointB,worldPoint,offsetB);add(c.contactPointB,c.contactPointB,offsetB);sub(c.contactPointB,c.contactPointB,bodyB.position);this.contactEquations.push(c);if(!this.enableFrictionReduction){if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}}}}}if(this.enableFrictionReduction){if(this.enableFriction&&numContacts){this.frictionEquations.push(this.createFrictionFromAverage(numContacts))}}return numContacts};var pcoa_tmp1=vec2.fromValues(0,0);Narrowphase.projectConvexOntoAxis=function(convexShape,convexOffset,convexAngle,worldAxis,result){var max=null,min=null,v,value,localAxis=pcoa_tmp1;vec2.rotate(localAxis,worldAxis,-convexAngle);for(var i=0;i<convexShape.vertices.length;i++){v=convexShape.vertices[i];value=dot(v,localAxis);if(max===null||value>max){max=value}if(min===null||value<min){min=value}}if(min>max){var t=min;min=max;max=t}var offset=dot(convexOffset,worldAxis);vec2.set(result,min+offset,max+offset)};var fsa_tmp1=vec2.fromValues(0,0),fsa_tmp2=vec2.fromValues(0,0),fsa_tmp3=vec2.fromValues(0,0),fsa_tmp4=vec2.fromValues(0,0),fsa_tmp5=vec2.fromValues(0,0),fsa_tmp6=vec2.fromValues(0,0);Narrowphase.findSeparatingAxis=function(c1,offset1,angle1,c2,offset2,angle2,sepAxis){var maxDist=null,overlap=false,found=false,edge=fsa_tmp1,worldPoint0=fsa_tmp2,worldPoint1=fsa_tmp3,normal=fsa_tmp4,span1=fsa_tmp5,span2=fsa_tmp6;if(c1 instanceof Box&&c2 instanceof Box){for(var j=0;j!==2;j++){var c=c1,angle=angle1;if(j===1){c=c2;angle=angle2}for(var i=0;i!==2;i++){if(i===0){vec2.set(normal,0,1)}else if(i===1){vec2.set(normal,1,0)}if(angle!==0){vec2.rotate(normal,normal,angle)}Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);var a=span1,b=span2,swapped=false;if(span1[0]>span2[0]){b=span1;a=span2;swapped=true}var dist=b[0]-a[1];overlap=dist<=0;if(maxDist===null||dist>maxDist){vec2.copy(sepAxis,normal);maxDist=dist;found=overlap}}}}else{for(var j=0;j!==2;j++){var c=c1,angle=angle1;if(j===1){c=c2;angle=angle2}for(var i=0;i!==c.vertices.length;i++){vec2.rotate(worldPoint0,c.vertices[i],angle);vec2.rotate(worldPoint1,c.vertices[(i+1)%c.vertices.length],angle);sub(edge,worldPoint1,worldPoint0);vec2.rotate90cw(normal,edge);vec2.normalize(normal,normal);Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);var a=span1,b=span2,swapped=false;if(span1[0]>span2[0]){b=span1;a=span2;swapped=true}var dist=b[0]-a[1];overlap=dist<=0;if(maxDist===null||dist>maxDist){vec2.copy(sepAxis,normal);maxDist=dist;found=overlap}}}}return found};var gce_tmp1=vec2.fromValues(0,0),gce_tmp2=vec2.fromValues(0,0),gce_tmp3=vec2.fromValues(0,0);Narrowphase.getClosestEdge=function(c,angle,axis,flip){var localAxis=gce_tmp1,edge=gce_tmp2,normal=gce_tmp3;vec2.rotate(localAxis,axis,-angle);if(flip){vec2.scale(localAxis,localAxis,-1)}var closestEdge=-1,N=c.vertices.length,maxDot=-1;for(var i=0;i!==N;i++){sub(edge,c.vertices[(i+1)%N],c.vertices[i%N]);vec2.rotate90cw(normal,edge);vec2.normalize(normal,normal);var d=dot(normal,localAxis);if(closestEdge===-1||d>maxDot){closestEdge=i%N;maxDot=d}}return closestEdge};var circleHeightfield_candidate=vec2.create(),circleHeightfield_dist=vec2.create(),circleHeightfield_v0=vec2.create(),circleHeightfield_v1=vec2.create(),circleHeightfield_minCandidate=vec2.create(),circleHeightfield_worldNormal=vec2.create(),circleHeightfield_minCandidateNormal=vec2.create();Narrowphase.prototype[Shape.CIRCLE|Shape.HEIGHTFIELD]=Narrowphase.prototype.circleHeightfield=function(circleBody,circleShape,circlePos,circleAngle,hfBody,hfShape,hfPos,hfAngle,justTest,radius){var data=hfShape.heights,radius=radius||circleShape.radius,w=hfShape.elementWidth,dist=circleHeightfield_dist,candidate=circleHeightfield_candidate,minCandidate=circleHeightfield_minCandidate,minCandidateNormal=circleHeightfield_minCandidateNormal,worldNormal=circleHeightfield_worldNormal,v0=circleHeightfield_v0,v1=circleHeightfield_v1; | |
var idxA=Math.floor((circlePos[0]-radius-hfPos[0])/w),idxB=Math.ceil((circlePos[0]+radius-hfPos[0])/w);if(idxA<0){idxA=0}if(idxB>=data.length){idxB=data.length-1}var max=data[idxA],min=data[idxB];for(var i=idxA;i<idxB;i++){if(data[i]<min){min=data[i]}if(data[i]>max){max=data[i]}}if(circlePos[1]-radius>max){return justTest?false:0}var found=false;for(var i=idxA;i<idxB;i++){vec2.set(v0,i*w,data[i]);vec2.set(v1,(i+1)*w,data[i+1]);vec2.add(v0,v0,hfPos);vec2.add(v1,v1,hfPos);vec2.sub(worldNormal,v1,v0);vec2.rotate(worldNormal,worldNormal,Math.PI/2);vec2.normalize(worldNormal,worldNormal);vec2.scale(candidate,worldNormal,-radius);vec2.add(candidate,candidate,circlePos);vec2.sub(dist,candidate,v0);var d=vec2.dot(dist,worldNormal);if(candidate[0]>=v0[0]&&candidate[0]<v1[0]&&d<=0){if(justTest){return true}found=true;vec2.scale(dist,worldNormal,-d);vec2.add(minCandidate,candidate,dist);vec2.copy(minCandidateNormal,worldNormal);var c=this.createContactEquation(hfBody,circleBody,hfShape,circleShape);vec2.copy(c.normalA,minCandidateNormal);vec2.scale(c.contactPointB,c.normalA,-radius);add(c.contactPointB,c.contactPointB,circlePos);sub(c.contactPointB,c.contactPointB,circleBody.position);vec2.copy(c.contactPointA,minCandidate);vec2.sub(c.contactPointA,c.contactPointA,hfBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}}}found=false;if(radius>0){for(var i=idxA;i<=idxB;i++){vec2.set(v0,i*w,data[i]);vec2.add(v0,v0,hfPos);vec2.sub(dist,circlePos,v0);if(vec2.squaredLength(dist)<Math.pow(radius,2)){if(justTest){return true}found=true;var c=this.createContactEquation(hfBody,circleBody,hfShape,circleShape);vec2.copy(c.normalA,dist);vec2.normalize(c.normalA,c.normalA);vec2.scale(c.contactPointB,c.normalA,-radius);add(c.contactPointB,c.contactPointB,circlePos);sub(c.contactPointB,c.contactPointB,circleBody.position);sub(c.contactPointA,v0,hfPos);add(c.contactPointA,c.contactPointA,hfPos);sub(c.contactPointA,c.contactPointA,hfBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}}}}if(found){return 1}return 0};var convexHeightfield_v0=vec2.create(),convexHeightfield_v1=vec2.create(),convexHeightfield_tilePos=vec2.create(),convexHeightfield_tempConvexShape=new Convex({vertices:[vec2.create(),vec2.create(),vec2.create(),vec2.create()]});Narrowphase.prototype[Shape.BOX|Shape.HEIGHTFIELD]=Narrowphase.prototype[Shape.CONVEX|Shape.HEIGHTFIELD]=Narrowphase.prototype.convexHeightfield=function(convexBody,convexShape,convexPos,convexAngle,hfBody,hfShape,hfPos,hfAngle,justTest){var data=hfShape.heights,w=hfShape.elementWidth,v0=convexHeightfield_v0,v1=convexHeightfield_v1,tilePos=convexHeightfield_tilePos,tileConvex=convexHeightfield_tempConvexShape;var idxA=Math.floor((convexBody.aabb.lowerBound[0]-hfPos[0])/w),idxB=Math.ceil((convexBody.aabb.upperBound[0]-hfPos[0])/w);if(idxA<0){idxA=0}if(idxB>=data.length){idxB=data.length-1}var max=data[idxA],min=data[idxB];for(var i=idxA;i<idxB;i++){if(data[i]<min){min=data[i]}if(data[i]>max){max=data[i]}}if(convexBody.aabb.lowerBound[1]>max){return justTest?false:0}var found=false;var numContacts=0;for(var i=idxA;i<idxB;i++){vec2.set(v0,i*w,data[i]);vec2.set(v1,(i+1)*w,data[i+1]);vec2.add(v0,v0,hfPos);vec2.add(v1,v1,hfPos);var tileHeight=100;vec2.set(tilePos,(v1[0]+v0[0])*.5,(v1[1]+v0[1]-tileHeight)*.5);vec2.sub(tileConvex.vertices[0],v1,tilePos);vec2.sub(tileConvex.vertices[1],v0,tilePos);vec2.copy(tileConvex.vertices[2],tileConvex.vertices[1]);vec2.copy(tileConvex.vertices[3],tileConvex.vertices[0]);tileConvex.vertices[2][1]-=tileHeight;tileConvex.vertices[3][1]-=tileHeight;numContacts+=this.convexConvex(convexBody,convexShape,convexPos,convexAngle,hfBody,tileConvex,tilePos,0,justTest)}return numContacts}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Box":36,"../shapes/Circle":38,"../shapes/Convex":39,"../shapes/Shape":44,"../utils/ContactEquationPool":47,"../utils/FrictionEquationPool":48,"../utils/TupleDictionary":55,"../utils/Utils":56}],11:[function(require,module,exports){module.exports=Ray;var vec2=require("../math/vec2");var RaycastResult=require("../collision/RaycastResult");var Shape=require("../shapes/Shape");var AABB=require("../collision/AABB");function Ray(options){options=options||{};this.from=options.from?vec2.fromValues(options.from[0],options.from[1]):vec2.create();this.to=options.to?vec2.fromValues(options.to[0],options.to[1]):vec2.create();this.checkCollisionResponse=options.checkCollisionResponse!==undefined?options.checkCollisionResponse:true;this.skipBackfaces=!!options.skipBackfaces;this.collisionMask=options.collisionMask!==undefined?options.collisionMask:-1;this.collisionGroup=options.collisionGroup!==undefined?options.collisionGroup:-1;this.mode=options.mode!==undefined?options.mode:Ray.ANY;this.callback=options.callback||function(result){};this.direction=vec2.create();this.length=1;this.update()}Ray.prototype.constructor=Ray;Ray.CLOSEST=1;Ray.ANY=2;Ray.ALL=4;Ray.prototype.update=function(){var d=this.direction;vec2.sub(d,this.to,this.from);this.length=vec2.length(d);vec2.normalize(d,d)};Ray.prototype.intersectBodies=function(result,bodies){for(var i=0,l=bodies.length;!result.shouldStop(this)&&i<l;i++){var body=bodies[i];var aabb=body.getAABB();if(aabb.overlapsRay(this)>=0||aabb.containsPoint(this.from)){this.intersectBody(result,body)}}};var intersectBody_worldPosition=vec2.create();Ray.prototype.intersectBody=function(result,body){var checkCollisionResponse=this.checkCollisionResponse;if(checkCollisionResponse&&!body.collisionResponse){return}var worldPosition=intersectBody_worldPosition;for(var i=0,N=body.shapes.length;i<N;i++){var shape=body.shapes[i];if(checkCollisionResponse&&!shape.collisionResponse){continue}if((this.collisionGroup&shape.collisionMask)===0||(shape.collisionGroup&this.collisionMask)===0){continue}vec2.rotate(worldPosition,shape.position,body.angle);vec2.add(worldPosition,worldPosition,body.position);var worldAngle=shape.angle+body.angle;this.intersectShape(result,shape,worldAngle,worldPosition,body);if(result.shouldStop(this)){break}}};Ray.prototype.intersectShape=function(result,shape,angle,position,body){var from=this.from;var distance=distanceFromIntersectionSquared(from,this.direction,position);if(distance>shape.boundingRadius*shape.boundingRadius){return}this._currentBody=body;this._currentShape=shape;shape.raycast(result,this,position,angle);this._currentBody=this._currentShape=null};Ray.prototype.getAABB=function(result){var to=this.to;var from=this.from;vec2.set(result.lowerBound,Math.min(to[0],from[0]),Math.min(to[1],from[1]));vec2.set(result.upperBound,Math.max(to[0],from[0]),Math.max(to[1],from[1]))};var hitPointWorld=vec2.create();Ray.prototype.reportIntersection=function(result,fraction,normal,faceIndex){var from=this.from;var to=this.to;var shape=this._currentShape;var body=this._currentBody;if(this.skipBackfaces&&vec2.dot(normal,this.direction)>0){return}switch(this.mode){case Ray.ALL:result.set(normal,shape,body,fraction,faceIndex);this.callback(result);break;case Ray.CLOSEST:if(fraction<result.fraction||!result.hasHit()){result.set(normal,shape,body,fraction,faceIndex)}break;case Ray.ANY:result.set(normal,shape,body,fraction,faceIndex);break}};var v0=vec2.create(),intersect=vec2.create();function distanceFromIntersectionSquared(from,direction,position){vec2.sub(v0,position,from);var dot=vec2.dot(v0,direction);vec2.scale(intersect,direction,dot);vec2.add(intersect,intersect,from);return vec2.squaredDistance(position,intersect)}},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":44}],12:[function(require,module,exports){var vec2=require("../math/vec2");var Ray=require("../collision/Ray");module.exports=RaycastResult;function RaycastResult(){this.normal=vec2.create();this.shape=null;this.body=null;this.faceIndex=-1;this.fraction=-1;this.isStopped=false}RaycastResult.prototype.reset=function(){vec2.set(this.normal,0,0);this.shape=null;this.body=null;this.faceIndex=-1;this.fraction=-1;this.isStopped=false};RaycastResult.prototype.getHitDistance=function(ray){return vec2.distance(ray.from,ray.to)*this.fraction};RaycastResult.prototype.hasHit=function(){return this.fraction!==-1};RaycastResult.prototype.getHitPoint=function(out,ray){vec2.lerp(out,ray.from,ray.to,this.fraction)};RaycastResult.prototype.stop=function(){this.isStopped=true};RaycastResult.prototype.shouldStop=function(ray){return this.isStopped||this.fraction!==-1&&ray.mode===Ray.ANY};RaycastResult.prototype.set=function(normal,shape,body,fraction,faceIndex){vec2.copy(this.normal,normal);this.shape=shape;this.body=body;this.fraction=fraction;this.faceIndex=faceIndex}},{"../collision/Ray":11,"../math/vec2":30}],13:[function(require,module,exports){var Utils=require("../utils/Utils"),Broadphase=require("../collision/Broadphase");module.exports=SAPBroadphase;function SAPBroadphase(){Broadphase.call(this,Broadphase.SAP);this.axisList=[];this.axisIndex=0;var that=this;this._addBodyHandler=function(e){that.axisList.push(e.body)};this._removeBodyHandler=function(e){var idx=that.axisList.indexOf(e.body);if(idx!==-1){that.axisList.splice(idx,1)}}}SAPBroadphase.prototype=new Broadphase;SAPBroadphase.prototype.constructor=SAPBroadphase;SAPBroadphase.prototype.setWorld=function(world){this.axisList.length=0;Utils.appendArray(this.axisList,world.bodies);world.off("addBody",this._addBodyHandler).off("removeBody",this._removeBodyHandler);world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler);this.world=world};SAPBroadphase.sortAxisList=function(a,axisIndex){axisIndex=axisIndex|0;for(var i=1,l=a.length;i<l;i++){var v=a[i];for(var j=i-1;j>=0;j--){if(a[j].aabb.lowerBound[axisIndex]<=v.aabb.lowerBound[axisIndex]){break}a[j+1]=a[j]}a[j+1]=v}return a};SAPBroadphase.prototype.sortList=function(){var bodies=this.axisList,axisIndex=this.axisIndex;SAPBroadphase.sortAxisList(bodies,axisIndex)};SAPBroadphase.prototype.getCollisionPairs=function(world){var bodies=this.axisList,result=this.result,axisIndex=this.axisIndex;result.length=0;var l=bodies.length;while(l--){var b=bodies[l];if(b.aabbNeedsUpdate){b.updateAABB()}}this.sortList();for(var i=0,N=bodies.length|0;i!==N;i++){var bi=bodies[i];for(var j=i+1;j<N;j++){var bj=bodies[j];var overlaps=bj.aabb.lowerBound[axisIndex]<=bi.aabb.upperBound[axisIndex];if(!overlaps){break}if(Broadphase.canCollide(bi,bj)&&this.boundingVolumeCheck(bi,bj)){result.push(bi,bj)}}}return result};SAPBroadphase.prototype.aabbQuery=function(world,aabb,result){result=result||[];this.sortList();var axisIndex=this.axisIndex;var axis="x";if(axisIndex===1){axis="y"}if(axisIndex===2){axis="z"}var axisList=this.axisList;var lower=aabb.lowerBound[axis];var upper=aabb.upperBound[axis];for(var i=0;i<axisList.length;i++){var b=axisList[i];if(b.aabbNeedsUpdate){b.updateAABB()}if(b.aabb.overlaps(aabb)){result.push(b)}}return result}},{"../collision/Broadphase":8,"../utils/Utils":56}],14:[function(require,module,exports){module.exports=Constraint;var Utils=require("../utils/Utils");function Constraint(bodyA,bodyB,type,options){this.type=type;options=Utils.defaults(options,{collideConnected:true,wakeUpBodies:true});this.equations=[];this.bodyA=bodyA;this.bodyB=bodyB;this.collideConnected=options.collideConnected;if(options.wakeUpBodies){if(bodyA){bodyA.wakeUp()}if(bodyB){bodyB.wakeUp()}}}Constraint.prototype.update=function(){throw new Error("method update() not implmemented in this Constraint subclass!")};Constraint.DISTANCE=1;Constraint.GEAR=2;Constraint.LOCK=3;Constraint.PRISMATIC=4;Constraint.REVOLUTE=5;Constraint.prototype.setStiffness=function(stiffness){var eqs=this.equations;for(var i=0;i!==eqs.length;i++){var eq=eqs[i];eq.stiffness=stiffness;eq.needsUpdate=true}};Constraint.prototype.setRelaxation=function(relaxation){var eqs=this.equations;for(var i=0;i!==eqs.length;i++){var eq=eqs[i];eq.relaxation=relaxation;eq.needsUpdate=true}}},{"../utils/Utils":56}],15:[function(require,module,exports){var Constraint=require("./Constraint"),Equation=require("../equations/Equation"),vec2=require("../math/vec2"),Utils=require("../utils/Utils");module.exports=DistanceConstraint;function DistanceConstraint(bodyA,bodyB,options){options=Utils.defaults(options,{localAnchorA:[0,0],localAnchorB:[0,0]});Constraint.call(this,bodyA,bodyB,Constraint.DISTANCE,options);this.localAnchorA=vec2.fromValues(options.localAnchorA[0],options.localAnchorA[1]);this.localAnchorB=vec2.fromValues(options.localAnchorB[0],options.localAnchorB[1]);var localAnchorA=this.localAnchorA;var localAnchorB=this.localAnchorB;this.distance=0;if(typeof options.distance==="number"){this.distance=options.distance}else{var worldAnchorA=vec2.create(),worldAnchorB=vec2.create(),r=vec2.create();vec2.rotate(worldAnchorA,localAnchorA,bodyA.angle);vec2.rotate(worldAnchorB,localAnchorB,bodyB.angle);vec2.add(r,bodyB.position,worldAnchorB);vec2.sub(r,r,worldAnchorA);vec2.sub(r,r,bodyA.position);this.distance=vec2.length(r)}var maxForce;if(typeof options.maxForce==="undefined"){maxForce=Number.MAX_VALUE}else{maxForce=options.maxForce}var normal=new Equation(bodyA,bodyB,-maxForce,maxForce);this.equations=[normal];this.maxForce=maxForce;var r=vec2.create();var ri=vec2.create();var rj=vec2.create();var that=this;normal.computeGq=function(){var bodyA=this.bodyA,bodyB=this.bodyB,xi=bodyA.position,xj=bodyB.position;vec2.rotate(ri,localAnchorA,bodyA.angle);vec2.rotate(rj,localAnchorB,bodyB.angle);vec2.add(r,xj,rj);vec2.sub(r,r,ri);vec2.sub(r,r,xi);return vec2.length(r)-that.distance};this.setMaxForce(maxForce);this.upperLimitEnabled=false;this.upperLimit=1;this.lowerLimitEnabled=false;this.lowerLimit=0;this.position=0}DistanceConstraint.prototype=new Constraint;DistanceConstraint.prototype.constructor=DistanceConstraint;var n=vec2.create();var ri=vec2.create();var rj=vec2.create();DistanceConstraint.prototype.update=function(){var normal=this.equations[0],bodyA=this.bodyA,bodyB=this.bodyB,distance=this.distance,xi=bodyA.position,xj=bodyB.position,normalEquation=this.equations[0],G=normal.G;vec2.rotate(ri,this.localAnchorA,bodyA.angle);vec2.rotate(rj,this.localAnchorB,bodyB.angle);vec2.add(n,xj,rj);vec2.sub(n,n,ri);vec2.sub(n,n,xi);this.position=vec2.length(n);var violating=false;if(this.upperLimitEnabled){if(this.position>this.upperLimit){normalEquation.maxForce=0;normalEquation.minForce=-this.maxForce;this.distance=this.upperLimit;violating=true}}if(this.lowerLimitEnabled){if(this.position<this.lowerLimit){normalEquation.maxForce=this.maxForce;normalEquation.minForce=0;this.distance=this.lowerLimit;violating=true}}if((this.lowerLimitEnabled||this.upperLimitEnabled)&&!violating){normalEquation.enabled=false;return}normalEquation.enabled=true;vec2.normalize(n,n);var rixn=vec2.crossLength(ri,n),rjxn=vec2.crossLength(rj,n);G[0]=-n[0];G[1]=-n[1];G[2]=-rixn;G[3]=n[0];G[4]=n[1];G[5]=rjxn};DistanceConstraint.prototype.setMaxForce=function(maxForce){var normal=this.equations[0];normal.minForce=-maxForce;normal.maxForce=maxForce};DistanceConstraint.prototype.getMaxForce=function(){var normal=this.equations[0];return normal.maxForce}},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":56,"./Constraint":14}],16:[function(require,module,exports){var Constraint=require("./Constraint"),Equation=require("../equations/Equation"),AngleLockEquation=require("../equations/AngleLockEquation"),vec2=require("../math/vec2");module.exports=GearConstraint;function GearConstraint(bodyA,bodyB,options){options=options||{};Constraint.call(this,bodyA,bodyB,Constraint.GEAR,options);this.ratio=options.ratio!==undefined?options.ratio:1;this.angle=options.angle!==undefined?options.angle:bodyB.angle-this.ratio*bodyA.angle;options.angle=this.angle;options.ratio=this.ratio;this.equations=[new AngleLockEquation(bodyA,bodyB,options)];if(options.maxTorque!==undefined){this.setMaxTorque(options.maxTorque)}}GearConstraint.prototype=new Constraint;GearConstraint.prototype.constructor=GearConstraint;GearConstraint.prototype.update=function(){var eq=this.equations[0];if(eq.ratio!==this.ratio){eq.setRatio(this.ratio)}eq.angle=this.angle};GearConstraint.prototype.setMaxTorque=function(torque){this.equations[0].setMaxTorque(torque)};GearConstraint.prototype.getMaxTorque=function(torque){return this.equations[0].maxForce}},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(require,module,exports){var Constraint=require("./Constraint"),vec2=require("../math/vec2"),Equation=require("../equations/Equation");module.exports=LockConstraint;function LockConstraint(bodyA,bodyB,options){options=options||{};Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options);var maxForce=typeof options.maxForce==="undefined"?Number.MAX_VALUE:options.maxForce;var localAngleB=options.localAngleB||0;var x=new Equation(bodyA,bodyB,-maxForce,maxForce),y=new Equation(bodyA,bodyB,-maxForce,maxForce),rot=new Equation(bodyA,bodyB,-maxForce,maxForce);var l=vec2.create(),g=vec2.create(),that=this;x.computeGq=function(){vec2.rotate(l,that.localOffsetB,bodyA.angle);vec2.sub(g,bodyB.position,bodyA.position);vec2.sub(g,g,l);return g[0]};y.computeGq=function(){vec2.rotate(l,that.localOffsetB,bodyA.angle);vec2.sub(g,bodyB.position,bodyA.position);vec2.sub(g,g,l);return g[1]};var r=vec2.create(),t=vec2.create();rot.computeGq=function(){vec2.rotate(r,that.localOffsetB,bodyB.angle-that.localAngleB);vec2.scale(r,r,-1);vec2.sub(g,bodyA.position,bodyB.position);vec2.add(g,g,r);vec2.rotate(t,r,-Math.PI/2);vec2.normalize(t,t);return vec2.dot(g,t)};this.localOffsetB=vec2.create();if(options.localOffsetB){vec2.copy(this.localOffsetB,options.localOffsetB)}else{vec2.sub(this.localOffsetB,bodyB.position,bodyA.position);vec2.rotate(this.localOffsetB,this.localOffsetB,-bodyA.angle)}this.localAngleB=0;if(typeof options.localAngleB==="number"){this.localAngleB=options.localAngleB}else{this.localAngleB=bodyB.angle-bodyA.angle}this.equations.push(x,y,rot);this.setMaxForce(maxForce)}LockConstraint.prototype=new Constraint;LockConstraint.prototype.constructor=LockConstraint;LockConstraint.prototype.setMaxForce=function(force){var eqs=this.equations;for(var i=0;i<this.equations.length;i++){eqs[i].maxForce=force;eqs[i].minForce=-force}};LockConstraint.prototype.getMaxForce=function(){return this.equations[0].maxForce};var l=vec2.create();var r=vec2.create();var t=vec2.create();var xAxis=vec2.fromValues(1,0);var yAxis=vec2.fromValues(0,1);LockConstraint.prototype.update=function(){var x=this.equations[0],y=this.equations[1],rot=this.equations[2],bodyA=this.bodyA,bodyB=this.bodyB;vec2.rotate(l,this.localOffsetB,bodyA.angle);vec2.rotate(r,this.localOffsetB,bodyB.angle-this.localAngleB);vec2.scale(r,r,-1);vec2.rotate(t,r,Math.PI/2);vec2.normalize(t,t);x.G[0]=-1;x.G[1]=0;x.G[2]=-vec2.crossLength(l,xAxis);x.G[3]=1;y.G[0]=0;y.G[1]=-1;y.G[2]=-vec2.crossLength(l,yAxis);y.G[4]=1;rot.G[0]=-t[0];rot.G[1]=-t[1];rot.G[3]=t[0];rot.G[4]=t[1];rot.G[5]=vec2.crossLength(r,t)}},{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(require,module,exports){var Constraint=require("./Constraint"),ContactEquation=require("../equations/ContactEquation"),Equation=require("../equations/Equation"),vec2=require("../math/vec2"),RotationalLockEquation=require("../equations/RotationalLockEquation");module.exports=PrismaticConstraint;function PrismaticConstraint(bodyA,bodyB,options){options=options||{};Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options);var localAnchorA=vec2.fromValues(0,0),localAxisA=vec2.fromValues(1,0),localAnchorB=vec2.fromValues(0,0);if(options.localAnchorA){vec2.copy(localAnchorA,options.localAnchorA)}if(options.localAxisA){vec2.copy(localAxisA,options.localAxisA)}if(options.localAnchorB){vec2.copy(localAnchorB,options.localAnchorB)}this.localAnchorA=localAnchorA;this.localAnchorB=localAnchorB;this.localAxisA=localAxisA;var maxForce=this.maxForce=typeof options.maxForce!=="undefined"?options.maxForce:Number.MAX_VALUE;var trans=new Equation(bodyA,bodyB,-maxForce,maxForce);var ri=new vec2.create,rj=new vec2.create,gg=new vec2.create,t=new vec2.create;trans.computeGq=function(){return vec2.dot(gg,t)};trans.updateJacobian=function(){var G=this.G,xi=bodyA.position,xj=bodyB.position;vec2.rotate(ri,localAnchorA,bodyA.angle);vec2.rotate(rj,localAnchorB,bodyB.angle);vec2.add(gg,xj,rj);vec2.sub(gg,gg,xi);vec2.sub(gg,gg,ri);vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2);G[0]=-t[0];G[1]=-t[1];G[2]=-vec2.crossLength(ri,t)+vec2.crossLength(t,gg);G[3]=t[0];G[4]=t[1];G[5]=vec2.crossLength(rj,t)};this.equations.push(trans);if(!options.disableRotationalLock){var rot=new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce);this.equations.push(rot)}this.position=0;this.velocity=0;this.lowerLimitEnabled=typeof options.lowerLimit!=="undefined"?true:false;this.upperLimitEnabled=typeof options.upperLimit!=="undefined"?true:false;this.lowerLimit=typeof options.lowerLimit!=="undefined"?options.lowerLimit:0;this.upperLimit=typeof options.upperLimit!=="undefined"?options.upperLimit:1;this.upperLimitEquation=new ContactEquation(bodyA,bodyB);this.lowerLimitEquation=new ContactEquation(bodyA,bodyB);this.upperLimitEquation.minForce=this.lowerLimitEquation.minForce=0;this.upperLimitEquation.maxForce=this.lowerLimitEquation.maxForce=maxForce;this.motorEquation=new Equation(bodyA,bodyB);this.motorEnabled=false;this.motorSpeed=0;var that=this;var motorEquation=this.motorEquation;var old=motorEquation.computeGW;motorEquation.computeGq=function(){return 0};motorEquation.computeGW=function(){var G=this.G,bi=this.bodyA,bj=this.bodyB,vi=bi.velocity,vj=bj.velocity,wi=bi.angularVelocity,wj=bj.angularVelocity;return this.gmult(G,vi,wi,vj,wj)+that.motorSpeed}}PrismaticConstraint.prototype=new Constraint;PrismaticConstraint.prototype.constructor=PrismaticConstraint;var worldAxisA=vec2.create(),worldAnchorA=vec2.create(),worldAnchorB=vec2.create(),orientedAnchorA=vec2.create(),orientedAnchorB=vec2.create(),tmp=vec2.create();PrismaticConstraint.prototype.update=function(){var eqs=this.equations,trans=eqs[0],upperLimit=this.upperLimit,lowerLimit=this.lowerLimit,upperLimitEquation=this.upperLimitEquation,lowerLimitEquation=this.lowerLimitEquation,bodyA=this.bodyA,bodyB=this.bodyB,localAxisA=this.localAxisA,localAnchorA=this.localAnchorA,localAnchorB=this.localAnchorB;trans.updateJacobian();vec2.rotate(worldAxisA,localAxisA,bodyA.angle);vec2.rotate(orientedAnchorA,localAnchorA,bodyA.angle);vec2.add(worldAnchorA,orientedAnchorA,bodyA.position);vec2.rotate(orientedAnchorB,localAnchorB,bodyB.angle);vec2.add(worldAnchorB,orientedAnchorB,bodyB.position);var relPosition=this.position=vec2.dot(worldAnchorB,worldAxisA)-vec2.dot(worldAnchorA,worldAxisA);if(this.motorEnabled){var G=this.motorEquation.G;G[0]=worldAxisA[0];G[1]=worldAxisA[1];G[2]=vec2.crossLength(worldAxisA,orientedAnchorB);G[3]=-worldAxisA[0];G[4]=-worldAxisA[1];G[5]=-vec2.crossLength(worldAxisA,orientedAnchorA)}if(this.upperLimitEnabled&&relPosition>upperLimit){vec2.scale(upperLimitEquation.normalA,worldAxisA,-1);vec2.sub(upperLimitEquation.contactPointA,worldAnchorA,bodyA.position);vec2.sub(upperLimitEquation.contactPointB,worldAnchorB,bodyB.position);vec2.scale(tmp,worldAxisA,upperLimit);vec2.add(upperLimitEquation.contactPointA,upperLimitEquation.contactPointA,tmp);if(eqs.indexOf(upperLimitEquation)===-1){eqs.push(upperLimitEquation)}}else{var idx=eqs.indexOf(upperLimitEquation);if(idx!==-1){eqs.splice(idx,1)}}if(this.lowerLimitEnabled&&relPosition<lowerLimit){vec2.scale(lowerLimitEquation.normalA,worldAxisA,1);vec2.sub(lowerLimitEquation.contactPointA,worldAnchorA,bodyA.position);vec2.sub(lowerLimitEquation.contactPointB,worldAnchorB,bodyB.position);vec2.scale(tmp,worldAxisA,lowerLimit);vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp);if(eqs.indexOf(lowerLimitEquation)===-1){eqs.push(lowerLimitEquation)}}else{var idx=eqs.indexOf(lowerLimitEquation);if(idx!==-1){eqs.splice(idx,1)}}};PrismaticConstraint.prototype.enableMotor=function(){if(this.motorEnabled){return}this.equations.push(this.motorEquation);this.motorEnabled=true};PrismaticConstraint.prototype.disableMotor=function(){if(!this.motorEnabled){return}var i=this.equations.indexOf(this.motorEquation);this.equations.splice(i,1);this.motorEnabled=false};PrismaticConstraint.prototype.setLimits=function(lower,upper){if(typeof lower==="number"){this.lowerLimit=lower;this.lowerLimitEnabled=true}else{this.lowerLimit=lower;this.lowerLimitEnabled=false}if(typeof upper==="number"){this.upperLimit=upper;this.upperLimitEnabled=true}else{this.upperLimit=upper;this.upperLimitEnabled=false}}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(require,module,exports){var Constraint=require("./Constraint"),Equation=require("../equations/Equation"),RotationalVelocityEquation=require("../equations/RotationalVelocityEquation"),RotationalLockEquation=require("../equations/RotationalLockEquation"),vec2=require("../math/vec2");module.exports=RevoluteConstraint;var worldPivotA=vec2.create(),worldPivotB=vec2.create(),xAxis=vec2.fromValues(1,0),yAxis=vec2.fromValues(0,1),g=vec2.create();function RevoluteConstraint(bodyA,bodyB,options){options=options||{};Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options);var maxForce=this.maxForce=typeof options.maxForce!=="undefined"?options.maxForce:Number.MAX_VALUE;this.pivotA=vec2.create();this.pivotB=vec2.create();if(options.worldPivot){vec2.sub(this.pivotA,options.worldPivot,bodyA.position);vec2.sub(this.pivotB,options.worldPivot,bodyB.position);vec2.rotate(this.pivotA,this.pivotA,-bodyA.angle);vec2.rotate(this.pivotB,this.pivotB,-bodyB.angle)}else{vec2.copy(this.pivotA,options.localPivotA);vec2.copy(this.pivotB,options.localPivotB)}var eqs=this.equations=[new Equation(bodyA,bodyB,-maxForce,maxForce),new Equation(bodyA,bodyB,-maxForce,maxForce)];var x=eqs[0];var y=eqs[1];var that=this;x.computeGq=function(){vec2.rotate(worldPivotA,that.pivotA,bodyA.angle);vec2.rotate(worldPivotB,that.pivotB,bodyB.angle);vec2.add(g,bodyB.position,worldPivotB);vec2.sub(g,g,bodyA.position);vec2.sub(g,g,worldPivotA);return vec2.dot(g,xAxis)};y.computeGq=function(){vec2.rotate(worldPivotA,that.pivotA,bodyA.angle);vec2.rotate(worldPivotB,that.pivotB,bodyB.angle);vec2.add(g,bodyB.position,worldPivotB);vec2.sub(g,g,bodyA.position);vec2.sub(g,g,worldPivotA);return vec2.dot(g,yAxis)};y.minForce=x.minForce=-maxForce;y.maxForce=x.maxForce=maxForce;this.motorEquation=new RotationalVelocityEquation(bodyA,bodyB);this.motorEnabled=false;this.angle=0;this.lowerLimitEnabled=false;this.upperLimitEnabled=false;this.lowerLimit=0;this.upperLimit=0;this.upperLimitEquation=new RotationalLockEquation(bodyA,bodyB);this.lowerLimitEquation=new RotationalLockEquation(bodyA,bodyB);this.upperLimitEquation.minForce=0;this.lowerLimitEquation.maxForce=0}RevoluteConstraint.prototype=new Constraint;RevoluteConstraint.prototype.constructor=RevoluteConstraint;RevoluteConstraint.prototype.setLimits=function(lower,upper){if(typeof lower==="number"){this.lowerLimit=lower;this.lowerLimitEnabled=true}else{this.lowerLimit=lower;this.lowerLimitEnabled=false}if(typeof upper==="number"){this.upperLimit=upper;this.upperLimitEnabled=true}else{this.upperLimit=upper;this.upperLimitEnabled=false}};RevoluteConstraint.prototype.update=function(){var bodyA=this.bodyA,bodyB=this.bodyB,pivotA=this.pivotA,pivotB=this.pivotB,eqs=this.equations,normal=eqs[0],tangent=eqs[1],x=eqs[0],y=eqs[1],upperLimit=this.upperLimit,lowerLimit=this.lowerLimit,upperLimitEquation=this.upperLimitEquation,lowerLimitEquation=this.lowerLimitEquation;var relAngle=this.angle=bodyB.angle-bodyA.angle;if(this.upperLimitEnabled&&relAngle>upperLimit){upperLimitEquation.angle=upperLimit;if(eqs.indexOf(upperLimitEquation)===-1){eqs.push(upperLimitEquation)}}else{var idx=eqs.indexOf(upperLimitEquation);if(idx!==-1){eqs.splice(idx,1)}}if(this.lowerLimitEnabled&&relAngle<lowerLimit){lowerLimitEquation.angle=lowerLimit;if(eqs.indexOf(lowerLimitEquation)===-1){eqs.push(lowerLimitEquation)}}else{var idx=eqs.indexOf(lowerLimitEquation);if(idx!==-1){eqs.splice(idx,1)}}vec2.rotate(worldPivotA,pivotA,bodyA.angle);vec2.rotate(worldPivotB,pivotB,bodyB.angle);x.G[0]=-1;x.G[1]=0;x.G[2]=-vec2.crossLength(worldPivotA,xAxis);x.G[3]=1;x.G[4]=0;x.G[5]=vec2.crossLength(worldPivotB,xAxis);y.G[0]=0;y.G[1]=-1;y.G[2]=-vec2.crossLength(worldPivotA,yAxis);y.G[3]=0;y.G[4]=1;y.G[5]=vec2.crossLength(worldPivotB,yAxis)};RevoluteConstraint.prototype.enableMotor=function(){if(this.motorEnabled){return}this.equations.push(this.motorEquation);this.motorEnabled=true};RevoluteConstraint.prototype.disableMotor=function(){if(!this.motorEnabled){return}var i=this.equations.indexOf(this.motorEquation);this.equations.splice(i,1);this.motorEnabled=false};RevoluteConstraint.prototype.motorIsEnabled=function(){return!!this.motorEnabled};RevoluteConstraint.prototype.setMotorSpeed=function(speed){if(!this.motorEnabled){return}var i=this.equations.indexOf(this.motorEquation);this.equations[i].relativeVelocity=speed};RevoluteConstraint.prototype.getMotorSpeed=function(){if(!this.motorEnabled){return false}return this.motorEquation.relativeVelocity}},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(require,module,exports){var Equation=require("./Equation"),vec2=require("../math/vec2");module.exports=AngleLockEquation;function AngleLockEquation(bodyA,bodyB,options){options=options||{};Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE);this.angle=options.angle||0;this.ratio=typeof options.ratio==="number"?options.ratio:1;this.setRatio(this.ratio)}AngleLockEquation.prototype=new Equation;AngleLockEquation.prototype.constructor=AngleLockEquation;AngleLockEquation.prototype.computeGq=function(){return this.ratio*this.bodyA.angle-this.bodyB.angle+this.angle};AngleLockEquation.prototype.setRatio=function(ratio){var G=this.G;G[2]=ratio;G[5]=-1;this.ratio=ratio};AngleLockEquation.prototype.setMaxTorque=function(torque){this.maxForce=torque;this.minForce=-torque}},{"../math/vec2":30,"./Equation":22}],21:[function(require,module,exports){var Equation=require("./Equation"),vec2=require("../math/vec2");module.exports=ContactEquation;function ContactEquation(bodyA,bodyB){Equation.call(this,bodyA,bodyB,0,Number.MAX_VALUE);this.contactPointA=vec2.create();this.penetrationVec=vec2.create();this.contactPointB=vec2.create();this.normalA=vec2.create();this.restitution=0;this.firstImpact=false;this.shapeA=null;this.shapeB=null}ContactEquation.prototype=new Equation;ContactEquation.prototype.constructor=ContactEquation;ContactEquation.prototype.computeB=function(a,b,h){var bi=this.bodyA,bj=this.bodyB,ri=this.contactPointA,rj=this.contactPointB,xi=bi.position,xj=bj.position;var penetrationVec=this.penetrationVec,n=this.normalA,G=this.G;var rixn=vec2.crossLength(ri,n),rjxn=vec2.crossLength(rj,n);G[0]=-n[0];G[1]=-n[1];G[2]=-rixn;G[3]=n[0];G[4]=n[1];G[5]=rjxn;vec2.add(penetrationVec,xj,rj);vec2.sub(penetrationVec,penetrationVec,xi);vec2.sub(penetrationVec,penetrationVec,ri);var GW,Gq;if(this.firstImpact&&this.restitution!==0){Gq=0;GW=1/b*(1+this.restitution)*this.computeGW()}else{Gq=vec2.dot(n,penetrationVec)+this.offset;GW=this.computeGW()}var GiMf=this.computeGiMf();var B=-Gq*a-GW*b-h*GiMf;return B};var vi=vec2.create();var vj=vec2.create();var relVel=vec2.create();ContactEquation.prototype.getVelocityAlongNormal=function(){this.bodyA.getVelocityAtPoint(vi,this.contactPointA);this.bodyB.getVelocityAtPoint(vj,this.contactPointB);vec2.subtract(relVel,vi,vj);return vec2.dot(this.normalA,relVel)}},{"../math/vec2":30,"./Equation":22}],22:[function(require,module,exports){ | |
module.exports=Equation;var vec2=require("../math/vec2"),Utils=require("../utils/Utils"),Body=require("../objects/Body");function Equation(bodyA,bodyB,minForce,maxForce){this.minForce=typeof minForce==="undefined"?-Number.MAX_VALUE:minForce;this.maxForce=typeof maxForce==="undefined"?Number.MAX_VALUE:maxForce;this.bodyA=bodyA;this.bodyB=bodyB;this.stiffness=Equation.DEFAULT_STIFFNESS;this.relaxation=Equation.DEFAULT_RELAXATION;this.G=new Utils.ARRAY_TYPE(6);for(var i=0;i<6;i++){this.G[i]=0}this.offset=0;this.a=0;this.b=0;this.epsilon=0;this.timeStep=1/60;this.needsUpdate=true;this.multiplier=0;this.relativeVelocity=0;this.enabled=true}Equation.prototype.constructor=Equation;Equation.DEFAULT_STIFFNESS=1e6;Equation.DEFAULT_RELAXATION=4;Equation.prototype.update=function(){var k=this.stiffness,d=this.relaxation,h=this.timeStep;this.a=4/(h*(1+4*d));this.b=4*d/(1+4*d);this.epsilon=4/(h*h*k*(1+4*d));this.needsUpdate=false};Equation.prototype.gmult=function(G,vi,wi,vj,wj){return G[0]*vi[0]+G[1]*vi[1]+G[2]*wi+G[3]*vj[0]+G[4]*vj[1]+G[5]*wj};Equation.prototype.computeB=function(a,b,h){var GW=this.computeGW();var Gq=this.computeGq();var GiMf=this.computeGiMf();return-Gq*a-GW*b-GiMf*h};var qi=vec2.create(),qj=vec2.create();Equation.prototype.computeGq=function(){var G=this.G,bi=this.bodyA,bj=this.bodyB,xi=bi.position,xj=bj.position,ai=bi.angle,aj=bj.angle;return this.gmult(G,qi,ai,qj,aj)+this.offset};Equation.prototype.computeGW=function(){var G=this.G,bi=this.bodyA,bj=this.bodyB,vi=bi.velocity,vj=bj.velocity,wi=bi.angularVelocity,wj=bj.angularVelocity;return this.gmult(G,vi,wi,vj,wj)+this.relativeVelocity};Equation.prototype.computeGWlambda=function(){var G=this.G,bi=this.bodyA,bj=this.bodyB,vi=bi.vlambda,vj=bj.vlambda,wi=bi.wlambda,wj=bj.wlambda;return this.gmult(G,vi,wi,vj,wj)};var iMfi=vec2.create(),iMfj=vec2.create();Equation.prototype.computeGiMf=function(){var bi=this.bodyA,bj=this.bodyB,fi=bi.force,ti=bi.angularForce,fj=bj.force,tj=bj.angularForce,invMassi=bi.invMassSolve,invMassj=bj.invMassSolve,invIi=bi.invInertiaSolve,invIj=bj.invInertiaSolve,G=this.G;vec2.scale(iMfi,fi,invMassi);vec2.multiply(iMfi,bi.massMultiplier,iMfi);vec2.scale(iMfj,fj,invMassj);vec2.multiply(iMfj,bj.massMultiplier,iMfj);return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj)};Equation.prototype.computeGiMGt=function(){var bi=this.bodyA,bj=this.bodyB,invMassi=bi.invMassSolve,invMassj=bj.invMassSolve,invIi=bi.invInertiaSolve,invIj=bj.invInertiaSolve,G=this.G;return G[0]*G[0]*invMassi*bi.massMultiplier[0]+G[1]*G[1]*invMassi*bi.massMultiplier[1]+G[2]*G[2]*invIi+G[3]*G[3]*invMassj*bj.massMultiplier[0]+G[4]*G[4]*invMassj*bj.massMultiplier[1]+G[5]*G[5]*invIj};var addToWlambda_temp=vec2.create(),addToWlambda_Gi=vec2.create(),addToWlambda_Gj=vec2.create(),addToWlambda_ri=vec2.create(),addToWlambda_rj=vec2.create(),addToWlambda_Mdiag=vec2.create();Equation.prototype.addToWlambda=function(deltalambda){var bi=this.bodyA,bj=this.bodyB,temp=addToWlambda_temp,Gi=addToWlambda_Gi,Gj=addToWlambda_Gj,ri=addToWlambda_ri,rj=addToWlambda_rj,invMassi=bi.invMassSolve,invMassj=bj.invMassSolve,invIi=bi.invInertiaSolve,invIj=bj.invInertiaSolve,Mdiag=addToWlambda_Mdiag,G=this.G;Gi[0]=G[0];Gi[1]=G[1];Gj[0]=G[3];Gj[1]=G[4];vec2.scale(temp,Gi,invMassi*deltalambda);vec2.multiply(temp,temp,bi.massMultiplier);vec2.add(bi.vlambda,bi.vlambda,temp);bi.wlambda+=invIi*G[2]*deltalambda;vec2.scale(temp,Gj,invMassj*deltalambda);vec2.multiply(temp,temp,bj.massMultiplier);vec2.add(bj.vlambda,bj.vlambda,temp);bj.wlambda+=invIj*G[5]*deltalambda};Equation.prototype.computeInvC=function(eps){return 1/(this.computeGiMGt()+eps)}},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":56}],23:[function(require,module,exports){var vec2=require("../math/vec2"),Equation=require("./Equation"),Utils=require("../utils/Utils");module.exports=FrictionEquation;function FrictionEquation(bodyA,bodyB,slipForce){Equation.call(this,bodyA,bodyB,-slipForce,slipForce);this.contactPointA=vec2.create();this.contactPointB=vec2.create();this.t=vec2.create();this.contactEquations=[];this.shapeA=null;this.shapeB=null;this.frictionCoefficient=.3}FrictionEquation.prototype=new Equation;FrictionEquation.prototype.constructor=FrictionEquation;FrictionEquation.prototype.setSlipForce=function(slipForce){this.maxForce=slipForce;this.minForce=-slipForce};FrictionEquation.prototype.getSlipForce=function(){return this.maxForce};FrictionEquation.prototype.computeB=function(a,b,h){var bi=this.bodyA,bj=this.bodyB,ri=this.contactPointA,rj=this.contactPointB,t=this.t,G=this.G;G[0]=-t[0];G[1]=-t[1];G[2]=-vec2.crossLength(ri,t);G[3]=t[0];G[4]=t[1];G[5]=vec2.crossLength(rj,t);var GW=this.computeGW(),GiMf=this.computeGiMf();var B=-GW*b-h*GiMf;return B}},{"../math/vec2":30,"../utils/Utils":56,"./Equation":22}],24:[function(require,module,exports){var Equation=require("./Equation"),vec2=require("../math/vec2");module.exports=RotationalLockEquation;function RotationalLockEquation(bodyA,bodyB,options){options=options||{};Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE);this.angle=options.angle||0;var G=this.G;G[2]=1;G[5]=-1}RotationalLockEquation.prototype=new Equation;RotationalLockEquation.prototype.constructor=RotationalLockEquation;var worldVectorA=vec2.create(),worldVectorB=vec2.create(),xAxis=vec2.fromValues(1,0),yAxis=vec2.fromValues(0,1);RotationalLockEquation.prototype.computeGq=function(){vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle);vec2.rotate(worldVectorB,yAxis,this.bodyB.angle);return vec2.dot(worldVectorA,worldVectorB)}},{"../math/vec2":30,"./Equation":22}],25:[function(require,module,exports){var Equation=require("./Equation"),vec2=require("../math/vec2");module.exports=RotationalVelocityEquation;function RotationalVelocityEquation(bodyA,bodyB){Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE);this.relativeVelocity=1;this.ratio=1}RotationalVelocityEquation.prototype=new Equation;RotationalVelocityEquation.prototype.constructor=RotationalVelocityEquation;RotationalVelocityEquation.prototype.computeB=function(a,b,h){var G=this.G;G[2]=-1;G[5]=this.ratio;var GiMf=this.computeGiMf();var GW=this.computeGW();var B=-GW*b-h*GiMf;return B}},{"../math/vec2":30,"./Equation":22}],26:[function(require,module,exports){var EventEmitter=function(){};module.exports=EventEmitter;EventEmitter.prototype={constructor:EventEmitter,on:function(type,listener,context){listener.context=context||this;if(this._listeners===undefined){this._listeners={}}var listeners=this._listeners;if(listeners[type]===undefined){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}return this},has:function(type,listener){if(this._listeners===undefined){return false}var listeners=this._listeners;if(listener){if(listeners[type]!==undefined&&listeners[type].indexOf(listener)!==-1){return true}}else{if(listeners[type]!==undefined){return true}}return false},off:function(type,listener){if(this._listeners===undefined){return this}var listeners=this._listeners;var index=listeners[type].indexOf(listener);if(index!==-1){listeners[type].splice(index,1)}return this},emit:function(event){if(this._listeners===undefined){return this}var listeners=this._listeners;var listenerArray=listeners[event.type];if(listenerArray!==undefined){event.target=this;for(var i=0,l=listenerArray.length;i<l;i++){var listener=listenerArray[i];listener.call(listener.context,event)}}return this}}},{}],27:[function(require,module,exports){var Material=require("./Material");var Equation=require("../equations/Equation");module.exports=ContactMaterial;function ContactMaterial(materialA,materialB,options){options=options||{};if(!(materialA instanceof Material)||!(materialB instanceof Material)){throw new Error("First two arguments must be Material instances.")}this.id=ContactMaterial.idCounter++;this.materialA=materialA;this.materialB=materialB;this.friction=typeof options.friction!=="undefined"?Number(options.friction):.3;this.restitution=typeof options.restitution!=="undefined"?Number(options.restitution):0;this.stiffness=typeof options.stiffness!=="undefined"?Number(options.stiffness):Equation.DEFAULT_STIFFNESS;this.relaxation=typeof options.relaxation!=="undefined"?Number(options.relaxation):Equation.DEFAULT_RELAXATION;this.frictionStiffness=typeof options.frictionStiffness!=="undefined"?Number(options.frictionStiffness):Equation.DEFAULT_STIFFNESS;this.frictionRelaxation=typeof options.frictionRelaxation!=="undefined"?Number(options.frictionRelaxation):Equation.DEFAULT_RELAXATION;this.surfaceVelocity=typeof options.surfaceVelocity!=="undefined"?Number(options.surfaceVelocity):0;this.contactSkinSize=.005}ContactMaterial.idCounter=0},{"../equations/Equation":22,"./Material":28}],28:[function(require,module,exports){module.exports=Material;function Material(id){this.id=id||Material.idCounter++}Material.idCounter=0},{}],29:[function(require,module,exports){var PolyK={};PolyK.GetArea=function(p){if(p.length<6)return 0;var l=p.length-2;var sum=0;for(var i=0;i<l;i+=2)sum+=(p[i+2]-p[i])*(p[i+1]+p[i+3]);sum+=(p[0]-p[l])*(p[l+1]+p[1]);return-sum*.5};PolyK.Triangulate=function(p){var n=p.length>>1;if(n<3)return[];var tgs=[];var avl=[];for(var i=0;i<n;i++)avl.push(i);var i=0;var al=n;while(al>3){var i0=avl[(i+0)%al];var i1=avl[(i+1)%al];var i2=avl[(i+2)%al];var ax=p[2*i0],ay=p[2*i0+1];var bx=p[2*i1],by=p[2*i1+1];var cx=p[2*i2],cy=p[2*i2+1];var earFound=false;if(PolyK._convex(ax,ay,bx,by,cx,cy)){earFound=true;for(var j=0;j<al;j++){var vi=avl[j];if(vi==i0||vi==i1||vi==i2)continue;if(PolyK._PointInTriangle(p[2*vi],p[2*vi+1],ax,ay,bx,by,cx,cy)){earFound=false;break}}}if(earFound){tgs.push(i0,i1,i2);avl.splice((i+1)%al,1);al--;i=0}else if(i++>3*al)break}tgs.push(avl[0],avl[1],avl[2]);return tgs};PolyK._PointInTriangle=function(px,py,ax,ay,bx,by,cx,cy){var v0x=cx-ax;var v0y=cy-ay;var v1x=bx-ax;var v1y=by-ay;var v2x=px-ax;var v2y=py-ay;var dot00=v0x*v0x+v0y*v0y;var dot01=v0x*v1x+v0y*v1y;var dot02=v0x*v2x+v0y*v2y;var dot11=v1x*v1x+v1y*v1y;var dot12=v1x*v2x+v1y*v2y;var invDenom=1/(dot00*dot11-dot01*dot01);var u=(dot11*dot02-dot01*dot12)*invDenom;var v=(dot00*dot12-dot01*dot02)*invDenom;return u>=0&&v>=0&&u+v<1};PolyK._convex=function(ax,ay,bx,by,cx,cy){return(ay-by)*(cx-bx)+(bx-ax)*(cy-by)>=0};module.exports=PolyK},{}],30:[function(require,module,exports){var vec2=module.exports={};var Utils=require("../utils/Utils");vec2.crossLength=function(a,b){return a[0]*b[1]-a[1]*b[0]};vec2.crossVZ=function(out,vec,zcomp){vec2.rotate(out,vec,-Math.PI/2);vec2.scale(out,out,zcomp);return out};vec2.crossZV=function(out,zcomp,vec){vec2.rotate(out,vec,Math.PI/2);vec2.scale(out,out,zcomp);return out};vec2.rotate=function(out,a,angle){if(angle!==0){var c=Math.cos(angle),s=Math.sin(angle),x=a[0],y=a[1];out[0]=c*x-s*y;out[1]=s*x+c*y}else{out[0]=a[0];out[1]=a[1]}};vec2.rotate90cw=function(out,a){var x=a[0];var y=a[1];out[0]=y;out[1]=-x};vec2.toLocalFrame=function(out,worldPoint,framePosition,frameAngle){vec2.copy(out,worldPoint);vec2.sub(out,out,framePosition);vec2.rotate(out,out,-frameAngle)};vec2.toGlobalFrame=function(out,localPoint,framePosition,frameAngle){vec2.copy(out,localPoint);vec2.rotate(out,out,frameAngle);vec2.add(out,out,framePosition)};vec2.vectorToLocalFrame=function(out,worldVector,frameAngle){vec2.rotate(out,worldVector,-frameAngle)};vec2.vectorToGlobalFrame=function(out,localVector,frameAngle){vec2.rotate(out,localVector,frameAngle)};vec2.centroid=function(out,a,b,c){vec2.add(out,a,b);vec2.add(out,out,c);vec2.scale(out,out,1/3);return out};vec2.create=function(){var out=new Utils.ARRAY_TYPE(2);out[0]=0;out[1]=0;return out};vec2.clone=function(a){var out=new Utils.ARRAY_TYPE(2);out[0]=a[0];out[1]=a[1];return out};vec2.fromValues=function(x,y){var out=new Utils.ARRAY_TYPE(2);out[0]=x;out[1]=y;return out};vec2.copy=function(out,a){out[0]=a[0];out[1]=a[1];return out};vec2.set=function(out,x,y){out[0]=x;out[1]=y;return out};vec2.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];return out};vec2.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];return out};vec2.sub=vec2.subtract;vec2.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];return out};vec2.mul=vec2.multiply;vec2.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];return out};vec2.div=vec2.divide;vec2.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;return out};vec2.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)};vec2.dist=vec2.distance;vec2.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y};vec2.sqrDist=vec2.squaredDistance;vec2.length=function(a){var x=a[0],y=a[1];return Math.sqrt(x*x+y*y)};vec2.len=vec2.length;vec2.squaredLength=function(a){var x=a[0],y=a[1];return x*x+y*y};vec2.sqrLen=vec2.squaredLength;vec2.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];return out};vec2.normalize=function(out,a){var x=a[0],y=a[1];var len=x*x+y*y;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len}return out};vec2.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]};vec2.str=function(a){return"vec2("+a[0]+", "+a[1]+")"};vec2.lerp=function(out,a,b,t){var ax=a[0],ay=a[1];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);return out};vec2.reflect=function(out,vector,normal){var dot=vector[0]*normal[0]+vector[1]*normal[1];out[0]=vector[0]-2*normal[0]*dot;out[1]=vector[1]-2*normal[1]*dot};vec2.getLineSegmentsIntersection=function(out,p0,p1,p2,p3){var t=vec2.getLineSegmentsIntersectionFraction(p0,p1,p2,p3);if(t<0){return false}else{out[0]=p0[0]+t*(p1[0]-p0[0]);out[1]=p0[1]+t*(p1[1]-p0[1]);return true}};vec2.getLineSegmentsIntersectionFraction=function(p0,p1,p2,p3){var s1_x=p1[0]-p0[0];var s1_y=p1[1]-p0[1];var s2_x=p3[0]-p2[0];var s2_y=p3[1]-p2[1];var s,t;s=(-s1_y*(p0[0]-p2[0])+s1_x*(p0[1]-p2[1]))/(-s2_x*s1_y+s1_x*s2_y);t=(s2_x*(p0[1]-p2[1])-s2_y*(p0[0]-p2[0]))/(-s2_x*s1_y+s1_x*s2_y);if(s>=0&&s<=1&&t>=0&&t<=1){return t}return-1}},{"../utils/Utils":56}],31:[function(require,module,exports){var vec2=require("../math/vec2"),decomp=require("poly-decomp"),Convex=require("../shapes/Convex"),RaycastResult=require("../collision/RaycastResult"),Ray=require("../collision/Ray"),AABB=require("../collision/AABB"),EventEmitter=require("../events/EventEmitter");module.exports=Body;function Body(options){options=options||{};EventEmitter.call(this);this.id=options.id||++Body._idCounter;this.world=null;this.shapes=[];this.mass=options.mass||0;this.invMass=0;this.inertia=0;this.invInertia=0;this.invMassSolve=0;this.invInertiaSolve=0;this.fixedRotation=!!options.fixedRotation;this.fixedX=!!options.fixedX;this.fixedY=!!options.fixedY;this.massMultiplier=vec2.create();this.position=vec2.fromValues(0,0);if(options.position){vec2.copy(this.position,options.position)}this.interpolatedPosition=vec2.fromValues(0,0);this.interpolatedAngle=0;this.previousPosition=vec2.fromValues(0,0);this.previousAngle=0;this.velocity=vec2.fromValues(0,0);if(options.velocity){vec2.copy(this.velocity,options.velocity)}this.vlambda=vec2.fromValues(0,0);this.wlambda=0;this.angle=options.angle||0;this.angularVelocity=options.angularVelocity||0;this.force=vec2.create();if(options.force){vec2.copy(this.force,options.force)}this.angularForce=options.angularForce||0;this.damping=typeof options.damping==="number"?options.damping:.1;this.angularDamping=typeof options.angularDamping==="number"?options.angularDamping:.1;this.type=Body.STATIC;if(typeof options.type!=="undefined"){this.type=options.type}else if(!options.mass){this.type=Body.STATIC}else{this.type=Body.DYNAMIC}this.boundingRadius=0;this.aabb=new AABB;this.aabbNeedsUpdate=true;this.allowSleep=options.allowSleep!==undefined?options.allowSleep:true;this.wantsToSleep=false;this.sleepState=Body.AWAKE;this.sleepSpeedLimit=options.sleepSpeedLimit!==undefined?options.sleepSpeedLimit:.2;this.sleepTimeLimit=options.sleepTimeLimit!==undefined?options.sleepTimeLimit:1;this.gravityScale=options.gravityScale!==undefined?options.gravityScale:1;this.collisionResponse=options.collisionResponse!==undefined?options.collisionResponse:true;this.idleTime=0;this.timeLastSleepy=0;this.ccdSpeedThreshold=options.ccdSpeedThreshold!==undefined?options.ccdSpeedThreshold:-1;this.ccdIterations=options.ccdIterations!==undefined?options.ccdIterations:10;this.concavePath=null;this._wakeUpAfterNarrowphase=false;this.updateMassProperties()}Body.prototype=new EventEmitter;Body.prototype.constructor=Body;Body._idCounter=0;Body.prototype.updateSolveMassProperties=function(){if(this.sleepState===Body.SLEEPING||this.type===Body.KINEMATIC){this.invMassSolve=0;this.invInertiaSolve=0}else{this.invMassSolve=this.invMass;this.invInertiaSolve=this.invInertia}};Body.prototype.setDensity=function(density){var totalArea=this.getArea();this.mass=totalArea*density;this.updateMassProperties()};Body.prototype.getArea=function(){var totalArea=0;for(var i=0;i<this.shapes.length;i++){totalArea+=this.shapes[i].area}return totalArea};Body.prototype.getAABB=function(){if(this.aabbNeedsUpdate){this.updateAABB()}return this.aabb};var shapeAABB=new AABB,tmp=vec2.create();Body.prototype.updateAABB=function(){var shapes=this.shapes,N=shapes.length,offset=tmp,bodyAngle=this.angle;for(var i=0;i!==N;i++){var shape=shapes[i],angle=shape.angle+bodyAngle;vec2.rotate(offset,shape.position,bodyAngle);vec2.add(offset,offset,this.position);shape.computeAABB(shapeAABB,offset,angle);if(i===0){this.aabb.copy(shapeAABB)}else{this.aabb.extend(shapeAABB)}}this.aabbNeedsUpdate=false};Body.prototype.updateBoundingRadius=function(){var shapes=this.shapes,N=shapes.length,radius=0;for(var i=0;i!==N;i++){var shape=shapes[i],offset=vec2.length(shape.position),r=shape.boundingRadius;if(offset+r>radius){radius=offset+r}}this.boundingRadius=radius};Body.prototype.addShape=function(shape,offset,angle){if(shape.body){throw new Error("A shape can only be added to one body.")}shape.body=this;if(offset){vec2.copy(shape.position,offset)}else{vec2.set(shape.position,0,0)}shape.angle=angle||0;this.shapes.push(shape);this.updateMassProperties();this.updateBoundingRadius();this.aabbNeedsUpdate=true};Body.prototype.removeShape=function(shape){var idx=this.shapes.indexOf(shape);if(idx!==-1){this.shapes.splice(idx,1);this.aabbNeedsUpdate=true;shape.body=null;return true}else{return false}};Body.prototype.updateMassProperties=function(){if(this.type===Body.STATIC||this.type===Body.KINEMATIC){this.mass=Number.MAX_VALUE;this.invMass=0;this.inertia=Number.MAX_VALUE;this.invInertia=0}else{var shapes=this.shapes,N=shapes.length,m=this.mass/N,I=0;if(!this.fixedRotation){for(var i=0;i<N;i++){var shape=shapes[i],r2=vec2.squaredLength(shape.position),Icm=shape.computeMomentOfInertia(m);I+=Icm+m*r2}this.inertia=I;this.invInertia=I>0?1/I:0}else{this.inertia=Number.MAX_VALUE;this.invInertia=0}this.invMass=1/this.mass;vec2.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};var Body_applyForce_r=vec2.create();Body.prototype.applyForce=function(force,relativePoint){vec2.add(this.force,this.force,force);if(relativePoint){var rotForce=vec2.crossLength(relativePoint,force);this.angularForce+=rotForce}};var Body_applyForce_forceWorld=vec2.create();var Body_applyForce_pointWorld=vec2.create();var Body_applyForce_pointLocal=vec2.create();Body.prototype.applyForceLocal=function(localForce,localPoint){localPoint=localPoint||Body_applyForce_pointLocal;var worldForce=Body_applyForce_forceWorld;var worldPoint=Body_applyForce_pointWorld;this.vectorToWorldFrame(worldForce,localForce);this.vectorToWorldFrame(worldPoint,localPoint);this.applyForce(worldForce,worldPoint)};var Body_applyImpulse_velo=vec2.create();Body.prototype.applyImpulse=function(impulseVector,relativePoint){if(this.type!==Body.DYNAMIC){return}var velo=Body_applyImpulse_velo;vec2.scale(velo,impulseVector,this.invMass);vec2.multiply(velo,this.massMultiplier,velo);vec2.add(this.velocity,velo,this.velocity);if(relativePoint){var rotVelo=vec2.crossLength(relativePoint,impulseVector);rotVelo*=this.invInertia;this.angularVelocity+=rotVelo}};var Body_applyImpulse_impulseWorld=vec2.create();var Body_applyImpulse_pointWorld=vec2.create();var Body_applyImpulse_pointLocal=vec2.create();Body.prototype.applyImpulseLocal=function(localImpulse,localPoint){localPoint=localPoint||Body_applyImpulse_pointLocal;var worldImpulse=Body_applyImpulse_impulseWorld;var worldPoint=Body_applyImpulse_pointWorld;this.vectorToWorldFrame(worldImpulse,localImpulse);this.vectorToWorldFrame(worldPoint,localPoint);this.applyImpulse(worldImpulse,worldPoint)};Body.prototype.toLocalFrame=function(out,worldPoint){vec2.toLocalFrame(out,worldPoint,this.position,this.angle)};Body.prototype.toWorldFrame=function(out,localPoint){vec2.toGlobalFrame(out,localPoint,this.position,this.angle)};Body.prototype.vectorToLocalFrame=function(out,worldVector){vec2.vectorToLocalFrame(out,worldVector,this.angle)};Body.prototype.vectorToWorldFrame=function(out,localVector){vec2.vectorToGlobalFrame(out,localVector,this.angle)};Body.prototype.fromPolygon=function(path,options){options=options||{};for(var i=this.shapes.length;i>=0;--i){this.removeShape(this.shapes[i])}var p=new decomp.Polygon;p.vertices=path;p.makeCCW();if(typeof options.removeCollinearPoints==="number"){p.removeCollinearPoints(options.removeCollinearPoints)}if(typeof options.skipSimpleCheck==="undefined"){if(!p.isSimple()){return false}}this.concavePath=p.vertices.slice(0);for(var i=0;i<this.concavePath.length;i++){var v=[0,0];vec2.copy(v,this.concavePath[i]);this.concavePath[i]=v}var convexes;if(options.optimalDecomp){convexes=p.decomp()}else{convexes=p.quickDecomp()}var cm=vec2.create();for(var i=0;i!==convexes.length;i++){var c=new Convex({vertices:convexes[i].vertices});for(var j=0;j!==c.vertices.length;j++){var v=c.vertices[j];vec2.sub(v,v,c.centerOfMass)}vec2.scale(cm,c.centerOfMass,1);c.updateTriangles();c.updateCenterOfMass();c.updateBoundingRadius();this.addShape(c,cm)}this.adjustCenterOfMass();this.aabbNeedsUpdate=true;return true};var adjustCenterOfMass_tmp1=vec2.fromValues(0,0),adjustCenterOfMass_tmp2=vec2.fromValues(0,0),adjustCenterOfMass_tmp3=vec2.fromValues(0,0),adjustCenterOfMass_tmp4=vec2.fromValues(0,0);Body.prototype.adjustCenterOfMass=function(){var offset_times_area=adjustCenterOfMass_tmp2,sum=adjustCenterOfMass_tmp3,cm=adjustCenterOfMass_tmp4,totalArea=0;vec2.set(sum,0,0);for(var i=0;i!==this.shapes.length;i++){var s=this.shapes[i];vec2.scale(offset_times_area,s.position,s.area);vec2.add(sum,sum,offset_times_area);totalArea+=s.area}vec2.scale(cm,sum,1/totalArea);for(var i=0;i!==this.shapes.length;i++){var s=this.shapes[i];vec2.sub(s.position,s.position,cm)}vec2.add(this.position,this.position,cm);for(var i=0;this.concavePath&&i<this.concavePath.length;i++){vec2.sub(this.concavePath[i],this.concavePath[i],cm)}this.updateMassProperties();this.updateBoundingRadius()};Body.prototype.setZeroForce=function(){vec2.set(this.force,0,0);this.angularForce=0};Body.prototype.resetConstraintVelocity=function(){var b=this,vlambda=b.vlambda;vec2.set(vlambda,0,0);b.wlambda=0};Body.prototype.addConstraintVelocity=function(){var b=this,v=b.velocity;vec2.add(v,v,b.vlambda);b.angularVelocity+=b.wlambda};Body.prototype.applyDamping=function(dt){if(this.type===Body.DYNAMIC){var v=this.velocity;vec2.scale(v,v,Math.pow(1-this.damping,dt));this.angularVelocity*=Math.pow(1-this.angularDamping,dt)}};Body.prototype.wakeUp=function(){var s=this.sleepState;this.sleepState=Body.AWAKE;this.idleTime=0;if(s!==Body.AWAKE){this.emit(Body.wakeUpEvent)}};Body.prototype.sleep=function(){this.sleepState=Body.SLEEPING;this.angularVelocity=0;this.angularForce=0;vec2.set(this.velocity,0,0);vec2.set(this.force,0,0);this.emit(Body.sleepEvent)};Body.prototype.sleepTick=function(time,dontSleep,dt){if(!this.allowSleep||this.type===Body.SLEEPING){return}this.wantsToSleep=false;var sleepState=this.sleepState,speedSquared=vec2.squaredLength(this.velocity)+Math.pow(this.angularVelocity,2),speedLimitSquared=Math.pow(this.sleepSpeedLimit,2);if(speedSquared>=speedLimitSquared){this.idleTime=0;this.sleepState=Body.AWAKE}else{this.idleTime+=dt;this.sleepState=Body.SLEEPY}if(this.idleTime>this.sleepTimeLimit){if(!dontSleep){this.sleep()}else{this.wantsToSleep=true}}};Body.prototype.overlaps=function(body){return this.world.overlapKeeper.bodiesAreOverlapping(this,body)};var integrate_fhMinv=vec2.create();var integrate_velodt=vec2.create();Body.prototype.integrate=function(dt){var minv=this.invMass,f=this.force,pos=this.position,velo=this.velocity;vec2.copy(this.previousPosition,this.position);this.previousAngle=this.angle;if(!this.fixedRotation){this.angularVelocity+=this.angularForce*this.invInertia*dt}vec2.scale(integrate_fhMinv,f,dt*minv);vec2.multiply(integrate_fhMinv,this.massMultiplier,integrate_fhMinv);vec2.add(velo,integrate_fhMinv,velo);if(!this.integrateToTimeOfImpact(dt)){vec2.scale(integrate_velodt,velo,dt);vec2.add(pos,pos,integrate_velodt);if(!this.fixedRotation){this.angle+=this.angularVelocity*dt}}this.aabbNeedsUpdate=true};var result=new RaycastResult;var ray=new Ray({mode:Ray.ALL});var direction=vec2.create();var end=vec2.create();var startToEnd=vec2.create();var rememberPosition=vec2.create();Body.prototype.integrateToTimeOfImpact=function(dt){if(this.ccdSpeedThreshold<0||vec2.squaredLength(this.velocity)<Math.pow(this.ccdSpeedThreshold,2)){return false}vec2.normalize(direction,this.velocity);vec2.scale(end,this.velocity,dt);vec2.add(end,end,this.position);vec2.sub(startToEnd,end,this.position);var startToEndAngle=this.angularVelocity*dt;var len=vec2.length(startToEnd);var timeOfImpact=1;var hit;var that=this;result.reset();ray.callback=function(result){if(result.body===that){return}hit=result.body;result.getHitPoint(end,ray);vec2.sub(startToEnd,end,that.position);timeOfImpact=vec2.length(startToEnd)/len;result.stop()};vec2.copy(ray.from,this.position);vec2.copy(ray.to,end);ray.update();this.world.raycast(result,ray);if(!hit){return false}var rememberAngle=this.angle;vec2.copy(rememberPosition,this.position);var iter=0;var tmin=0;var tmid=0;var tmax=timeOfImpact;while(tmax>=tmin&&iter<this.ccdIterations){iter++;tmid=(tmax-tmin)/2;vec2.scale(integrate_velodt,startToEnd,timeOfImpact);vec2.add(this.position,rememberPosition,integrate_velodt);this.angle=rememberAngle+startToEndAngle*timeOfImpact;this.updateAABB();var overlaps=this.aabb.overlaps(hit.aabb)&&this.world.narrowphase.bodiesOverlap(this,hit);if(overlaps){tmin=tmid}else{tmax=tmid}}timeOfImpact=tmid;vec2.copy(this.position,rememberPosition);this.angle=rememberAngle;vec2.scale(integrate_velodt,startToEnd,timeOfImpact);vec2.add(this.position,this.position,integrate_velodt);if(!this.fixedRotation){this.angle+=startToEndAngle*timeOfImpact}return true};Body.prototype.getVelocityAtPoint=function(result,relativePoint){vec2.crossVZ(result,relativePoint,this.angularVelocity);vec2.subtract(result,this.velocity,result);return result};Body.sleepyEvent={type:"sleepy"};Body.sleepEvent={type:"sleep"};Body.wakeUpEvent={type:"wakeup"};Body.DYNAMIC=1;Body.STATIC=2;Body.KINEMATIC=4;Body.AWAKE=0;Body.SLEEPY=1;Body.SLEEPING=2},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":39,"poly-decomp":5}],32:[function(require,module,exports){var vec2=require("../math/vec2");var Spring=require("./Spring");var Utils=require("../utils/Utils");module.exports=LinearSpring;function LinearSpring(bodyA,bodyB,options){options=options||{};Spring.call(this,bodyA,bodyB,options);this.localAnchorA=vec2.fromValues(0,0);this.localAnchorB=vec2.fromValues(0,0);if(options.localAnchorA){vec2.copy(this.localAnchorA,options.localAnchorA)}if(options.localAnchorB){vec2.copy(this.localAnchorB,options.localAnchorB)}if(options.worldAnchorA){this.setWorldAnchorA(options.worldAnchorA)}if(options.worldAnchorB){this.setWorldAnchorB(options.worldAnchorB)}var worldAnchorA=vec2.create();var worldAnchorB=vec2.create();this.getWorldAnchorA(worldAnchorA);this.getWorldAnchorB(worldAnchorB);var worldDistance=vec2.distance(worldAnchorA,worldAnchorB);this.restLength=typeof options.restLength==="number"?options.restLength:worldDistance}LinearSpring.prototype=new Spring;LinearSpring.prototype.constructor=LinearSpring;LinearSpring.prototype.setWorldAnchorA=function(worldAnchorA){this.bodyA.toLocalFrame(this.localAnchorA,worldAnchorA)};LinearSpring.prototype.setWorldAnchorB=function(worldAnchorB){this.bodyB.toLocalFrame(this.localAnchorB,worldAnchorB)};LinearSpring.prototype.getWorldAnchorA=function(result){this.bodyA.toWorldFrame(result,this.localAnchorA)};LinearSpring.prototype.getWorldAnchorB=function(result){this.bodyB.toWorldFrame(result,this.localAnchorB)};var applyForce_r=vec2.create(),applyForce_r_unit=vec2.create(),applyForce_u=vec2.create(),applyForce_f=vec2.create(),applyForce_worldAnchorA=vec2.create(),applyForce_worldAnchorB=vec2.create(),applyForce_ri=vec2.create(),applyForce_rj=vec2.create(),applyForce_tmp=vec2.create();LinearSpring.prototype.applyForce=function(){var k=this.stiffness,d=this.damping,l=this.restLength,bodyA=this.bodyA,bodyB=this.bodyB,r=applyForce_r,r_unit=applyForce_r_unit,u=applyForce_u,f=applyForce_f,tmp=applyForce_tmp;var worldAnchorA=applyForce_worldAnchorA,worldAnchorB=applyForce_worldAnchorB,ri=applyForce_ri,rj=applyForce_rj;this.getWorldAnchorA(worldAnchorA);this.getWorldAnchorB(worldAnchorB);vec2.sub(ri,worldAnchorA,bodyA.position);vec2.sub(rj,worldAnchorB,bodyB.position);vec2.sub(r,worldAnchorB,worldAnchorA);var rlen=vec2.len(r);vec2.normalize(r_unit,r);vec2.sub(u,bodyB.velocity,bodyA.velocity);vec2.crossZV(tmp,bodyB.angularVelocity,rj);vec2.add(u,u,tmp);vec2.crossZV(tmp,bodyA.angularVelocity,ri);vec2.sub(u,u,tmp);vec2.scale(f,r_unit,-k*(rlen-l)-d*vec2.dot(u,r_unit));vec2.sub(bodyA.force,bodyA.force,f);vec2.add(bodyB.force,bodyB.force,f);var ri_x_f=vec2.crossLength(ri,f);var rj_x_f=vec2.crossLength(rj,f);bodyA.angularForce-=ri_x_f;bodyB.angularForce+=rj_x_f}},{"../math/vec2":30,"../utils/Utils":56,"./Spring":34}],33:[function(require,module,exports){var vec2=require("../math/vec2");var Spring=require("./Spring");module.exports=RotationalSpring;function RotationalSpring(bodyA,bodyB,options){options=options||{};Spring.call(this,bodyA,bodyB,options);this.restAngle=typeof options.restAngle==="number"?options.restAngle:bodyB.angle-bodyA.angle}RotationalSpring.prototype=new Spring;RotationalSpring.prototype.constructor=RotationalSpring;RotationalSpring.prototype.applyForce=function(){var k=this.stiffness,d=this.damping,l=this.restAngle,bodyA=this.bodyA,bodyB=this.bodyB,x=bodyB.angle-bodyA.angle,u=bodyB.angularVelocity-bodyA.angularVelocity;var torque=-k*(x-l)-d*u*0;bodyA.angularForce-=torque;bodyB.angularForce+=torque}},{"../math/vec2":30,"./Spring":34}],34:[function(require,module,exports){var vec2=require("../math/vec2");var Utils=require("../utils/Utils");module.exports=Spring;function Spring(bodyA,bodyB,options){options=Utils.defaults(options,{stiffness:100,damping:1});this.stiffness=options.stiffness;this.damping=options.damping;this.bodyA=bodyA;this.bodyB=bodyB}Spring.prototype.applyForce=function(){}},{"../math/vec2":30,"../utils/Utils":56}],35:[function(require,module,exports){var vec2=require("../math/vec2");var Utils=require("../utils/Utils");var Constraint=require("../constraints/Constraint");var FrictionEquation=require("../equations/FrictionEquation");var Body=require("../objects/Body");module.exports=TopDownVehicle;function TopDownVehicle(chassisBody,options){options=options||{};this.chassisBody=chassisBody;this.wheels=[];this.groundBody=new Body({mass:0});this.world=null;var that=this;this.preStepCallback=function(){that.update()}}TopDownVehicle.prototype.addToWorld=function(world){this.world=world;world.addBody(this.groundBody);world.on("preStep",this.preStepCallback);for(var i=0;i<this.wheels.length;i++){var wheel=this.wheels[i];world.addConstraint(wheel)}};TopDownVehicle.prototype.removeFromWorld=function(){var world=this.world;world.removeBody(this.groundBody);world.off("preStep",this.preStepCallback);for(var i=0;i<this.wheels.length;i++){ | |
var wheel=this.wheels[i];world.removeConstraint(wheel)}this.world=null};TopDownVehicle.prototype.addWheel=function(wheelOptions){var wheel=new WheelConstraint(this,wheelOptions);this.wheels.push(wheel);return wheel};TopDownVehicle.prototype.update=function(){for(var i=0;i<this.wheels.length;i++){this.wheels[i].update()}};function WheelConstraint(vehicle,options){options=options||{};this.vehicle=vehicle;this.forwardEquation=new FrictionEquation(vehicle.chassisBody,vehicle.groundBody);this.sideEquation=new FrictionEquation(vehicle.chassisBody,vehicle.groundBody);this.steerValue=0;this.engineForce=0;this.setSideFriction(options.sideFriction!==undefined?options.sideFriction:5);this.localForwardVector=vec2.fromValues(0,1);if(options.localForwardVector){vec2.copy(this.localForwardVector,options.localForwardVector)}this.localPosition=vec2.fromValues(0,0);if(options.localPosition){vec2.copy(this.localPosition,options.localPosition)}Constraint.apply(this,vehicle.chassisBody,vehicle.groundBody);this.equations.push(this.forwardEquation,this.sideEquation);this.setBrakeForce(0)}WheelConstraint.prototype=new Constraint;WheelConstraint.prototype.setBrakeForce=function(force){this.forwardEquation.setSlipForce(force)};WheelConstraint.prototype.setSideFriction=function(force){this.sideEquation.setSlipForce(force)};var worldVelocity=vec2.create();var relativePoint=vec2.create();WheelConstraint.prototype.getSpeed=function(){this.vehicle.chassisBody.vectorToWorldFrame(relativePoint,this.localForwardVector);this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity,relativePoint);return vec2.dot(worldVelocity,relativePoint)};var tmpVec=vec2.create();WheelConstraint.prototype.update=function(){this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t,this.localForwardVector);vec2.rotate(this.sideEquation.t,this.localForwardVector,Math.PI/2);this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t,this.sideEquation.t);vec2.rotate(this.forwardEquation.t,this.forwardEquation.t,this.steerValue);vec2.rotate(this.sideEquation.t,this.sideEquation.t,this.steerValue);this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB,this.localPosition);vec2.copy(this.sideEquation.contactPointB,this.forwardEquation.contactPointB);this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA,this.localPosition);vec2.copy(this.sideEquation.contactPointA,this.forwardEquation.contactPointA);vec2.normalize(tmpVec,this.forwardEquation.t);vec2.scale(tmpVec,tmpVec,this.engineForce);this.vehicle.chassisBody.applyForce(tmpVec,this.forwardEquation.contactPointA)}},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":56}],36:[function(require,module,exports){var vec2=require("../math/vec2"),Shape=require("./Shape"),Convex=require("./Convex");module.exports=Box;function Box(options){if(typeof arguments[0]==="number"&&typeof arguments[1]==="number"){options={width:arguments[0],height:arguments[1]};console.warn("The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })")}options=options||{};var width=this.width=options.width||1;var height=this.height=options.height||1;var verts=[vec2.fromValues(-width/2,-height/2),vec2.fromValues(width/2,-height/2),vec2.fromValues(width/2,height/2),vec2.fromValues(-width/2,height/2)];var axes=[vec2.fromValues(1,0),vec2.fromValues(0,1)];options.vertices=verts;options.axes=axes;options.type=Shape.BOX;Convex.call(this,options)}Box.prototype=new Convex;Box.prototype.constructor=Box;Box.prototype.computeMomentOfInertia=function(mass){var w=this.width,h=this.height;return mass*(h*h+w*w)/12};Box.prototype.updateBoundingRadius=function(){var w=this.width,h=this.height;this.boundingRadius=Math.sqrt(w*w+h*h)/2};var corner1=vec2.create(),corner2=vec2.create(),corner3=vec2.create(),corner4=vec2.create();Box.prototype.computeAABB=function(out,position,angle){out.setFromPoints(this.vertices,position,angle,0)};Box.prototype.updateArea=function(){this.area=this.width*this.height}},{"../math/vec2":30,"./Convex":39,"./Shape":44}],37:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2");module.exports=Capsule;function Capsule(options){if(typeof arguments[0]==="number"&&typeof arguments[1]==="number"){options={length:arguments[0],radius:arguments[1]};console.warn("The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })")}options=options||{};this.length=options.length||1;this.radius=options.radius||1;options.type=Shape.CAPSULE;Shape.call(this,options)}Capsule.prototype=new Shape;Capsule.prototype.constructor=Capsule;Capsule.prototype.computeMomentOfInertia=function(mass){var r=this.radius,w=this.length+r,h=r*2;return mass*(h*h+w*w)/12};Capsule.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius+this.length/2};Capsule.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius+this.radius*2*this.length};var r=vec2.create();Capsule.prototype.computeAABB=function(out,position,angle){var radius=this.radius;vec2.set(r,this.length/2,0);if(angle!==0){vec2.rotate(r,r,angle)}vec2.set(out.upperBound,Math.max(r[0]+radius,-r[0]+radius),Math.max(r[1]+radius,-r[1]+radius));vec2.set(out.lowerBound,Math.min(r[0]-radius,-r[0]-radius),Math.min(r[1]-radius,-r[1]-radius));vec2.add(out.lowerBound,out.lowerBound,position);vec2.add(out.upperBound,out.upperBound,position)};var intersectCapsule_hitPointWorld=vec2.create();var intersectCapsule_normal=vec2.create();var intersectCapsule_l0=vec2.create();var intersectCapsule_l1=vec2.create();var intersectCapsule_unit_y=vec2.fromValues(0,1);Capsule.prototype.raycast=function(result,ray,position,angle){var from=ray.from;var to=ray.to;var direction=ray.direction;var hitPointWorld=intersectCapsule_hitPointWorld;var normal=intersectCapsule_normal;var l0=intersectCapsule_l0;var l1=intersectCapsule_l1;var halfLen=this.length/2;for(var i=0;i<2;i++){var y=this.radius*(i*2-1);vec2.set(l0,-halfLen,y);vec2.set(l1,halfLen,y);vec2.toGlobalFrame(l0,l0,position,angle);vec2.toGlobalFrame(l1,l1,position,angle);var delta=vec2.getLineSegmentsIntersectionFraction(from,to,l0,l1);if(delta>=0){vec2.rotate(normal,intersectCapsule_unit_y,angle);vec2.scale(normal,normal,i*2-1);ray.reportIntersection(result,delta,normal,-1);if(result.shouldStop(ray)){return}}}var diagonalLengthSquared=Math.pow(this.radius,2)+Math.pow(halfLen,2);for(var i=0;i<2;i++){vec2.set(l0,halfLen*(i*2-1),0);vec2.toGlobalFrame(l0,l0,position,angle);var a=Math.pow(to[0]-from[0],2)+Math.pow(to[1]-from[1],2);var b=2*((to[0]-from[0])*(from[0]-l0[0])+(to[1]-from[1])*(from[1]-l0[1]));var c=Math.pow(from[0]-l0[0],2)+Math.pow(from[1]-l0[1],2)-Math.pow(this.radius,2);var delta=Math.pow(b,2)-4*a*c;if(delta<0){continue}else if(delta===0){vec2.lerp(hitPointWorld,from,to,delta);if(vec2.squaredDistance(hitPointWorld,position)>diagonalLengthSquared){vec2.sub(normal,hitPointWorld,l0);vec2.normalize(normal,normal);ray.reportIntersection(result,delta,normal,-1);if(result.shouldStop(ray)){return}}}else{var sqrtDelta=Math.sqrt(delta);var inv2a=1/(2*a);var d1=(-b-sqrtDelta)*inv2a;var d2=(-b+sqrtDelta)*inv2a;if(d1>=0&&d1<=1){vec2.lerp(hitPointWorld,from,to,d1);if(vec2.squaredDistance(hitPointWorld,position)>diagonalLengthSquared){vec2.sub(normal,hitPointWorld,l0);vec2.normalize(normal,normal);ray.reportIntersection(result,d1,normal,-1);if(result.shouldStop(ray)){return}}}if(d2>=0&&d2<=1){vec2.lerp(hitPointWorld,from,to,d2);if(vec2.squaredDistance(hitPointWorld,position)>diagonalLengthSquared){vec2.sub(normal,hitPointWorld,l0);vec2.normalize(normal,normal);ray.reportIntersection(result,d2,normal,-1);if(result.shouldStop(ray)){return}}}}}}},{"../math/vec2":30,"./Shape":44}],38:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2");module.exports=Circle;function Circle(options){if(typeof arguments[0]==="number"){options={radius:arguments[0]};console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")}options=options||{};this.radius=options.radius||1;options.type=Shape.CIRCLE;Shape.call(this,options)}Circle.prototype=new Shape;Circle.prototype.constructor=Circle;Circle.prototype.computeMomentOfInertia=function(mass){var r=this.radius;return mass*r*r/2};Circle.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius};Circle.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius};Circle.prototype.computeAABB=function(out,position,angle){var r=this.radius;vec2.set(out.upperBound,r,r);vec2.set(out.lowerBound,-r,-r);if(position){vec2.add(out.lowerBound,out.lowerBound,position);vec2.add(out.upperBound,out.upperBound,position)}};var Ray_intersectSphere_intersectionPoint=vec2.create();var Ray_intersectSphere_normal=vec2.create();Circle.prototype.raycast=function(result,ray,position,angle){var from=ray.from,to=ray.to,r=this.radius;var a=Math.pow(to[0]-from[0],2)+Math.pow(to[1]-from[1],2);var b=2*((to[0]-from[0])*(from[0]-position[0])+(to[1]-from[1])*(from[1]-position[1]));var c=Math.pow(from[0]-position[0],2)+Math.pow(from[1]-position[1],2)-Math.pow(r,2);var delta=Math.pow(b,2)-4*a*c;var intersectionPoint=Ray_intersectSphere_intersectionPoint;var normal=Ray_intersectSphere_normal;if(delta<0){return}else if(delta===0){vec2.lerp(intersectionPoint,from,to,delta);vec2.sub(normal,intersectionPoint,position);vec2.normalize(normal,normal);ray.reportIntersection(result,delta,normal,-1)}else{var sqrtDelta=Math.sqrt(delta);var inv2a=1/(2*a);var d1=(-b-sqrtDelta)*inv2a;var d2=(-b+sqrtDelta)*inv2a;if(d1>=0&&d1<=1){vec2.lerp(intersectionPoint,from,to,d1);vec2.sub(normal,intersectionPoint,position);vec2.normalize(normal,normal);ray.reportIntersection(result,d1,normal,-1);if(result.shouldStop(ray)){return}}if(d2>=0&&d2<=1){vec2.lerp(intersectionPoint,from,to,d2);vec2.sub(normal,intersectionPoint,position);vec2.normalize(normal,normal);ray.reportIntersection(result,d2,normal,-1)}}}},{"../math/vec2":30,"./Shape":44}],39:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2"),polyk=require("../math/polyk"),decomp=require("poly-decomp");module.exports=Convex;function Convex(options){if(Array.isArray(arguments[0])){options={vertices:arguments[0],axes:arguments[1]};console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")}options=options||{};this.vertices=[];var vertices=options.vertices!==undefined?options.vertices:[];for(var i=0;i<vertices.length;i++){var v=vec2.create();vec2.copy(v,vertices[i]);this.vertices.push(v)}this.axes=[];if(options.axes){for(var i=0;i<options.axes.length;i++){var axis=vec2.create();vec2.copy(axis,options.axes[i]);this.axes.push(axis)}}else{for(var i=0;i<this.vertices.length;i++){var worldPoint0=this.vertices[i];var worldPoint1=this.vertices[(i+1)%this.vertices.length];var normal=vec2.create();vec2.sub(normal,worldPoint1,worldPoint0);vec2.rotate90cw(normal,normal);vec2.normalize(normal,normal);this.axes.push(normal)}}this.centerOfMass=vec2.fromValues(0,0);this.triangles=[];if(this.vertices.length){this.updateTriangles();this.updateCenterOfMass()}this.boundingRadius=0;options.type=Shape.CONVEX;Shape.call(this,options);this.updateBoundingRadius();this.updateArea();if(this.area<0){throw new Error("Convex vertices must be given in conter-clockwise winding.")}}Convex.prototype=new Shape;Convex.prototype.constructor=Convex;var tmpVec1=vec2.create();var tmpVec2=vec2.create();Convex.prototype.projectOntoLocalAxis=function(localAxis,result){var max=null,min=null,v,value,localAxis=tmpVec1;for(var i=0;i<this.vertices.length;i++){v=this.vertices[i];value=vec2.dot(v,localAxis);if(max===null||value>max){max=value}if(min===null||value<min){min=value}}if(min>max){var t=min;min=max;max=t}vec2.set(result,min,max)};Convex.prototype.projectOntoWorldAxis=function(localAxis,shapeOffset,shapeAngle,result){var worldAxis=tmpVec2;this.projectOntoLocalAxis(localAxis,result);if(shapeAngle!==0){vec2.rotate(worldAxis,localAxis,shapeAngle)}else{worldAxis=localAxis}var offset=vec2.dot(shapeOffset,worldAxis);vec2.set(result,result[0]+offset,result[1]+offset)};Convex.prototype.updateTriangles=function(){this.triangles.length=0;var polykVerts=[];for(var i=0;i<this.vertices.length;i++){var v=this.vertices[i];polykVerts.push(v[0],v[1])}var triangles=polyk.Triangulate(polykVerts);for(var i=0;i<triangles.length;i+=3){var id1=triangles[i],id2=triangles[i+1],id3=triangles[i+2];this.triangles.push([id1,id2,id3])}};var updateCenterOfMass_centroid=vec2.create(),updateCenterOfMass_centroid_times_mass=vec2.create(),updateCenterOfMass_a=vec2.create(),updateCenterOfMass_b=vec2.create(),updateCenterOfMass_c=vec2.create(),updateCenterOfMass_ac=vec2.create(),updateCenterOfMass_ca=vec2.create(),updateCenterOfMass_cb=vec2.create(),updateCenterOfMass_n=vec2.create();Convex.prototype.updateCenterOfMass=function(){var triangles=this.triangles,verts=this.vertices,cm=this.centerOfMass,centroid=updateCenterOfMass_centroid,n=updateCenterOfMass_n,a=updateCenterOfMass_a,b=updateCenterOfMass_b,c=updateCenterOfMass_c,ac=updateCenterOfMass_ac,ca=updateCenterOfMass_ca,cb=updateCenterOfMass_cb,centroid_times_mass=updateCenterOfMass_centroid_times_mass;vec2.set(cm,0,0);var totalArea=0;for(var i=0;i!==triangles.length;i++){var t=triangles[i],a=verts[t[0]],b=verts[t[1]],c=verts[t[2]];vec2.centroid(centroid,a,b,c);var m=Convex.triangleArea(a,b,c);totalArea+=m;vec2.scale(centroid_times_mass,centroid,m);vec2.add(cm,cm,centroid_times_mass)}vec2.scale(cm,cm,1/totalArea)};Convex.prototype.computeMomentOfInertia=function(mass){var denom=0,numer=0,N=this.vertices.length;for(var j=N-1,i=0;i<N;j=i,i++){var p0=this.vertices[j];var p1=this.vertices[i];var a=Math.abs(vec2.crossLength(p0,p1));var b=vec2.dot(p1,p1)+vec2.dot(p1,p0)+vec2.dot(p0,p0);denom+=a*b;numer+=a}return mass/6*(denom/numer)};Convex.prototype.updateBoundingRadius=function(){var verts=this.vertices,r2=0;for(var i=0;i!==verts.length;i++){var l2=vec2.squaredLength(verts[i]);if(l2>r2){r2=l2}}this.boundingRadius=Math.sqrt(r2)};Convex.triangleArea=function(a,b,c){return((b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1]))*.5};Convex.prototype.updateArea=function(){this.updateTriangles();this.area=0;var triangles=this.triangles,verts=this.vertices;for(var i=0;i!==triangles.length;i++){var t=triangles[i],a=verts[t[0]],b=verts[t[1]],c=verts[t[2]];var m=Convex.triangleArea(a,b,c);this.area+=m}};Convex.prototype.computeAABB=function(out,position,angle){out.setFromPoints(this.vertices,position,angle,0)};var intersectConvex_rayStart=vec2.create();var intersectConvex_rayEnd=vec2.create();var intersectConvex_normal=vec2.create();Convex.prototype.raycast=function(result,ray,position,angle){var rayStart=intersectConvex_rayStart;var rayEnd=intersectConvex_rayEnd;var normal=intersectConvex_normal;var vertices=this.vertices;vec2.toLocalFrame(rayStart,ray.from,position,angle);vec2.toLocalFrame(rayEnd,ray.to,position,angle);var n=vertices.length;for(var i=0;i<n&&!result.shouldStop(ray);i++){var q1=vertices[i];var q2=vertices[(i+1)%n];var delta=vec2.getLineSegmentsIntersectionFraction(rayStart,rayEnd,q1,q2);if(delta>=0){vec2.sub(normal,q2,q1);vec2.rotate(normal,normal,-Math.PI/2+angle);vec2.normalize(normal,normal);ray.reportIntersection(result,delta,normal,i)}}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":44,"poly-decomp":5}],40:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2"),Utils=require("../utils/Utils");module.exports=Heightfield;function Heightfield(options){if(Array.isArray(arguments[0])){options={heights:arguments[0]};if(typeof arguments[1]==="object"){for(var key in arguments[1]){options[key]=arguments[1][key]}}console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}options=options||{};this.heights=options.heights?options.heights.slice(0):[];this.maxValue=options.maxValue||null;this.minValue=options.minValue||null;this.elementWidth=options.elementWidth||.1;if(options.maxValue===undefined||options.minValue===undefined){this.updateMaxMinValues()}options.type=Shape.HEIGHTFIELD;Shape.call(this,options)}Heightfield.prototype=new Shape;Heightfield.prototype.constructor=Heightfield;Heightfield.prototype.updateMaxMinValues=function(){var data=this.heights;var maxValue=data[0];var minValue=data[0];for(var i=0;i!==data.length;i++){var v=data[i];if(v>maxValue){maxValue=v}if(v<minValue){minValue=v}}this.maxValue=maxValue;this.minValue=minValue};Heightfield.prototype.computeMomentOfInertia=function(mass){return Number.MAX_VALUE};Heightfield.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE};Heightfield.prototype.updateArea=function(){var data=this.heights,area=0;for(var i=0;i<data.length-1;i++){area+=(data[i]+data[i+1])/2*this.elementWidth}this.area=area};var points=[vec2.create(),vec2.create(),vec2.create(),vec2.create()];Heightfield.prototype.computeAABB=function(out,position,angle){vec2.set(points[0],0,this.maxValue);vec2.set(points[1],this.elementWidth*this.heights.length,this.maxValue);vec2.set(points[2],this.elementWidth*this.heights.length,this.minValue);vec2.set(points[3],0,this.minValue);out.setFromPoints(points,position,angle)};Heightfield.prototype.getLineSegment=function(start,end,i){var data=this.heights;var width=this.elementWidth;vec2.set(start,i*width,data[i]);vec2.set(end,(i+1)*width,data[i+1])};Heightfield.prototype.getSegmentIndex=function(position){return Math.floor(position[0]/this.elementWidth)};Heightfield.prototype.getClampedSegmentIndex=function(position){var i=this.getSegmentIndex(position);i=Math.min(this.heights.length,Math.max(i,0));return i};var intersectHeightfield_hitPointWorld=vec2.create();var intersectHeightfield_worldNormal=vec2.create();var intersectHeightfield_l0=vec2.create();var intersectHeightfield_l1=vec2.create();var intersectHeightfield_localFrom=vec2.create();var intersectHeightfield_localTo=vec2.create();var intersectHeightfield_unit_y=vec2.fromValues(0,1);function getLineSegmentsIntersection(out,p0,p1,p2,p3){var s1_x,s1_y,s2_x,s2_y;s1_x=p1[0]-p0[0];s1_y=p1[1]-p0[1];s2_x=p3[0]-p2[0];s2_y=p3[1]-p2[1];var s,t;s=(-s1_y*(p0[0]-p2[0])+s1_x*(p0[1]-p2[1]))/(-s2_x*s1_y+s1_x*s2_y);t=(s2_x*(p0[1]-p2[1])-s2_y*(p0[0]-p2[0]))/(-s2_x*s1_y+s1_x*s2_y);if(s>=0&&s<=1&&t>=0&&t<=1){var intX=p0[0]+t*s1_x;var intY=p0[1]+t*s1_y;out[0]=intX;out[1]=intY;return t}return-1}Heightfield.prototype.raycast=function(result,ray,position,angle){var from=ray.from;var to=ray.to;var direction=ray.direction;var hitPointWorld=intersectHeightfield_hitPointWorld;var worldNormal=intersectHeightfield_worldNormal;var l0=intersectHeightfield_l0;var l1=intersectHeightfield_l1;var localFrom=intersectHeightfield_localFrom;var localTo=intersectHeightfield_localTo;vec2.toLocalFrame(localFrom,from,position,angle);vec2.toLocalFrame(localTo,to,position,angle);var i0=this.getClampedSegmentIndex(localFrom);var i1=this.getClampedSegmentIndex(localTo);if(i0>i1){var tmp=i0;i0=i1;i1=tmp}for(var i=0;i<this.heights.length-1;i++){this.getLineSegment(l0,l1,i);var t=vec2.getLineSegmentsIntersectionFraction(localFrom,localTo,l0,l1);if(t>=0){vec2.sub(worldNormal,l1,l0);vec2.rotate(worldNormal,worldNormal,angle+Math.PI/2);vec2.normalize(worldNormal,worldNormal);ray.reportIntersection(result,t,worldNormal,-1);if(result.shouldStop(ray)){return}}}}},{"../math/vec2":30,"../utils/Utils":56,"./Shape":44}],41:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2");module.exports=Line;function Line(options){if(typeof arguments[0]==="number"){options={length:arguments[0]};console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")}options=options||{};this.length=options.length||1;options.type=Shape.LINE;Shape.call(this,options)}Line.prototype=new Shape;Line.prototype.constructor=Line;Line.prototype.computeMomentOfInertia=function(mass){return mass*Math.pow(this.length,2)/12};Line.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var points=[vec2.create(),vec2.create()];Line.prototype.computeAABB=function(out,position,angle){var l2=this.length/2;vec2.set(points[0],-l2,0);vec2.set(points[1],l2,0);out.setFromPoints(points,position,angle,0)};var raycast_hitPoint=vec2.create();var raycast_normal=vec2.create();var raycast_l0=vec2.create();var raycast_l1=vec2.create();var raycast_unit_y=vec2.fromValues(0,1);Line.prototype.raycast=function(result,ray,position,angle){var from=ray.from;var to=ray.to;var l0=raycast_l0;var l1=raycast_l1;var halfLen=this.length/2;vec2.set(l0,-halfLen,0);vec2.set(l1,halfLen,0);vec2.toGlobalFrame(l0,l0,position,angle);vec2.toGlobalFrame(l1,l1,position,angle);var fraction=vec2.getLineSegmentsIntersectionFraction(l0,l1,from,to);if(fraction>=0){var normal=raycast_normal;vec2.rotate(normal,raycast_unit_y,angle);ray.reportIntersection(result,fraction,normal,-1)}}},{"../math/vec2":30,"./Shape":44}],42:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2");module.exports=Particle;function Particle(options){options=options||{};options.type=Shape.PARTICLE;Shape.call(this,options)}Particle.prototype=new Shape;Particle.prototype.constructor=Particle;Particle.prototype.computeMomentOfInertia=function(mass){return 0};Particle.prototype.updateBoundingRadius=function(){this.boundingRadius=0};Particle.prototype.computeAABB=function(out,position,angle){vec2.copy(out.lowerBound,position);vec2.copy(out.upperBound,position)}},{"../math/vec2":30,"./Shape":44}],43:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2"),Utils=require("../utils/Utils");module.exports=Plane;function Plane(options){options=options||{};options.type=Shape.PLANE;Shape.call(this,options)}Plane.prototype=new Shape;Plane.prototype.constructor=Plane;Plane.prototype.computeMomentOfInertia=function(mass){return 0};Plane.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE};Plane.prototype.computeAABB=function(out,position,angle){var a=angle%(2*Math.PI);var set=vec2.set;var max=1e7;var lowerBound=out.lowerBound;var upperBound=out.upperBound;set(lowerBound,-max,-max);set(upperBound,max,max);if(a===0){upperBound[1]=0}else if(a===Math.PI/2){lowerBound[0]=0}else if(a===Math.PI){lowerBound[1]=0}else if(a===3*Math.PI/2){upperBound[0]=0}};Plane.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var intersectPlane_planePointToFrom=vec2.create();var intersectPlane_dir_scaled_with_t=vec2.create();var intersectPlane_hitPoint=vec2.create();var intersectPlane_normal=vec2.create();var intersectPlane_len=vec2.create();Plane.prototype.raycast=function(result,ray,position,angle){var from=ray.from;var to=ray.to;var direction=ray.direction;var planePointToFrom=intersectPlane_planePointToFrom;var dir_scaled_with_t=intersectPlane_dir_scaled_with_t;var hitPoint=intersectPlane_hitPoint;var normal=intersectPlane_normal;var len=intersectPlane_len;vec2.set(normal,0,1);vec2.rotate(normal,normal,angle);vec2.sub(len,from,position);var planeToFrom=vec2.dot(len,normal);vec2.sub(len,to,position);var planeToTo=vec2.dot(len,normal);if(planeToFrom*planeToTo>0){return}if(vec2.squaredDistance(from,to)<planeToFrom*planeToFrom){return}var n_dot_dir=vec2.dot(normal,direction);vec2.sub(planePointToFrom,from,position);var t=-vec2.dot(normal,planePointToFrom)/n_dot_dir/ray.length;ray.reportIntersection(result,t,normal,-1)}},{"../math/vec2":30,"../utils/Utils":56,"./Shape":44}],44:[function(require,module,exports){module.exports=Shape;var vec2=require("../math/vec2");function Shape(options){options=options||{};this.body=null;this.position=vec2.fromValues(0,0);if(options.position){vec2.copy(this.position,options.position)}this.angle=options.angle||0;this.type=options.type||0;this.id=Shape.idCounter++;this.boundingRadius=0;this.collisionGroup=options.collisionGroup!==undefined?options.collisionGroup:1;this.collisionResponse=options.collisionResponse!==undefined?options.collisionResponse:true;this.collisionMask=options.collisionMask!==undefined?options.collisionMask:1;this.material=options.material||null;this.area=0;this.sensor=options.sensor!==undefined?options.sensor:false;if(this.type){this.updateBoundingRadius()}this.updateArea()}Shape.idCounter=0;Shape.CIRCLE=1;Shape.PARTICLE=2;Shape.PLANE=4;Shape.CONVEX=8;Shape.LINE=16;Shape.BOX=32;Object.defineProperty(Shape,"RECTANGLE",{get:function(){console.warn("Shape.RECTANGLE is deprecated, use Shape.BOX instead.");return Shape.BOX}});Shape.CAPSULE=64;Shape.HEIGHTFIELD=128;Shape.prototype.computeMomentOfInertia=function(mass){};Shape.prototype.updateBoundingRadius=function(){};Shape.prototype.updateArea=function(){};Shape.prototype.computeAABB=function(out,position,angle){};Shape.prototype.raycast=function(result,ray,position,angle){}},{"../math/vec2":30}],45:[function(require,module,exports){var vec2=require("../math/vec2"),Solver=require("./Solver"),Utils=require("../utils/Utils"),FrictionEquation=require("../equations/FrictionEquation");module.exports=GSSolver;function GSSolver(options){Solver.call(this,options,Solver.GS);options=options||{};this.iterations=options.iterations||10;this.tolerance=options.tolerance||1e-7;this.arrayStep=30;this.lambda=new Utils.ARRAY_TYPE(this.arrayStep);this.Bs=new Utils.ARRAY_TYPE(this.arrayStep);this.invCs=new Utils.ARRAY_TYPE(this.arrayStep);this.useZeroRHS=false;this.frictionIterations=options.frictionIterations!==undefined?0:options.frictionIterations;this.usedIterations=0}GSSolver.prototype=new Solver;GSSolver.prototype.constructor=GSSolver;function setArrayZero(array){var l=array.length;while(l--){array[l]=+0}}GSSolver.prototype.solve=function(h,world){this.sortEquations();var iter=0,maxIter=this.iterations,maxFrictionIter=this.frictionIterations,equations=this.equations,Neq=equations.length,tolSquared=Math.pow(this.tolerance*Neq,2),bodies=world.bodies,Nbodies=world.bodies.length,add=vec2.add,set=vec2.set,useZeroRHS=this.useZeroRHS,lambda=this.lambda;this.usedIterations=0;if(Neq){for(var i=0;i!==Nbodies;i++){var b=bodies[i];b.updateSolveMassProperties()}}if(lambda.length<Neq){lambda=this.lambda=new Utils.ARRAY_TYPE(Neq+this.arrayStep);this.Bs=new Utils.ARRAY_TYPE(Neq+this.arrayStep);this.invCs=new Utils.ARRAY_TYPE(Neq+this.arrayStep)}setArrayZero(lambda);var invCs=this.invCs,Bs=this.Bs,lambda=this.lambda;for(var i=0;i!==equations.length;i++){var c=equations[i];if(c.timeStep!==h||c.needsUpdate){c.timeStep=h;c.update()}Bs[i]=c.computeB(c.a,c.b,h);invCs[i]=c.computeInvC(c.epsilon)}var q,B,c,deltalambdaTot,i,j;if(Neq!==0){for(i=0;i!==Nbodies;i++){var b=bodies[i];b.resetConstraintVelocity()}if(maxFrictionIter){for(iter=0;iter!==maxFrictionIter;iter++){deltalambdaTot=0;for(j=0;j!==Neq;j++){c=equations[j];var deltalambda=GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);deltalambdaTot+=Math.abs(deltalambda)}this.usedIterations++;if(deltalambdaTot*deltalambdaTot<=tolSquared){break}}GSSolver.updateMultipliers(equations,lambda,1/h);for(j=0;j!==Neq;j++){var eq=equations[j];if(eq instanceof FrictionEquation){var f=0;for(var k=0;k!==eq.contactEquations.length;k++){f+=eq.contactEquations[k].multiplier}f*=eq.frictionCoefficient/eq.contactEquations.length;eq.maxForce=f;eq.minForce=-f}}}for(iter=0;iter!==maxIter;iter++){deltalambdaTot=0;for(j=0;j!==Neq;j++){c=equations[j];var deltalambda=GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);deltalambdaTot+=Math.abs(deltalambda)}this.usedIterations++;if(deltalambdaTot*deltalambdaTot<=tolSquared){break}}for(i=0;i!==Nbodies;i++){bodies[i].addConstraintVelocity()}GSSolver.updateMultipliers(equations,lambda,1/h)}};GSSolver.updateMultipliers=function(equations,lambda,invDt){var l=equations.length;while(l--){equations[l].multiplier=lambda[l]*invDt}};GSSolver.iterateEquation=function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){var B=Bs[j],invC=invCs[j],lambdaj=lambda[j],GWlambda=eq.computeGWlambda();var maxForce=eq.maxForce,minForce=eq.minForce;if(useZeroRHS){B=0}var deltalambda=invC*(B-GWlambda-eps*lambdaj);var lambdaj_plus_deltalambda=lambdaj+deltalambda;if(lambdaj_plus_deltalambda<minForce*dt){deltalambda=minForce*dt-lambdaj}else if(lambdaj_plus_deltalambda>maxForce*dt){deltalambda=maxForce*dt-lambdaj}lambda[j]+=deltalambda;eq.addToWlambda(deltalambda);return deltalambda}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":56,"./Solver":46}],46:[function(require,module,exports){var Utils=require("../utils/Utils"),EventEmitter=require("../events/EventEmitter");module.exports=Solver;function Solver(options,type){options=options||{};EventEmitter.call(this);this.type=type;this.equations=[];this.equationSortFunction=options.equationSortFunction||false}Solver.prototype=new EventEmitter;Solver.prototype.constructor=Solver;Solver.prototype.solve=function(dt,world){throw new Error("Solver.solve should be implemented by subclasses!")};var mockWorld={bodies:[]};Solver.prototype.solveIsland=function(dt,island){this.removeAllEquations();if(island.equations.length){this.addEquations(island.equations);mockWorld.bodies.length=0;island.getBodies(mockWorld.bodies);if(mockWorld.bodies.length){this.solve(dt,mockWorld)}}};Solver.prototype.sortEquations=function(){if(this.equationSortFunction){this.equations.sort(this.equationSortFunction)}};Solver.prototype.addEquation=function(eq){if(eq.enabled){this.equations.push(eq)}};Solver.prototype.addEquations=function(eqs){for(var i=0,N=eqs.length;i!==N;i++){var eq=eqs[i];if(eq.enabled){this.equations.push(eq)}}};Solver.prototype.removeEquation=function(eq){var i=this.equations.indexOf(eq);if(i!==-1){this.equations.splice(i,1)}};Solver.prototype.removeAllEquations=function(){this.equations.length=0};Solver.GS=1;Solver.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":56}],47:[function(require,module,exports){var ContactEquation=require("../equations/ContactEquation");var Pool=require("./Pool");module.exports=ContactEquationPool;function ContactEquationPool(){Pool.apply(this,arguments)}ContactEquationPool.prototype=new Pool;ContactEquationPool.prototype.constructor=ContactEquationPool;ContactEquationPool.prototype.create=function(){return new ContactEquation};ContactEquationPool.prototype.destroy=function(equation){equation.bodyA=equation.bodyB=null;return this}},{"../equations/ContactEquation":21,"./Pool":54}],48:[function(require,module,exports){var FrictionEquation=require("../equations/FrictionEquation");var Pool=require("./Pool");module.exports=FrictionEquationPool;function FrictionEquationPool(){Pool.apply(this,arguments)}FrictionEquationPool.prototype=new Pool;FrictionEquationPool.prototype.constructor=FrictionEquationPool;FrictionEquationPool.prototype.create=function(){return new FrictionEquation};FrictionEquationPool.prototype.destroy=function(equation){equation.bodyA=equation.bodyB=null;return this}},{"../equations/FrictionEquation":23,"./Pool":54}],49:[function(require,module,exports){var IslandNode=require("../world/IslandNode");var Pool=require("./Pool");module.exports=IslandNodePool;function IslandNodePool(){Pool.apply(this,arguments)}IslandNodePool.prototype=new Pool;IslandNodePool.prototype.constructor=IslandNodePool;IslandNodePool.prototype.create=function(){return new IslandNode};IslandNodePool.prototype.destroy=function(node){node.reset();return this}},{"../world/IslandNode":59,"./Pool":54}],50:[function(require,module,exports){var Island=require("../world/Island");var Pool=require("./Pool");module.exports=IslandPool;function IslandPool(){Pool.apply(this,arguments)}IslandPool.prototype=new Pool;IslandPool.prototype.constructor=IslandPool;IslandPool.prototype.create=function(){return new Island};IslandPool.prototype.destroy=function(island){island.reset(); | |
return this}},{"../world/Island":57,"./Pool":54}],51:[function(require,module,exports){var TupleDictionary=require("./TupleDictionary");var OverlapKeeperRecord=require("./OverlapKeeperRecord");var OverlapKeeperRecordPool=require("./OverlapKeeperRecordPool");var Utils=require("./Utils");module.exports=OverlapKeeper;function OverlapKeeper(){this.overlappingShapesLastState=new TupleDictionary;this.overlappingShapesCurrentState=new TupleDictionary;this.recordPool=new OverlapKeeperRecordPool({size:16});this.tmpDict=new TupleDictionary;this.tmpArray1=[]}OverlapKeeper.prototype.tick=function(){var last=this.overlappingShapesLastState;var current=this.overlappingShapesCurrentState;var l=last.keys.length;while(l--){var key=last.keys[l];var lastObject=last.getByKey(key);var currentObject=current.getByKey(key);if(lastObject){this.recordPool.release(lastObject)}}last.reset();last.copy(current);current.reset()};OverlapKeeper.prototype.setOverlapping=function(bodyA,shapeA,bodyB,shapeB){var last=this.overlappingShapesLastState;var current=this.overlappingShapesCurrentState;if(!current.get(shapeA.id,shapeB.id)){var data=this.recordPool.get();data.set(bodyA,shapeA,bodyB,shapeB);current.set(shapeA.id,shapeB.id,data)}};OverlapKeeper.prototype.getNewOverlaps=function(result){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,result)};OverlapKeeper.prototype.getEndOverlaps=function(result){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,result)};OverlapKeeper.prototype.bodiesAreOverlapping=function(bodyA,bodyB){var current=this.overlappingShapesCurrentState;var l=current.keys.length;while(l--){var key=current.keys[l];var data=current.data[key];if(data.bodyA===bodyA&&data.bodyB===bodyB||data.bodyA===bodyB&&data.bodyB===bodyA){return true}}return false};OverlapKeeper.prototype.getDiff=function(dictA,dictB,result){var result=result||[];var last=dictA;var current=dictB;result.length=0;var l=current.keys.length;while(l--){var key=current.keys[l];var data=current.data[key];if(!data){throw new Error("Key "+key+" had no data!")}var lastData=last.data[key];if(!lastData){result.push(data)}}return result};OverlapKeeper.prototype.isNewOverlap=function(shapeA,shapeB){var idA=shapeA.id|0,idB=shapeB.id|0;var last=this.overlappingShapesLastState;var current=this.overlappingShapesCurrentState;return!!!last.get(idA,idB)&&!!current.get(idA,idB)};OverlapKeeper.prototype.getNewBodyOverlaps=function(result){this.tmpArray1.length=0;var overlaps=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(overlaps,result)};OverlapKeeper.prototype.getEndBodyOverlaps=function(result){this.tmpArray1.length=0;var overlaps=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(overlaps,result)};OverlapKeeper.prototype.getBodyDiff=function(overlaps,result){result=result||[];var accumulator=this.tmpDict;var l=overlaps.length;while(l--){var data=overlaps[l];accumulator.set(data.bodyA.id|0,data.bodyB.id|0,data)}l=accumulator.keys.length;while(l--){var data=accumulator.getByKey(accumulator.keys[l]);if(data){result.push(data.bodyA,data.bodyB)}}accumulator.reset();return result}},{"./OverlapKeeperRecord":52,"./OverlapKeeperRecordPool":53,"./TupleDictionary":55,"./Utils":56}],52:[function(require,module,exports){module.exports=OverlapKeeperRecord;function OverlapKeeperRecord(bodyA,shapeA,bodyB,shapeB){this.shapeA=shapeA;this.shapeB=shapeB;this.bodyA=bodyA;this.bodyB=bodyB}OverlapKeeperRecord.prototype.set=function(bodyA,shapeA,bodyB,shapeB){OverlapKeeperRecord.call(this,bodyA,shapeA,bodyB,shapeB)}},{}],53:[function(require,module,exports){var OverlapKeeperRecord=require("./OverlapKeeperRecord");var Pool=require("./Pool");module.exports=OverlapKeeperRecordPool;function OverlapKeeperRecordPool(){Pool.apply(this,arguments)}OverlapKeeperRecordPool.prototype=new Pool;OverlapKeeperRecordPool.prototype.constructor=OverlapKeeperRecordPool;OverlapKeeperRecordPool.prototype.create=function(){return new OverlapKeeperRecord};OverlapKeeperRecordPool.prototype.destroy=function(record){record.bodyA=record.bodyB=record.shapeA=record.shapeB=null;return this}},{"./OverlapKeeperRecord":52,"./Pool":54}],54:[function(require,module,exports){module.exports=Pool;function Pool(options){options=options||{};this.objects=[];if(options.size!==undefined){this.resize(options.size)}}Pool.prototype.resize=function(size){var objects=this.objects;while(objects.length>size){objects.pop()}while(objects.length<size){objects.push(this.create())}return this};Pool.prototype.get=function(){var objects=this.objects;return objects.length?objects.pop():this.create()};Pool.prototype.release=function(object){this.destroy(object);this.objects.push(object);return this}},{}],55:[function(require,module,exports){var Utils=require("./Utils");module.exports=TupleDictionary;function TupleDictionary(){this.data={};this.keys=[]}TupleDictionary.prototype.getKey=function(id1,id2){id1=id1|0;id2=id2|0;if((id1|0)===(id2|0)){return-1}return((id1|0)>(id2|0)?id1<<16|id2&65535:id2<<16|id1&65535)|0};TupleDictionary.prototype.getByKey=function(key){key=key|0;return this.data[key]};TupleDictionary.prototype.get=function(i,j){return this.data[this.getKey(i,j)]};TupleDictionary.prototype.set=function(i,j,value){if(!value){throw new Error("No data!")}var key=this.getKey(i,j);if(!this.data[key]){this.keys.push(key)}this.data[key]=value;return key};TupleDictionary.prototype.reset=function(){var data=this.data,keys=this.keys;var l=keys.length;while(l--){delete data[keys[l]]}keys.length=0};TupleDictionary.prototype.copy=function(dict){this.reset();Utils.appendArray(this.keys,dict.keys);var l=dict.keys.length;while(l--){var key=dict.keys[l];this.data[key]=dict.data[key]}}},{"./Utils":56}],56:[function(require,module,exports){module.exports=Utils;function Utils(){}Utils.appendArray=function(a,b){if(b.length<15e4){a.push.apply(a,b)}else{for(var i=0,len=b.length;i!==len;++i){a.push(b[i])}}};Utils.splice=function(array,index,howmany){howmany=howmany||1;for(var i=index,len=array.length-howmany;i<len;i++){array[i]=array[i+howmany]}array.length=len};if(typeof P2_ARRAY_TYPE!=="undefined"){Utils.ARRAY_TYPE=P2_ARRAY_TYPE}else if(typeof Float32Array!=="undefined"){Utils.ARRAY_TYPE=Float32Array}else{Utils.ARRAY_TYPE=Array}Utils.extend=function(a,b){for(var key in b){a[key]=b[key]}};Utils.defaults=function(options,defaults){options=options||{};for(var key in defaults){if(!(key in options)){options[key]=defaults[key]}}return options}},{}],57:[function(require,module,exports){var Body=require("../objects/Body");module.exports=Island;function Island(){this.equations=[];this.bodies=[]}Island.prototype.reset=function(){this.equations.length=this.bodies.length=0};var bodyIds=[];Island.prototype.getBodies=function(result){var bodies=result||[],eqs=this.equations;bodyIds.length=0;for(var i=0;i!==eqs.length;i++){var eq=eqs[i];if(bodyIds.indexOf(eq.bodyA.id)===-1){bodies.push(eq.bodyA);bodyIds.push(eq.bodyA.id)}if(bodyIds.indexOf(eq.bodyB.id)===-1){bodies.push(eq.bodyB);bodyIds.push(eq.bodyB.id)}}return bodies};Island.prototype.wantsToSleep=function(){for(var i=0;i<this.bodies.length;i++){var b=this.bodies[i];if(b.type===Body.DYNAMIC&&!b.wantsToSleep){return false}}return true};Island.prototype.sleep=function(){for(var i=0;i<this.bodies.length;i++){var b=this.bodies[i];b.sleep()}return true}},{"../objects/Body":31}],58:[function(require,module,exports){var vec2=require("../math/vec2"),Island=require("./Island"),IslandNode=require("./IslandNode"),IslandNodePool=require("./../utils/IslandNodePool"),IslandPool=require("./../utils/IslandPool"),Body=require("../objects/Body");module.exports=IslandManager;function IslandManager(options){this.nodePool=new IslandNodePool({size:16});this.islandPool=new IslandPool({size:8});this.equations=[];this.islands=[];this.nodes=[];this.queue=[]}IslandManager.getUnvisitedNode=function(nodes){var Nnodes=nodes.length;for(var i=0;i!==Nnodes;i++){var node=nodes[i];if(!node.visited&&node.body.type===Body.DYNAMIC){return node}}return false};IslandManager.prototype.visit=function(node,bds,eqs){bds.push(node.body);var Neqs=node.equations.length;for(var i=0;i!==Neqs;i++){var eq=node.equations[i];if(eqs.indexOf(eq)===-1){eqs.push(eq)}}};IslandManager.prototype.bfs=function(root,bds,eqs){var queue=this.queue;queue.length=0;queue.push(root);root.visited=true;this.visit(root,bds,eqs);while(queue.length){var node=queue.pop();var child;while(child=IslandManager.getUnvisitedNode(node.neighbors)){child.visited=true;this.visit(child,bds,eqs);if(child.body.type===Body.DYNAMIC){queue.push(child)}}}};IslandManager.prototype.split=function(world){var bodies=world.bodies,nodes=this.nodes,equations=this.equations;while(nodes.length){this.nodePool.release(nodes.pop())}for(var i=0;i!==bodies.length;i++){var node=this.nodePool.get();node.body=bodies[i];nodes.push(node)}for(var k=0;k!==equations.length;k++){var eq=equations[k],i=bodies.indexOf(eq.bodyA),j=bodies.indexOf(eq.bodyB),ni=nodes[i],nj=nodes[j];ni.neighbors.push(nj);nj.neighbors.push(ni);ni.equations.push(eq);nj.equations.push(eq)}var islands=this.islands;for(var i=0;i<islands.length;i++){this.islandPool.release(islands[i])}islands.length=0;var child;while(child=IslandManager.getUnvisitedNode(nodes)){var island=this.islandPool.get();this.bfs(child,island.bodies,island.equations);islands.push(island)}return islands}},{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":49,"./../utils/IslandPool":50,"./Island":57,"./IslandNode":59}],59:[function(require,module,exports){module.exports=IslandNode;function IslandNode(body){this.body=body;this.neighbors=[];this.equations=[];this.visited=false}IslandNode.prototype.reset=function(){this.equations.length=0;this.neighbors.length=0;this.visited=false;this.body=null}},{}],60:[function(require,module,exports){var GSSolver=require("../solver/GSSolver"),Solver=require("../solver/Solver"),Ray=require("../collision/Ray"),vec2=require("../math/vec2"),Circle=require("../shapes/Circle"),Convex=require("../shapes/Convex"),Line=require("../shapes/Line"),Plane=require("../shapes/Plane"),Capsule=require("../shapes/Capsule"),Particle=require("../shapes/Particle"),EventEmitter=require("../events/EventEmitter"),Body=require("../objects/Body"),Shape=require("../shapes/Shape"),LinearSpring=require("../objects/LinearSpring"),Material=require("../material/Material"),ContactMaterial=require("../material/ContactMaterial"),DistanceConstraint=require("../constraints/DistanceConstraint"),Constraint=require("../constraints/Constraint"),LockConstraint=require("../constraints/LockConstraint"),RevoluteConstraint=require("../constraints/RevoluteConstraint"),PrismaticConstraint=require("../constraints/PrismaticConstraint"),GearConstraint=require("../constraints/GearConstraint"),pkg=require("../../package.json"),Broadphase=require("../collision/Broadphase"),AABB=require("../collision/AABB"),SAPBroadphase=require("../collision/SAPBroadphase"),Narrowphase=require("../collision/Narrowphase"),Utils=require("../utils/Utils"),OverlapKeeper=require("../utils/OverlapKeeper"),IslandManager=require("./IslandManager"),RotationalSpring=require("../objects/RotationalSpring");module.exports=World;function World(options){EventEmitter.apply(this);options=options||{};this.springs=[];this.bodies=[];this.disabledBodyCollisionPairs=[];this.solver=options.solver||new GSSolver;this.narrowphase=new Narrowphase(this);this.islandManager=new IslandManager;this.gravity=vec2.fromValues(0,-9.78);if(options.gravity){vec2.copy(this.gravity,options.gravity)}this.frictionGravity=vec2.length(this.gravity)||10;this.useWorldGravityAsFrictionGravity=true;this.useFrictionGravityOnZeroGravity=true;this.broadphase=options.broadphase||new SAPBroadphase;this.broadphase.setWorld(this);this.constraints=[];this.defaultMaterial=new Material;this.defaultContactMaterial=new ContactMaterial(this.defaultMaterial,this.defaultMaterial);this.lastTimeStep=1/60;this.applySpringForces=true;this.applyDamping=true;this.applyGravity=true;this.solveConstraints=true;this.contactMaterials=[];this.time=0;this.accumulator=0;this.stepping=false;this.bodiesToBeRemoved=[];this.islandSplit=typeof options.islandSplit!=="undefined"?!!options.islandSplit:true;this.emitImpactEvent=true;this._constraintIdCounter=0;this._bodyIdCounter=0;this.postStepEvent={type:"postStep"};this.addBodyEvent={type:"addBody",body:null};this.removeBodyEvent={type:"removeBody",body:null};this.addSpringEvent={type:"addSpring",spring:null};this.impactEvent={type:"impact",bodyA:null,bodyB:null,shapeA:null,shapeB:null,contactEquation:null};this.postBroadphaseEvent={type:"postBroadphase",pairs:null};this.sleepMode=World.NO_SLEEPING;this.beginContactEvent={type:"beginContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null,contactEquations:[]};this.endContactEvent={type:"endContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null};this.preSolveEvent={type:"preSolve",contactEquations:null,frictionEquations:null};this.overlappingShapesLastState={keys:[]};this.overlappingShapesCurrentState={keys:[]};this.overlapKeeper=new OverlapKeeper}World.prototype=new Object(EventEmitter.prototype);World.prototype.constructor=World;World.NO_SLEEPING=1;World.BODY_SLEEPING=2;World.ISLAND_SLEEPING=4;World.prototype.addConstraint=function(constraint){this.constraints.push(constraint)};World.prototype.addContactMaterial=function(contactMaterial){this.contactMaterials.push(contactMaterial)};World.prototype.removeContactMaterial=function(cm){var idx=this.contactMaterials.indexOf(cm);if(idx!==-1){Utils.splice(this.contactMaterials,idx,1)}};World.prototype.getContactMaterial=function(materialA,materialB){var cmats=this.contactMaterials;for(var i=0,N=cmats.length;i!==N;i++){var cm=cmats[i];if(cm.materialA.id===materialA.id&&cm.materialB.id===materialB.id||cm.materialA.id===materialB.id&&cm.materialB.id===materialA.id){return cm}}return false};World.prototype.removeConstraint=function(constraint){var idx=this.constraints.indexOf(constraint);if(idx!==-1){Utils.splice(this.constraints,idx,1)}};var step_r=vec2.create(),step_runit=vec2.create(),step_u=vec2.create(),step_f=vec2.create(),step_fhMinv=vec2.create(),step_velodt=vec2.create(),step_mg=vec2.create(),xiw=vec2.fromValues(0,0),xjw=vec2.fromValues(0,0),zero=vec2.fromValues(0,0),interpvelo=vec2.fromValues(0,0);World.prototype.step=function(dt,timeSinceLastCalled,maxSubSteps){maxSubSteps=maxSubSteps||10;timeSinceLastCalled=timeSinceLastCalled||0;if(timeSinceLastCalled===0){this.internalStep(dt);this.time+=dt}else{this.accumulator+=timeSinceLastCalled;var substeps=0;while(this.accumulator>=dt&&substeps<maxSubSteps){this.internalStep(dt);this.time+=dt;this.accumulator-=dt;substeps++}var t=this.accumulator%dt/dt;for(var j=0;j!==this.bodies.length;j++){var b=this.bodies[j];vec2.lerp(b.interpolatedPosition,b.previousPosition,b.position,t);b.interpolatedAngle=b.previousAngle+t*(b.angle-b.previousAngle)}}};var endOverlaps=[];World.prototype.internalStep=function(dt){this.stepping=true;var that=this,Nsprings=this.springs.length,springs=this.springs,bodies=this.bodies,g=this.gravity,solver=this.solver,Nbodies=this.bodies.length,broadphase=this.broadphase,np=this.narrowphase,constraints=this.constraints,t0,t1,fhMinv=step_fhMinv,velodt=step_velodt,mg=step_mg,scale=vec2.scale,add=vec2.add,rotate=vec2.rotate,islandManager=this.islandManager;this.overlapKeeper.tick();this.lastTimeStep=dt;if(this.useWorldGravityAsFrictionGravity){var gravityLen=vec2.length(this.gravity);if(!(gravityLen===0&&this.useFrictionGravityOnZeroGravity)){this.frictionGravity=gravityLen}}if(this.applyGravity){for(var i=0;i!==Nbodies;i++){var b=bodies[i],fi=b.force;if(b.type!==Body.DYNAMIC||b.sleepState===Body.SLEEPING){continue}vec2.scale(mg,g,b.mass*b.gravityScale);add(fi,fi,mg)}}if(this.applySpringForces){for(var i=0;i!==Nsprings;i++){var s=springs[i];s.applyForce()}}if(this.applyDamping){for(var i=0;i!==Nbodies;i++){var b=bodies[i];if(b.type===Body.DYNAMIC){b.applyDamping(dt)}}}var result=broadphase.getCollisionPairs(this);var ignoredPairs=this.disabledBodyCollisionPairs;for(var i=ignoredPairs.length-2;i>=0;i-=2){for(var j=result.length-2;j>=0;j-=2){if(ignoredPairs[i]===result[j]&&ignoredPairs[i+1]===result[j+1]||ignoredPairs[i+1]===result[j]&&ignoredPairs[i]===result[j+1]){result.splice(j,2)}}}var Nconstraints=constraints.length;for(i=0;i!==Nconstraints;i++){var c=constraints[i];if(!c.collideConnected){for(var j=result.length-2;j>=0;j-=2){if(c.bodyA===result[j]&&c.bodyB===result[j+1]||c.bodyB===result[j]&&c.bodyA===result[j+1]){result.splice(j,2)}}}}this.postBroadphaseEvent.pairs=result;this.emit(this.postBroadphaseEvent);this.postBroadphaseEvent.pairs=null;np.reset(this);for(var i=0,Nresults=result.length;i!==Nresults;i+=2){var bi=result[i],bj=result[i+1];for(var k=0,Nshapesi=bi.shapes.length;k!==Nshapesi;k++){var si=bi.shapes[k],xi=si.position,ai=si.angle;for(var l=0,Nshapesj=bj.shapes.length;l!==Nshapesj;l++){var sj=bj.shapes[l],xj=sj.position,aj=sj.angle;var cm=this.defaultContactMaterial;if(si.material&&sj.material){var tmp=this.getContactMaterial(si.material,sj.material);if(tmp){cm=tmp}}this.runNarrowphase(np,bi,si,xi,ai,bj,sj,xj,aj,cm,this.frictionGravity)}}}for(var i=0;i!==Nbodies;i++){var body=bodies[i];if(body._wakeUpAfterNarrowphase){body.wakeUp();body._wakeUpAfterNarrowphase=false}}if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(endOverlaps);var e=this.endContactEvent;var l=endOverlaps.length;while(l--){var data=endOverlaps[l];e.shapeA=data.shapeA;e.shapeB=data.shapeB;e.bodyA=data.bodyA;e.bodyB=data.bodyB;this.emit(e)}endOverlaps.length=0}var preSolveEvent=this.preSolveEvent;preSolveEvent.contactEquations=np.contactEquations;preSolveEvent.frictionEquations=np.frictionEquations;this.emit(preSolveEvent);preSolveEvent.contactEquations=preSolveEvent.frictionEquations=null;var Nconstraints=constraints.length;for(i=0;i!==Nconstraints;i++){constraints[i].update()}if(np.contactEquations.length||np.frictionEquations.length||Nconstraints){if(this.islandSplit){islandManager.equations.length=0;Utils.appendArray(islandManager.equations,np.contactEquations);Utils.appendArray(islandManager.equations,np.frictionEquations);for(i=0;i!==Nconstraints;i++){Utils.appendArray(islandManager.equations,constraints[i].equations)}islandManager.split(this);for(var i=0;i!==islandManager.islands.length;i++){var island=islandManager.islands[i];if(island.equations.length){solver.solveIsland(dt,island)}}}else{solver.addEquations(np.contactEquations);solver.addEquations(np.frictionEquations);for(i=0;i!==Nconstraints;i++){solver.addEquations(constraints[i].equations)}if(this.solveConstraints){solver.solve(dt,this)}solver.removeAllEquations()}}for(var i=0;i!==Nbodies;i++){var body=bodies[i];body.integrate(dt)}for(var i=0;i!==Nbodies;i++){bodies[i].setZeroForce()}if(this.emitImpactEvent&&this.has("impact")){var ev=this.impactEvent;for(var i=0;i!==np.contactEquations.length;i++){var eq=np.contactEquations[i];if(eq.firstImpact){ev.bodyA=eq.bodyA;ev.bodyB=eq.bodyB;ev.shapeA=eq.shapeA;ev.shapeB=eq.shapeB;ev.contactEquation=eq;this.emit(ev)}}}if(this.sleepMode===World.BODY_SLEEPING){for(i=0;i!==Nbodies;i++){bodies[i].sleepTick(this.time,false,dt)}}else if(this.sleepMode===World.ISLAND_SLEEPING&&this.islandSplit){for(i=0;i!==Nbodies;i++){bodies[i].sleepTick(this.time,true,dt)}for(var i=0;i<this.islandManager.islands.length;i++){var island=this.islandManager.islands[i];if(island.wantsToSleep()){island.sleep()}}}this.stepping=false;var bodiesToBeRemoved=this.bodiesToBeRemoved;for(var i=0;i!==bodiesToBeRemoved.length;i++){this.removeBody(bodiesToBeRemoved[i])}bodiesToBeRemoved.length=0;this.emit(this.postStepEvent)};World.prototype.runNarrowphase=function(np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen){if(!((si.collisionGroup&sj.collisionMask)!==0&&(sj.collisionGroup&si.collisionMask)!==0)){return}vec2.rotate(xiw,xi,bi.angle);vec2.rotate(xjw,xj,bj.angle);vec2.add(xiw,xiw,bi.position);vec2.add(xjw,xjw,bj.position);var aiw=ai+bi.angle;var ajw=aj+bj.angle;np.enableFriction=cm.friction>0;np.frictionCoefficient=cm.friction;var reducedMass;if(bi.type===Body.STATIC||bi.type===Body.KINEMATIC){reducedMass=bj.mass}else if(bj.type===Body.STATIC||bj.type===Body.KINEMATIC){reducedMass=bi.mass}else{reducedMass=bi.mass*bj.mass/(bi.mass+bj.mass)}np.slipForce=cm.friction*glen*reducedMass;np.restitution=cm.restitution;np.surfaceVelocity=cm.surfaceVelocity;np.frictionStiffness=cm.frictionStiffness;np.frictionRelaxation=cm.frictionRelaxation;np.stiffness=cm.stiffness;np.relaxation=cm.relaxation;np.contactSkinSize=cm.contactSkinSize;np.enabledEquations=bi.collisionResponse&&bj.collisionResponse&&si.collisionResponse&&sj.collisionResponse;var resolver=np[si.type|sj.type],numContacts=0;if(resolver){var sensor=si.sensor||sj.sensor;var numFrictionBefore=np.frictionEquations.length;if(si.type<sj.type){numContacts=resolver.call(np,bi,si,xiw,aiw,bj,sj,xjw,ajw,sensor)}else{numContacts=resolver.call(np,bj,sj,xjw,ajw,bi,si,xiw,aiw,sensor)}var numFrictionEquations=np.frictionEquations.length-numFrictionBefore;if(numContacts){if(bi.allowSleep&&bi.type===Body.DYNAMIC&&bi.sleepState===Body.SLEEPING&&bj.sleepState===Body.AWAKE&&bj.type!==Body.STATIC){var speedSquaredB=vec2.squaredLength(bj.velocity)+Math.pow(bj.angularVelocity,2);var speedLimitSquaredB=Math.pow(bj.sleepSpeedLimit,2);if(speedSquaredB>=speedLimitSquaredB*2){bi._wakeUpAfterNarrowphase=true}}if(bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&bi.sleepState===Body.AWAKE&&bi.type!==Body.STATIC){var speedSquaredA=vec2.squaredLength(bi.velocity)+Math.pow(bi.angularVelocity,2);var speedLimitSquaredA=Math.pow(bi.sleepSpeedLimit,2);if(speedSquaredA>=speedLimitSquaredA*2){bj._wakeUpAfterNarrowphase=true}}this.overlapKeeper.setOverlapping(bi,si,bj,sj);if(this.has("beginContact")&&this.overlapKeeper.isNewOverlap(si,sj)){var e=this.beginContactEvent;e.shapeA=si;e.shapeB=sj;e.bodyA=bi;e.bodyB=bj;e.contactEquations.length=0;if(typeof numContacts==="number"){for(var i=np.contactEquations.length-numContacts;i<np.contactEquations.length;i++){e.contactEquations.push(np.contactEquations[i])}}this.emit(e)}if(typeof numContacts==="number"&&numFrictionEquations>1){for(var i=np.frictionEquations.length-numFrictionEquations;i<np.frictionEquations.length;i++){var f=np.frictionEquations[i];f.setSlipForce(f.getSlipForce()/numFrictionEquations)}}}}};World.prototype.addSpring=function(spring){this.springs.push(spring);var evt=this.addSpringEvent;evt.spring=spring;this.emit(evt);evt.spring=null};World.prototype.removeSpring=function(spring){var idx=this.springs.indexOf(spring);if(idx!==-1){Utils.splice(this.springs,idx,1)}};World.prototype.addBody=function(body){if(this.bodies.indexOf(body)===-1){this.bodies.push(body);body.world=this;var evt=this.addBodyEvent;evt.body=body;this.emit(evt);evt.body=null}};World.prototype.removeBody=function(body){if(this.stepping){this.bodiesToBeRemoved.push(body)}else{body.world=null;var idx=this.bodies.indexOf(body);if(idx!==-1){Utils.splice(this.bodies,idx,1);this.removeBodyEvent.body=body;body.resetConstraintVelocity();this.emit(this.removeBodyEvent);this.removeBodyEvent.body=null}}};World.prototype.getBodyById=function(id){var bodies=this.bodies;for(var i=0;i<bodies.length;i++){var b=bodies[i];if(b.id===id){return b}}return false};World.prototype.disableBodyCollision=function(bodyA,bodyB){this.disabledBodyCollisionPairs.push(bodyA,bodyB)};World.prototype.enableBodyCollision=function(bodyA,bodyB){var pairs=this.disabledBodyCollisionPairs;for(var i=0;i<pairs.length;i+=2){if(pairs[i]===bodyA&&pairs[i+1]===bodyB||pairs[i+1]===bodyA&&pairs[i]===bodyB){pairs.splice(i,2);return}}};World.prototype.clear=function(){this.time=0;if(this.solver&&this.solver.equations.length){this.solver.removeAllEquations()}var cs=this.constraints;for(var i=cs.length-1;i>=0;i--){this.removeConstraint(cs[i])}var bodies=this.bodies;for(var i=bodies.length-1;i>=0;i--){this.removeBody(bodies[i])}var springs=this.springs;for(var i=springs.length-1;i>=0;i--){this.removeSpring(springs[i])}var cms=this.contactMaterials;for(var i=cms.length-1;i>=0;i--){this.removeContactMaterial(cms[i])}World.apply(this)};var hitTest_tmp1=vec2.create(),hitTest_zero=vec2.fromValues(0,0),hitTest_tmp2=vec2.fromValues(0,0);World.prototype.hitTest=function(worldPoint,bodies,precision){precision=precision||0;var pb=new Body({position:worldPoint}),ps=new Particle,px=worldPoint,pa=0,x=hitTest_tmp1,zero=hitTest_zero,tmp=hitTest_tmp2;pb.addShape(ps);var n=this.narrowphase,result=[];for(var i=0,N=bodies.length;i!==N;i++){var b=bodies[i];for(var j=0,NS=b.shapes.length;j!==NS;j++){var s=b.shapes[j];vec2.rotate(x,s.position,b.angle);vec2.add(x,x,b.position);var a=s.angle+b.angle;if(s instanceof Circle&&n.circleParticle(b,s,x,a,pb,ps,px,pa,true)||s instanceof Convex&&n.particleConvex(pb,ps,px,pa,b,s,x,a,true)||s instanceof Plane&&n.particlePlane(pb,ps,px,pa,b,s,x,a,true)||s instanceof Capsule&&n.particleCapsule(pb,ps,px,pa,b,s,x,a,true)||s instanceof Particle&&vec2.squaredLength(vec2.sub(tmp,x,worldPoint))<precision*precision){result.push(b)}}}return result};World.prototype.setGlobalStiffness=function(stiffness){var constraints=this.constraints;for(var i=0;i!==constraints.length;i++){var c=constraints[i];for(var j=0;j!==c.equations.length;j++){var eq=c.equations[j];eq.stiffness=stiffness;eq.needsUpdate=true}}var contactMaterials=this.contactMaterials;for(var i=0;i!==contactMaterials.length;i++){var c=contactMaterials[i];c.stiffness=c.frictionStiffness=stiffness}var c=this.defaultContactMaterial;c.stiffness=c.frictionStiffness=stiffness};World.prototype.setGlobalRelaxation=function(relaxation){for(var i=0;i!==this.constraints.length;i++){var c=this.constraints[i];for(var j=0;j!==c.equations.length;j++){var eq=c.equations[j];eq.relaxation=relaxation;eq.needsUpdate=true}}for(var i=0;i!==this.contactMaterials.length;i++){var c=this.contactMaterials[i];c.relaxation=c.frictionRelaxation=relaxation}var c=this.defaultContactMaterial;c.relaxation=c.frictionRelaxation=relaxation};var tmpAABB=new AABB;var tmpArray=[];World.prototype.raycast=function(result,ray){ray.getAABB(tmpAABB);this.broadphase.aabbQuery(this,tmpAABB,tmpArray);ray.intersectBodies(result,tmpArray);tmpArray.length=0;return result.hasHit()}},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":37,"../shapes/Circle":38,"../shapes/Convex":39,"../shapes/Line":41,"../shapes/Particle":42,"../shapes/Plane":43,"../shapes/Shape":44,"../solver/GSSolver":45,"../solver/Solver":46,"../utils/OverlapKeeper":51,"../utils/Utils":56,"./IslandManager":58}],p2:[function(require,module,exports){var p2=module.exports={AABB:require("./collision/AABB"),AngleLockEquation:require("./equations/AngleLockEquation"),Body:require("./objects/Body"),Broadphase:require("./collision/Broadphase"),Capsule:require("./shapes/Capsule"),Circle:require("./shapes/Circle"),Constraint:require("./constraints/Constraint"),ContactEquation:require("./equations/ContactEquation"),ContactEquationPool:require("./utils/ContactEquationPool"),ContactMaterial:require("./material/ContactMaterial"),Convex:require("./shapes/Convex"),DistanceConstraint:require("./constraints/DistanceConstraint"),Equation:require("./equations/Equation"),EventEmitter:require("./events/EventEmitter"),FrictionEquation:require("./equations/FrictionEquation"),FrictionEquationPool:require("./utils/FrictionEquationPool"),GearConstraint:require("./constraints/GearConstraint"),GSSolver:require("./solver/GSSolver"),Heightfield:require("./shapes/Heightfield"),Line:require("./shapes/Line"),LockConstraint:require("./constraints/LockConstraint"),Material:require("./material/Material"),Narrowphase:require("./collision/Narrowphase"),NaiveBroadphase:require("./collision/NaiveBroadphase"),Particle:require("./shapes/Particle"),Plane:require("./shapes/Plane"),Pool:require("./utils/Pool"),RevoluteConstraint:require("./constraints/RevoluteConstraint"),PrismaticConstraint:require("./constraints/PrismaticConstraint"),Ray:require("./collision/Ray"),RaycastResult:require("./collision/RaycastResult"),Box:require("./shapes/Box"),RotationalVelocityEquation:require("./equations/RotationalVelocityEquation"),SAPBroadphase:require("./collision/SAPBroadphase"),Shape:require("./shapes/Shape"),Solver:require("./solver/Solver"),Spring:require("./objects/Spring"),TopDownVehicle:require("./objects/TopDownVehicle"),LinearSpring:require("./objects/LinearSpring"),RotationalSpring:require("./objects/RotationalSpring"),Utils:require("./utils/Utils"),World:require("./world/World"),vec2:require("./math/vec2"),version:require("../package.json").version};Object.defineProperty(p2,"Rectangle",{get:function(){console.warn("The Rectangle class has been renamed to Box.");return this.Box}})},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":36,"./shapes/Capsule":37,"./shapes/Circle":38,"./shapes/Convex":39,"./shapes/Heightfield":40,"./shapes/Line":41,"./shapes/Particle":42,"./shapes/Plane":43,"./shapes/Shape":44,"./solver/GSSolver":45,"./solver/Solver":46,"./utils/ContactEquationPool":47,"./utils/FrictionEquationPool":48,"./utils/Pool":54,"./utils/Utils":56,"./world/World":60}]},{},[]);var e2d=require("e2d");var p2=require("p2");var r=e2d.Renderer.create(800,600);var cvs=e2d.Canvas.create(800,600);r.ready();r.on("frame",function(){if(!r.mouseData.clicked&&r.mouseData.state==="down"){cvs.render(e2d.moveTo(r.previousMouseData.x,r.previousMouseData.y),e2d.lineTo(r.mouseData.x,r.mouseData.y),e2d.stroke())}return r.render(e2d.clearRect(800,600),e2d.drawCanvas(cvs))})},0); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "requirebin-sketch", | |
"version": "1.0.0", | |
"dependencies": { | |
"e2d": "3.4.1", | |
"p2": "0.7.1" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- contents of this file will be placed inside the <body> --> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- contents of this file will be placed inside the <head> --> | |
<link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css"> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment